<commit_before>/**
 * Created by kgrube on 1/5/2016.
 */

/**
 * @private
 */
var Q = require('q'),
    request = require('request'),
    _ = require('lodash'),
    xml2js = require('xml2js').parseString;

/**
 * @typedef {object} PRTGFilter
 * @property {string} [filter_drel]         Only include records younger than this setting (for content='messages' and content='tickets' only).
 *                                          Possible values: today, yesterday, 7days, 30days, 12months, forever
 *
 * @property {string[]|string} [filter_status]    Only include sensors with a specific status (for content='sensors' only). Using multiple filter_status fields performs a logical OR.
 *                              See types PRTG.DEFAULTS.status.
 *
 * @property {string[]|string} [filter_tags]       Only include sensors with a specific tag (for content="sensors" only).
 *                                          Using multiple filter_tag fields performs a logical OR.
 *                                          Possible values: @tag(tagname)
 *
 * @property {string|string[]} [filter_xyz] filter_xyz where xyz is any column name used in the columns parameter;
 *                                          Substrings: use filter_xyz=@sub(substring1,substring2);
 *                                          Values not equal/above/below: use filter_xyz=@neq(value), filter_xyz=@above(value), filter_xyz=@below(value)
 *
 * @property {string} [sortby]              Sorts the data.  If this parameter is omitted, the table will be sorted based on the first column.  Add a leading '-' to reverse.
 *                                          Possible values: any column name used in the columns parameter.  (sortby=name, sortby=lastvalue, sortby=-lastvalue)
 */

/**
 * @typedef {object} Sensor
 * @property {string} name
 * @property {string} sensortype
 * @property {string} interval
 * @property {string} probename
 * @property {string} probegroupname
 * @property {string} parentdevicename
 * @property {string} parentdeviceid
 * @property {string} lastvalue
 * @property {string} lastmessage
 * @property {string} favorite
 * @property {string} statustext
 * @property {string} statusid
 * @property {string} lastup
 * @property {string} lastdown
 * @property {string} lastcheck
 * @property {string} uptime
 * @property {string} uptimetime
 * @property {string} downtime
 * @property {string} downtimetime
 * @property {string} updowntotal
 * @property {string} updownsince
 */

/**
 * @typedef {object} SensorColumns
 * @property {number} objid
 * @property {string} type
 * @property {string} name
 * @property tags
 * @property active
 * @property downtime
 * @property downtimetime
 * @property downtimesince
 * @property uptime
 * @property uptimetime
 * @property uptimesince
 * @property knowntime
 * @property cumsince
 * @property sensor
 * @property interval
 * @property lastcheck
 * @property lastup
 * @property lastdown
 * @property device
 * @property group
 * @property probe
 * @property grpdev
 * @property notifiesx
 * @property intervalx
 * @property access
 * @property dependency
 * @property probegroupdevice
 * @property status
 * @property message
 * @property priority
 * @property lastvalue
 * @property upsens
 * @property downsens
 * @property partialdownsens
 * @property warnsens
 * @property pausedsens
 * @property unusualsens
 * @property undefinedsens
 * @property totalsens
 * @property favorite
 * @property minigraph
 * @property comments
 * @property basetype ??
 * @property baselink ??
 * @property parentid ??
 *
 */

/**
 *
 * @param options
 * @param options.username
 * @param options.passhash
 * @param options.url Base URL of your PRTG installation, e.g. the API is accessible at <url>/API/
 * @constructor
 */
function PRTG(options) {
    if (!options) {
        throw "options must be defined.";
    }

    if (!options.username) {
        throw "options.username must be defined.";
    }

    if (!options.passhash) {
        throw "options.passhash must be defined.";
    }

    if (!options.url) {
        throw "options.url must be defined.";
    }

    this.auth = '&username=' + options.username + '&passhash=' + options.passhash;
    this.url = options.url;

    this.DEFAULTS = {};

    //PRTG uses different notations for these IDs all over the place
    this.DEFAULTS.status = {};
    this.DEFAULTS.status[1] = "Unknown";
    this.DEFAULTS.status[2] = "Scanning";
    this.DEFAULTS.status[3] = "Up";
    this.DEFAULTS.status[4] = "Warning";
    this.DEFAULTS.status[5] = "Down";
    this.DEFAULTS.status[6] = "No Probe";
    this.DEFAULTS.status[7] = "Paused by User";
    this.DEFAULTS.status[8] = "Paused by Dependency";
    this.DEFAULTS.status[9] = "Paused by Schedule";
    this.DEFAULTS.status[10] = "Unusual";
    this.DEFAULTS.status[11] = "Not Licensed";
    this.DEFAULTS.status[12] = "Paused Until";
    this.DEFAULTS.status[13] = "Down (Acknowledged)";
    this.DEFAULTS.status[14] = "Down (Partial)";
    this.DEFAULTS.status['Unknown'] = 1;
    this.DEFAULTS.status['Scanning'] = 2;
    this.DEFAULTS.status['Collecting'] = 2;
    this.DEFAULTS.status['Up'] = 3;
    this.DEFAULTS.status['Warning'] = 4;
    this.DEFAULTS.status['Down'] = 5;
    this.DEFAULTS.status['No Probe'] = 6;
    this.DEFAULTS.status['Paused by User'] = 7;
    this.DEFAULTS.status['PausedbyUser'] = 7;
    this.DEFAULTS.status['Paused by Dependency'] = 8;
    this.DEFAULTS.status['PausedbyDependency'] = 8;
    this.DEFAULTS.status['Paused by Schedule'] = 9;
    this.DEFAULTS.status['PausedbySchedule'] = 9;
    this.DEFAULTS.status['Unusual'] = 10;
    this.DEFAULTS.status['Not Licensed'] = 11;
    this.DEFAULTS.status['PausedbyLicense'] = 11;
    this.DEFAULTS.status['Paused Until'] = 12;
    this.DEFAULTS.status['PausedUntil'] = 12;
    this.DEFAULTS.status['Down (Acknowledged)'] = 13;
    this.DEFAULTS.status['DownAcknowledged'] = 13;
    this.DEFAULTS.status['Down (Partial)'] = 14;
    this.DEFAULTS.status['DownPartial'] = 14;

    this.DEFAULTS.httpCodes = {};
    this.DEFAULTS.httpCodes[200] = "OK";
    this.DEFAULTS.httpCodes[302] = "Found";
    this.DEFAULTS.httpCodes[400] = "Bad Request";
    this.DEFAULTS.httpCodes[401] = "Unauthorized";

}

/**
 *
 * @returns {{}|*}
 */
PRTG.prototype.getDefaults = function () {
    return this.DEFAULTS;
};

/**
 * Return opposite mapping for status to status id
 * @param str
 * @returns {string|number}
 */
PRTG.prototype.getStatus = function (str) {
    return this.DEFAULTS.status[str];
};

/**
 *
 * @param {string} path
 * @param {string|string[]} resultPath See https://lodash.com/docs#get
 * @param {function} [parse] parse function that uses signature of fn(string, callback) with callback of fn(err, result)
 * @returns {promise|object}
 */
PRTG.prototype.api = function (path, resultPath, parse) {
    var deferred = Q.defer();
    var self = this;

    var options = {
        url: this.url + path + this.auth
    };

    request(options, function (err, res, data) {
        if (err) {
            deferred.reject(err);
        } else if (res.statusCode != 200) {
            deferred.reject('Error: ' + self.getDefaults().httpCodes[res.statusCode]);
        } else if (res.statusCode === 200) {
            try {
                if (!parse) {
                    deferred.resolve(_.get(JSON.parse(data), resultPath));
                } else {
                    parse(data, function (err, res) {
                        if (!err) {
                            deferred.resolve(_.get(res, resultPath));
                        } else {
                            deferred.reject(err);
                        }
                    });
                }
            } catch (e) {
                deferred.reject(e);
            }
        }
    });

    return deferred.promise;
};

/**
 *
 * @param objid sensor's ID
 * @returns {*|promise|Sensor}
 */
PRTG.prototype.getSensor = function (objid) {
    return this.api('/api/getsensordetails.json?id=' + objid, 'sensordata');
};

/**
 *
 * @param objid
 * @param {string|string[]} [columns] Defaults to 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message'
 * @returns {*|promise|Sensor[]}
 */
PRTG.prototype.getDeviceSensors = function (objid, columns) {
    var path = '/api/table.json?content=sensors&output=json';

    if (columns) {
        if (_.isArray(columns)) {
            columns = columns.join(',');
        }
    } else {
        columns = 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message';
    }
    path += '&columns=' + columns;

    if (objid) {
        path += '&id=' + objid;
    }

    return this.api(path, 'sensors');
};

/**
 *
 * @param objid
 * @param property
 * @returns {promise|Object}
 */
PRTG.prototype.getObjectProperty = function (objid, property) {
    return this.api('/api/getobjectstatus.htm?id=' + objid + '&name=' + property + '&show=text', 'prtg.result', parseXML);
};

/**
 *
 * @param objid
 * @returns {*|promise|string}
 */
PRTG.prototype.getSensorStatusId = function (objid) {
    var deferred = Q.defer();

    this.getSensor(objid)
        .then(function (res) {
            deferred.resolve(res.statusid);
        })
        .fail(deferred.reject);

    return deferred.promise;
};

/**
 * @param objid
 * @returns {*|promise|string}
 */
PRTG.prototype.getDeviceStatusId = function (objid) {
    return this.getSensorStatusId(objid);
};

/**
 * @param columns
 * @param {PRTGFilter} [filter]
 * @param {string|number} [objid] filter set to this object (device/group/probe)
 * @returns {promise|Sensor[]}
 */
PRTG.prototype.getSensors = function (columns, filter, objid) {
    var path = '/api/table.json?content=sensors';

    if (columns) {
        if (_.isArray(columns)) {
            columns = columns.join(',');
        }
    } else {
        columns = 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message';
    }

    path += '&columns=' + columns;

    if (filter) {
        path += parameterize(filter);
    }

    if (objid) {
        path += '&id=' + objid;
    }

    return this.api(path, 'sensors');
};

PRTG.prototype.getDownOrAckSensors = function () {
    return this.getSensors(null, { filter_status: [this.DEFAULTS.status['Down'], this.DEFAULTS.status['DownAcknowledged']] });
};

/**
 *
 * @private
 * @param {string} str xml string to parse
 * @param {function} cb callback(err, res)
 */
function parseXML(str, cb) {
    xml2js(str, {
        emptyTag: null,
        ignoreAttrs: true,
        mergeAttrs: true,
        explicitArray: false,
        trim: true
    }, cb);
}

/**
 *
 * @param {PRTGFilter} filter
 * @returns {string}
 */
function parameterize(filter) {
    var params = [];

    for (var f in filter) {
        if (filter.hasOwnProperty(f)) {
            if (_.isArray(filter[f])) {
                for (var i = 0; i < filter[f].length; i++) {
                    params.push(f + '=' + filter[f][i]);
                }
            } else {
                params.push(f + '=' + filter[f])
            }
        }
    }

    return '&' + params.join('&');
}

module.exports = PRTG;
<commit_msg>convert statusids to strings for comparison from API<commit_after>/**
 * Created by kgrube on 1/5/2016.
 */

/**
 * @private
 */
var Q = require('q'),
    request = require('request'),
    _ = require('lodash'),
    xml2js = require('xml2js').parseString;

/**
 * @typedef {object} PRTGFilter
 * @property {string} [filter_drel]         Only include records younger than this setting (for content='messages' and content='tickets' only).
 *                                          Possible values: today, yesterday, 7days, 30days, 12months, forever
 *
 * @property {string[]|string} [filter_status]    Only include sensors with a specific status (for content='sensors' only). Using multiple filter_status fields performs a logical OR.
 *                              See types PRTG.DEFAULTS.status.
 *
 * @property {string[]|string} [filter_tags]       Only include sensors with a specific tag (for content="sensors" only).
 *                                          Using multiple filter_tag fields performs a logical OR.
 *                                          Possible values: @tag(tagname)
 *
 * @property {string|string[]} [filter_xyz] filter_xyz where xyz is any column name used in the columns parameter;
 *                                          Substrings: use filter_xyz=@sub(substring1,substring2);
 *                                          Values not equal/above/below: use filter_xyz=@neq(value), filter_xyz=@above(value), filter_xyz=@below(value)
 *
 * @property {string} [sortby]              Sorts the data.  If this parameter is omitted, the table will be sorted based on the first column.  Add a leading '-' to reverse.
 *                                          Possible values: any column name used in the columns parameter.  (sortby=name, sortby=lastvalue, sortby=-lastvalue)
 */

/**
 * @typedef {object} Sensor
 * @property {string} name
 * @property {string} sensortype
 * @property {string} interval
 * @property {string} probename
 * @property {string} probegroupname
 * @property {string} parentdevicename
 * @property {string} parentdeviceid
 * @property {string} lastvalue
 * @property {string} lastmessage
 * @property {string} favorite
 * @property {string} statustext
 * @property {string} statusid
 * @property {string} lastup
 * @property {string} lastdown
 * @property {string} lastcheck
 * @property {string} uptime
 * @property {string} uptimetime
 * @property {string} downtime
 * @property {string} downtimetime
 * @property {string} updowntotal
 * @property {string} updownsince
 */

/**
 * @typedef {object} SensorColumns
 * @property {number} objid
 * @property {string} type
 * @property {string} name
 * @property tags
 * @property active
 * @property downtime
 * @property downtimetime
 * @property downtimesince
 * @property uptime
 * @property uptimetime
 * @property uptimesince
 * @property knowntime
 * @property cumsince
 * @property sensor
 * @property interval
 * @property lastcheck
 * @property lastup
 * @property lastdown
 * @property device
 * @property group
 * @property probe
 * @property grpdev
 * @property notifiesx
 * @property intervalx
 * @property access
 * @property dependency
 * @property probegroupdevice
 * @property status
 * @property message
 * @property priority
 * @property lastvalue
 * @property upsens
 * @property downsens
 * @property partialdownsens
 * @property warnsens
 * @property pausedsens
 * @property unusualsens
 * @property undefinedsens
 * @property totalsens
 * @property favorite
 * @property minigraph
 * @property comments
 * @property basetype ??
 * @property baselink ??
 * @property parentid ??
 *
 */

/**
 *
 * @param options
 * @param options.username
 * @param options.passhash
 * @param options.url Base URL of your PRTG installation, e.g. the API is accessible at <url>/API/
 * @constructor
 */
function PRTG(options) {
    if (!options) {
        throw "options must be defined.";
    }

    if (!options.username) {
        throw "options.username must be defined.";
    }

    if (!options.passhash) {
        throw "options.passhash must be defined.";
    }

    if (!options.url) {
        throw "options.url must be defined.";
    }

    this.auth = '&username=' + options.username + '&passhash=' + options.passhash;
    this.url = options.url;

    this.DEFAULTS = {};

    //PRTG uses different notations for these IDs all over the place
    this.DEFAULTS.status = {};
    this.DEFAULTS.status['1'] = "Unknown";
    this.DEFAULTS.status['2'] = "Scanning";
    this.DEFAULTS.status['3'] = "Up";
    this.DEFAULTS.status['4'] = "Warning";
    this.DEFAULTS.status['5'] = "Down";
    this.DEFAULTS.status['6'] = "No Probe";
    this.DEFAULTS.status['7'] = "Paused by User";
    this.DEFAULTS.status['8'] = "Paused by Dependency";
    this.DEFAULTS.status['9'] = "Paused by Schedule";
    this.DEFAULTS.status['10'] = "Unusual";
    this.DEFAULTS.status['11'] = "Not Licensed";
    this.DEFAULTS.status['12'] = "Paused Until";
    this.DEFAULTS.status['13'] = "Down (Acknowledged)";
    this.DEFAULTS.status['14'] = "Down (Partial)";
    this.DEFAULTS.status['Unknown'] = '1';
    this.DEFAULTS.status['Scanning'] = '2';
    this.DEFAULTS.status['Collecting'] = '2';
    this.DEFAULTS.status['Up'] = '3';
    this.DEFAULTS.status['Warning'] = '4';
    this.DEFAULTS.status['Down'] = '5';
    this.DEFAULTS.status['No Probe'] = '6';
    this.DEFAULTS.status['Paused by User'] = '7';
    this.DEFAULTS.status['PausedbyUser'] = '7';
    this.DEFAULTS.status['Paused by Dependency'] = '8';
    this.DEFAULTS.status['PausedbyDependency'] = '8';
    this.DEFAULTS.status['Paused by Schedule'] = '9';
    this.DEFAULTS.status['PausedbySchedule'] = '9';
    this.DEFAULTS.status['Unusual'] = '10';
    this.DEFAULTS.status['Not Licensed'] = '11';
    this.DEFAULTS.status['PausedbyLicense'] = '11';
    this.DEFAULTS.status['Paused Until'] = '12';
    this.DEFAULTS.status['PausedUntil'] = '12';
    this.DEFAULTS.status['Down (Acknowledged)'] = '13';
    this.DEFAULTS.status['DownAcknowledged'] = '13';
    this.DEFAULTS.status['Down (Partial)'] = '14';
    this.DEFAULTS.status['DownPartial'] = '14';

    this.DEFAULTS.httpCodes = {};
    this.DEFAULTS.httpCodes[200] = "OK";
    this.DEFAULTS.httpCodes[302] = "Found";
    this.DEFAULTS.httpCodes[400] = "Bad Request";
    this.DEFAULTS.httpCodes[401] = "Unauthorized";

}

/**
 *
 * @returns {{}|*}
 */
PRTG.prototype.getDefaults = function () {
    return this.DEFAULTS;
};

/**
 * Return opposite mapping for status to status id
 * @param str
 * @returns {string|number}
 */
PRTG.prototype.getStatus = function (str) {
    return this.DEFAULTS.status[str];
};

/**
 *
 * @param {string} path
 * @param {string|string[]} resultPath See https://lodash.com/docs#get
 * @param {function} [parse] parse function that uses signature of fn(string, callback) with callback of fn(err, result)
 * @returns {promise|object}
 */
PRTG.prototype.api = function (path, resultPath, parse) {
    var deferred = Q.defer();
    var self = this;

    var options = {
        url: this.url + path + this.auth
    };

    request(options, function (err, res, data) {
        if (err) {
            deferred.reject(err);
        } else if (res.statusCode != 200) {
            deferred.reject('Error: ' + self.getDefaults().httpCodes[res.statusCode]);
        } else if (res.statusCode === 200) {
            try {
                if (!parse) {
                    deferred.resolve(_.get(JSON.parse(data), resultPath));
                } else {
                    parse(data, function (err, res) {
                        if (!err) {
                            deferred.resolve(_.get(res, resultPath));
                        } else {
                            deferred.reject(err);
                        }
                    });
                }
            } catch (e) {
                deferred.reject(e);
            }
        }
    });

    return deferred.promise;
};

/**
 *
 * @param objid sensor's ID
 * @returns {*|promise|Sensor}
 */
PRTG.prototype.getSensor = function (objid) {
    return this.api('/api/getsensordetails.json?id=' + objid, 'sensordata');
};

/**
 *
 * @param objid
 * @param {string|string[]} [columns] Defaults to 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message'
 * @returns {*|promise|Sensor[]}
 */
PRTG.prototype.getDeviceSensors = function (objid, columns) {
    var path = '/api/table.json?content=sensors&output=json';

    if (columns) {
        if (_.isArray(columns)) {
            columns = columns.join(',');
        }
    } else {
        columns = 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message';
    }
    path += '&columns=' + columns;

    if (objid) {
        path += '&id=' + objid;
    }

    return this.api(path, 'sensors');
};

/**
 *
 * @param objid
 * @param property
 * @returns {promise|Object}
 */
PRTG.prototype.getObjectProperty = function (objid, property) {
    return this.api('/api/getobjectstatus.htm?id=' + objid + '&name=' + property + '&show=text', 'prtg.result', parseXML);
};

/**
 *
 * @param objid
 * @returns {*|promise|string}
 */
PRTG.prototype.getSensorStatusId = function (objid) {
    var deferred = Q.defer();

    this.getSensor(objid)
        .then(function (res) {
            deferred.resolve(res.statusid);
        })
        .fail(deferred.reject);

    return deferred.promise;
};

/**
 * @param objid
 * @returns {*|promise|string}
 */
PRTG.prototype.getDeviceStatusId = function (objid) {
    return this.getSensorStatusId(objid);
};

/**
 * @param columns
 * @param {PRTGFilter} [filter]
 * @param {string|number} [objid] filter set to this object (device/group/probe)
 * @returns {promise|Sensor[]}
 */
PRTG.prototype.getSensors = function (columns, filter, objid) {
    var path = '/api/table.json?content=sensors';

    if (columns) {
        if (_.isArray(columns)) {
            columns = columns.join(',');
        }
    } else {
        columns = 'objid,probe,group,device,sensor,lastvalue,type,name,tags,active,status,grpdev,message';
    }

    path += '&columns=' + columns;

    if (filter) {
        path += parameterize(filter);
    }

    if (objid) {
        path += '&id=' + objid;
    }

    return this.api(path, 'sensors');
};

PRTG.prototype.getDownOrAckSensors = function () {
    return this.getSensors(null, { filter_status: [this.DEFAULTS.status['Down'], this.DEFAULTS.status['DownAcknowledged']] });
};

/**
 *
 * @private
 * @param {string} str xml string to parse
 * @param {function} cb callback(err, res)
 */
function parseXML(str, cb) {
    xml2js(str, {
        emptyTag: null,
        ignoreAttrs: true,
        mergeAttrs: true,
        explicitArray: false,
        trim: true
    }, cb);
}

/**
 *
 * @param {PRTGFilter} filter
 * @returns {string}
 */
function parameterize(filter) {
    var params = [];

    for (var f in filter) {
        if (filter.hasOwnProperty(f)) {
            if (_.isArray(filter[f])) {
                for (var i = 0; i < filter[f].length; i++) {
                    params.push(f + '=' + filter[f][i]);
                }
            } else {
                params.push(f + '=' + filter[f])
            }
        }
    }

    return '&' + params.join('&');
}

module.exports = PRTG;
<|endoftext|>


<commit_before>import { isPlainObject } from 'shared/util'

const vm = require('vm')
const path = require('path')
const resolve = require('resolve')
const NativeModule = require('module')

function createContext (context) {
  const sandbox = {
    Buffer,
    console,
    process,
    setTimeout,
    setInterval,
    setImmediate,
    clearTimeout,
    clearInterval,
    clearImmediate,
    __VUE_SSR_CONTEXT__: context
  }
  sandbox.global = sandbox
  return sandbox
}

function compileModule (files, basedir) {
  const compiledScripts = {}
  const resolvedModules = {}

  function getCompiledScript (filename) {
    if (compiledScripts[filename]) {
      return compiledScripts[filename]
    }
    const code = files[filename]
    const wrapper = NativeModule.wrap(code)
    const script = new vm.Script(wrapper, {
      filename,
      displayErrors: true
    })
    compiledScripts[filename] = script
    return script
  }

  function evaluateModule (filename, context, evaluatedFiles = {}) {
    if (evaluatedFiles[filename]) {
      return evaluatedFiles[filename]
    }

    const script = getCompiledScript(filename)
    const compiledWrapper = script.runInNewContext(context)
    const m = { exports: {}}
    const r = file => {
      file = path.join('.', file)
      if (files[file]) {
        return evaluateModule(file, context, evaluatedFiles)
      } else if (basedir) {
        return require(
          resolvedModules[file] ||
          (resolvedModules[file] = resolve.sync(file, { basedir }))
        )
      } else {
        return require(file)
      }
    }
    compiledWrapper.call(m.exports, m.exports, r, m)

    const res = Object.prototype.hasOwnProperty.call(m.exports, 'default')
      ? m.exports.default
      : m.exports
    evaluatedFiles[filename] = res
    return res
  }
  return evaluateModule
}

function deepClone (val) {
  if (isPlainObject(val)) {
    const res = {}
    for (const key in val) {
      res[key] = deepClone(val[key])
    }
    return res
  } else if (Array.isArray(val)) {
    return val.slice()
  } else {
    return val
  }
}

export function createBundleRunner (entry, files, basedir, runInNewContext) {
  const evaluate = compileModule(files, basedir)
  if (runInNewContext) {
    // new context mode: creates a fresh context and re-evaluate the bundle
    // on each render. Ensures entire application state is fresh for each
    // render, but incurs extra evaluation cost.
    return (userContext = {}) => new Promise(resolve => {
      userContext._registeredComponents = new Set()
      const res = evaluate(entry, createContext(userContext))
      resolve(typeof res === 'function' ? res(userContext) : res)
    })
  } else {
    // direct mode: instead of re-evaluating the whole bundle on
    // each render, it simply calls the exported function. This avoids the
    // module evaluation costs but requires the source code to be structured
    // slightly differently.

    // the initial context is only used for collecting possible non-component
    // styles injected by vue-style-loader.
    const initialContext = {}
    const sharedContext = createContext(initialContext)

    let runner // lazy creation so that errors can be caught by user
    return (userContext = {}) => new Promise(resolve => {
      if (!runner) {
        runner = evaluate(entry, sharedContext)
        // On subsequent renders, __VUE_SSR_CONTEXT__ will not be avaialbe
        // to prevent cross-request pollution.
        delete sharedContext.__VUE_SSR_CONTEXT__
        if (typeof runner !== 'function') {
          throw new Error(
            'bundle export should be a function when using ' +
            '{ runInNewContext: false }.'
          )
        }
      }
      userContext._registeredComponents = new Set()
      // vue-style-loader styles imported outside of component lifecycle hooks
      if (initialContext._styles) {
        userContext._styles = deepClone(initialContext._styles)
      }
      resolve(runner(userContext))
    })
  }
}
<commit_msg>run bundle in the same global context when runInNewContext is false (fix #5559)<commit_after>import { isPlainObject } from 'shared/util'

const vm = require('vm')
const path = require('path')
const resolve = require('resolve')
const NativeModule = require('module')

function createContext (context) {
  const sandbox = {
    Buffer,
    console,
    process,
    setTimeout,
    setInterval,
    setImmediate,
    clearTimeout,
    clearInterval,
    clearImmediate,
    __VUE_SSR_CONTEXT__: context
  }
  sandbox.global = sandbox
  return sandbox
}

function compileModule (files, basedir, runInNewContext) {
  const compiledScripts = {}
  const resolvedModules = {}

  function getCompiledScript (filename) {
    if (compiledScripts[filename]) {
      return compiledScripts[filename]
    }
    const code = files[filename]
    const wrapper = NativeModule.wrap(code)
    const script = new vm.Script(wrapper, {
      filename,
      displayErrors: true
    })
    compiledScripts[filename] = script
    return script
  }

  function evaluateModule (filename, context, evaluatedFiles = {}) {
    if (evaluatedFiles[filename]) {
      return evaluatedFiles[filename]
    }

    const script = getCompiledScript(filename)
    const compiledWrapper = runInNewContext
      ? script.runInNewContext(context)
      : script.runInThisContext()
    const m = { exports: {}}
    const r = file => {
      file = path.join('.', file)
      if (files[file]) {
        return evaluateModule(file, context, evaluatedFiles)
      } else if (basedir) {
        return require(
          resolvedModules[file] ||
          (resolvedModules[file] = resolve.sync(file, { basedir }))
        )
      } else {
        return require(file)
      }
    }
    compiledWrapper.call(m.exports, m.exports, r, m)

    const res = Object.prototype.hasOwnProperty.call(m.exports, 'default')
      ? m.exports.default
      : m.exports
    evaluatedFiles[filename] = res
    return res
  }
  return evaluateModule
}

function deepClone (val) {
  if (isPlainObject(val)) {
    const res = {}
    for (const key in val) {
      res[key] = deepClone(val[key])
    }
    return res
  } else if (Array.isArray(val)) {
    return val.slice()
  } else {
    return val
  }
}

export function createBundleRunner (entry, files, basedir, runInNewContext) {
  const evaluate = compileModule(files, basedir, runInNewContext)
  if (runInNewContext) {
    // new context mode: creates a fresh context and re-evaluate the bundle
    // on each render. Ensures entire application state is fresh for each
    // render, but incurs extra evaluation cost.
    return (userContext = {}) => new Promise(resolve => {
      userContext._registeredComponents = new Set()
      const res = evaluate(entry, createContext(userContext))
      resolve(typeof res === 'function' ? res(userContext) : res)
    })
  } else {
    // direct mode: instead of re-evaluating the whole bundle on
    // each render, it simply calls the exported function. This avoids the
    // module evaluation costs but requires the source code to be structured
    // slightly differently.
    let runner // lazy creation so that errors can be caught by user
    let initialContext
    return (userContext = {}) => new Promise(resolve => {
      if (!runner) {
        // the initial context is only used for collecting possible non-component
        // styles injected by vue-style-loader.
        initialContext = global.__VUE_SSR_CONTEXT__ = {}
        runner = evaluate(entry)
        // On subsequent renders, __VUE_SSR_CONTEXT__ will not be avaialbe
        // to prevent cross-request pollution.
        delete global.__VUE_SSR_CONTEXT__
        if (typeof runner !== 'function') {
          throw new Error(
            'bundle export should be a function when using ' +
            '{ runInNewContext: false }.'
          )
        }
      }
      userContext._registeredComponents = new Set()
      // vue-style-loader styles imported outside of component lifecycle hooks
      if (initialContext._styles) {
        userContext._styles = deepClone(initialContext._styles)
      }
      resolve(runner(userContext))
    })
  }
}
<|endoftext|>


<commit_before>/*
 *   Copyright 2015
 */

/**
 * Changes the locale of the cube
 */
var ChangeLocale = Backbone.View.extend({

    initialize: function (args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("changeLocale_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render", "show", "handleClick", "fetch_datasources");

        this.datasources = new Connections({}, { dialog: this });

        // Add change locale button to saiku toolbar
        this.add_button();
        this.workspace.toolbar.changeLocale = this.show;

        // Listen to adjust event and rerender
        this.workspace.bind('workspace:adjust', this.render);

        // Create locale screen
        this.localeOptionsScreen = $("
  " +
            "
" +
            "
         <button id='en_US' > English </button>
 " +
            "
   	    <button id='nl_BE' > Dutch </button>
 " +
            "
   	    <button id='fr_FR' > French </button>
" +
            "
" +
            "
 " +
            "
 Choose your language
")
        ;

        // attach event handler
        this.localeOptionsScreen.find('button').click(this.handleClick);

        //function for menu
        $("#nav ul ").css({display: "none"}); // Opera Fix
        $("#nav li").hover(function () {
            $(this).find('ul:first').css({visibility: "visible", display: "none"}).show(400);
        }, function () {
            $(this).find('ul:first').css({visibility: "hidden"});
        });

        // Append chart to workspace
        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide())
            .prepend(this.localeOptionsScreen.hide());

    },

    add_button: function () {
        var $chart_button =
            $('')
                .css({  'background-image': "url('js/saiku/plugins/ChangeLocale/images/change_locale.png')",
                    'background-repeat': 'no-repeat',
                    'background-position': '7px 7px'
                });

        var $chart_li = $('

').append($chart_button);
        $(this.workspace.toolbar.el).find("ul").append($chart_li);
    },

    show: function (event, ui) {
        $(this.workspace.table.el).toggle();
        $(this.el).toggle();
        $(this.localeOptionsScreen).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render();
        } else {
            this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
        }
    },

    fetch_datasources: function () {
        return true;
    },

    handleClick: function (event) {
        // Keep a reference to the main plugin object.
        var this_p = this;

        // get selected locale
        var newLocale = $(event.target).attr('id');

        // get current selected connection name (without URL data)
        selectedCube = $(".cubes option:selected").val();
        selectedConnectionName = selectedCube.substring(0, selectedCube.indexOf("/"));

        // Get all connections from back-end
        getUrl = Settings.REST_URL + "admin" + "/datasources";
        $.get(getUrl, function (data) {
            allConnections = data;
            // match
            selectedConnection = _.find(allConnections, function (connection) {
                return connection.connectionname == selectedConnectionName
            });

            selectedDataSource = new DataSource(selectedConnection);

            // change locale
            if (selectedConnection.advanced == null) {
                alert("Change the URL connection string to advanced");
            } else {
                referenceText = "locale=";
                start = selectedConnection.advanced.toLowerCase().indexOf(referenceText);
                start = start + referenceText.length;
                if (start == -1) {
                    alert("no locale defined in connection string of data source")
                }
                else {
                    end = selectedConnection.advanced.indexOf(";", start);
                    oldLocale = selectedConnection.advanced.substring(start, end);
                    selectedDataSource.set({"advanced": selectedConnection.advanced.replace(oldLocale, newLocale)});
                    // post update
                    this_p.saveDataSource(selectedDataSource);
                    // refresh datasources
                    Saiku.session.sessionworkspace.refresh()
                }
            }
        });
        return false;
    },

    saveDataSource: function (selectedDataSource) {
        selectedDataSource.save({}, {
                data: JSON.stringify(selectedDataSource.attributes),
                contentType: "application/json",
                success: function (model, respose, options) {
                    console.log("The model has been updated to the server");
                },
                error: function (model, xhr, options) {
                    console.log("Something went wrong while updating the model: " + xhr.responseText);
                }
            }
        );
    },

    render: function (chartOptions) {

    }
});

var DataSource = Backbone.Model.extend({
//    url: "admin/datasources",
    urlRoot: "admin/datasources",
    refresh: function () {
        $.ajax({
            type: 'GET',
            url: Settings.REST_URL + "admin" + "/datasources/" + this.get("connectionname") + "/refresh"
        });
    }
});

/**
 * Start Plugin
 */
Saiku.events.bind('session:new', function (session) {

    function new_workspace(args) {
        // Add stats element
        if (typeof args.workspace.changeLocale == "undefined") {
            args.workspace.changeLocale = new ChangeLocale({ workspace: args.workspace });
        }
    };

    function clear_workspace(args) {
        if (typeof args.workspace.changeLocale != "undefined") {
            $(args.workspace.changeLocale.localeOptionsScreen).hide();
            $(args.workspace.changeLocale.el).parents().find('.workspace_results table').show();
            $(args.workspace.changeLocale.el).hide();
        }
    };

    // Attach stats to existing tabs
    for (var i = 0; i < Saiku.tabs._tabs.length; i++) {
        var tab = Saiku.tabs._tabs[i];
        new_workspace({
            workspace: tab.content
        });
    }
    ;

    // Attach stats to future tabs
    Saiku.session.bind("workspace:new", new_workspace);
    Saiku.session.bind("workspace:clear", clear_workspace);
});
<commit_msg>ChangeLocale: add OSBI copyright<commit_after>/*
 *   Copyright 2015 OSBI
 */

/**
 * Changes the locale of the cube
 */
var ChangeLocale = Backbone.View.extend({

    initialize: function (args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("changeLocale_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render", "show", "handleClick", "fetch_datasources");

        this.datasources = new Connections({}, { dialog: this });

        // Add change locale button to saiku toolbar
        this.add_button();
        this.workspace.toolbar.changeLocale = this.show;

        // Listen to adjust event and rerender
        this.workspace.bind('workspace:adjust', this.render);

        // Create locale screen
        this.localeOptionsScreen = $("
  " +
            "
" +
            "
         <button id='en_US' > English </button>
 " +
            "
   	    <button id='nl_BE' > Dutch </button>
 " +
            "
   	    <button id='fr_FR' > French </button>
" +
            "
" +
            "
 " +
            "
 Choose your language
")
        ;

        // attach event handler
        this.localeOptionsScreen.find('button').click(this.handleClick);

        //function for menu
        $("#nav ul ").css({display: "none"}); // Opera Fix
        $("#nav li").hover(function () {
            $(this).find('ul:first').css({visibility: "visible", display: "none"}).show(400);
        }, function () {
            $(this).find('ul:first').css({visibility: "hidden"});
        });

        // Append chart to workspace
        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide())
            .prepend(this.localeOptionsScreen.hide());

    },

    add_button: function () {
        var $chart_button =
            $('')
                .css({  'background-image': "url('js/saiku/plugins/ChangeLocale/images/change_locale.png')",
                    'background-repeat': 'no-repeat',
                    'background-position': '7px 7px'
                });

        var $chart_li = $('

').append($chart_button);
        $(this.workspace.toolbar.el).find("ul").append($chart_li);
    },

    show: function (event, ui) {
        $(this.workspace.table.el).toggle();
        $(this.el).toggle();
        $(this.localeOptionsScreen).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render();
        } else {
            this.workspace.table.render({ data: this.workspace.query.result.lastresult() });
        }
    },

    fetch_datasources: function () {
        return true;
    },

    handleClick: function (event) {
        // Keep a reference to the main plugin object.
        var this_p = this;

        // get selected locale
        var newLocale = $(event.target).attr('id');

        // get current selected connection name (without URL data)
        selectedCube = $(".cubes option:selected").val();
        selectedConnectionName = selectedCube.substring(0, selectedCube.indexOf("/"));

        // Get all connections from back-end
        getUrl = Settings.REST_URL + "admin" + "/datasources";
        $.get(getUrl, function (data) {
            allConnections = data;
            // match
            selectedConnection = _.find(allConnections, function (connection) {
                return connection.connectionname == selectedConnectionName
            });

            selectedDataSource = new DataSource(selectedConnection);

            // change locale
            if (selectedConnection.advanced == null) {
                alert("Change the URL connection string to advanced");
            } else {
                referenceText = "locale=";
                start = selectedConnection.advanced.toLowerCase().indexOf(referenceText);
                start = start + referenceText.length;
                if (start == -1) {
                    alert("no locale defined in connection string of data source")
                }
                else {
                    end = selectedConnection.advanced.indexOf(";", start);
                    oldLocale = selectedConnection.advanced.substring(start, end);
                    selectedDataSource.set({"advanced": selectedConnection.advanced.replace(oldLocale, newLocale)});
                    // post update
                    this_p.saveDataSource(selectedDataSource);
                    // refresh datasources
                    Saiku.session.sessionworkspace.refresh()
                }
            }
        });
        return false;
    },

    saveDataSource: function (selectedDataSource) {
        selectedDataSource.save({}, {
                data: JSON.stringify(selectedDataSource.attributes),
                contentType: "application/json",
                success: function (model, respose, options) {
                    console.log("The model has been updated to the server");
                },
                error: function (model, xhr, options) {
                    console.log("Something went wrong while updating the model: " + xhr.responseText);
                }
            }
        );
    },

    render: function (chartOptions) {

    }
});

var DataSource = Backbone.Model.extend({
//    url: "admin/datasources",
    urlRoot: "admin/datasources",
    refresh: function () {
        $.ajax({
            type: 'GET',
            url: Settings.REST_URL + "admin" + "/datasources/" + this.get("connectionname") + "/refresh"
        });
    }
});

/**
 * Start Plugin
 */
Saiku.events.bind('session:new', function (session) {

    function new_workspace(args) {
        // Add stats element
        if (typeof args.workspace.changeLocale == "undefined") {
            args.workspace.changeLocale = new ChangeLocale({ workspace: args.workspace });
        }
    };

    function clear_workspace(args) {
        if (typeof args.workspace.changeLocale != "undefined") {
            $(args.workspace.changeLocale.localeOptionsScreen).hide();
            $(args.workspace.changeLocale.el).parents().find('.workspace_results table').show();
            $(args.workspace.changeLocale.el).hide();
        }
    };

    // Attach stats to existing tabs
    for (var i = 0; i < Saiku.tabs._tabs.length; i++) {
        var tab = Saiku.tabs._tabs[i];
        new_workspace({
            workspace: tab.content
        });
    }
    ;

    // Attach stats to future tabs
    Saiku.session.bind("workspace:new", new_workspace);
    Saiku.session.bind("workspace:clear", clear_workspace);
});
<|endoftext|>


<commit_before>const _ = require('lodash');
const Searcher = require('../Searcher.js');

class PickAnyTrait
{

    move(me, other, log){
        if (me.board.remaining.length == 1) {
          log('Answering: ' + me.board.remaining[0].name);
          return me.board.remaining[0].name;
        }
        log('Remaining: ' + me.board.remaining.length);
        var field = _(me.board.remaining).map((who) => Object.keys(who)).flatten().unique().shuffle().value()[0];
        var value = _(me.board.remaining).map((who) => who[field]).filter(value => value).shuffle().value()[0];
        log('Filtering on ' + field + ' = ' + value);
        return Searcher.where(field, value);
    }

}
module.exports = PickAnyTrait;

<commit_msg>Explainer<commit_after>const _ = require('lodash');
const Searcher = require('../Searcher.js');

/**
 * Chooses a field randomly from all the remaining characters,
 * then chooses a value randomly and returns a Searcher for
 * that field and value.
 *
 * But if there's only one character left, it just returns
 * their name.
 *
 * This strategy never guesses wrong, but it might lose if it
 * takes too long.
 */
class PickAnyTrait
{

    move(me, other, log){
        if (me.board.remaining.length == 1) {
          log('Answering: ' + me.board.remaining[0].name);
          return me.board.remaining[0].name;
        }
        log('Remaining: ' + me.board.remaining.length);
        var field = _(me.board.remaining).map((who) => Object.keys(who)).flatten().unique().shuffle().value()[0];
        var value = _(me.board.remaining).map((who) => who[field]).filter(value => value).shuffle().value()[0];
        log('Filtering on ' + field + ' = ' + value);
        return Searcher.where(field, value);
    }

}

module.exports = PickAnyTrait;
<|endoftext|>


<commit_before>var request = require('request');

var Redmine = function(config) {
    this.config = config;
    this.statuses = null;
    this.users = {};
    this.projects = {};
    this.mergeRequestField = null;

    this.clearCache = function(config) {
        this.statuses = null;
        this.users = {};
        this.projects = {};
        this.mergeRequestField = null;
    };

    this.getMergeRequestField = function(cb) {
        if(this.mergeRequestField) {
            cb(null, this.mergeRequestField);
        } else {
            //TODO
        }
    };

    this.getUser = function(name, cb) {
        if(name in this.users) {
            cb(null, this.users[name]);
        } else {
            var self = this;

            request.request({
                url: this.config.url + "/users.json",
                method: "GET",
                json: true,
                body: {
                    key: this.config.api_key,
                    name: name
                }
            }, function(err, res, body) {
                if(err) {
                    cb(err);
                } else {
                    //TODO
                }
            });
        }
    };

    this.getStatus = function(name, cb) {
        var key = name.toLowerCase();
        if(this.statuses == null) {
            request.request({
                url: this.config.url + "/issues_statuses.json",
                method: "GET",
                json: true,
                body: {
                    key: this.config.api_key
                }
            }, function(err, res, body) {
                if(err) {
                    cb(err);
                } else {
                    //TODO
                }
            });
        } else {
            if(key in this.statuses) {
                cb(null, this.statuses[key]);
            } else {
                cb("status does not exist");
            }
        }
    };

    this.getRedmineProject = function(name, cb) {
        if(name in this.projects) {
            cb(null, this.projects[name]);
        } else {
            //TODO
        }
    };

    this.updateIssue = function(id, body, impersonate) {
        //TODO
    };
};

<commit_msg>querying users, status, and custom fields works correctly<commit_after>var request = require('request');
var fs = require('fs');
var util = require('util');
var url = require('url');

function Redmine(config) {
    this.config = config;
    this.statuses = null;
    this.users = {};
    this.projects = {};
    this.mergeRequestField = null;
    this.request = null;

    if(config.ssl_ca) {
        this.request = request.defaults({
            agentOptions: {
                ca: fs.readFileSync(this.config.ssl_ca)
            },
            json: true
        });
    } else {
        this.request = request.defaults({
            json: true
        });
    }

    this.clearCache = function(config) {
        this.statuses = null;
        this.users = {};
        this.projects = {};
        this.mergeRequestField = null;
    };

    this.checkResponse = function(err, res, cb) {
        if(err) {
            cb(err);
            return false;
        } else if(res.statusCode != 200) {
            cb("http error code " + res.statusCode.toString());
            return false;
        } else {
            return true;
        }
    };

    this.getMergeRequestField = function(cb) {
        var self = this;

        var ret = function() {
            if(self.mergeRequestField) {
                cb(null, self.mergeRequestField);
            } else {
                cb("merge request field does not exist");
            }
        };

        if(this.mergeRequestField) {
            ret();
        } else {
            var self = this;

            this.request({
                url: url.resolve(this.config.url, "/custom_fields.json"),
                method: "GET",
                body: {
                    key: this.config.api_key
                }
            }, function(err, res, body) {
                if(self.checkResponse(err, res, cb)) {
                    for(var i in body.custom_fields) {
                        var field = body.custom_fields[i];
                        if(field.name.toLowerCase() == "merge request") {
                            self.mergeRequestField = field;
                            break;
                        }
                    }
                    ret();
                }
            });
        }
    };

    this.getUser = function(name, cb) {
        if(name in this.users) {
            cb(null, this.users[name]);
        } else {
            var self = this;

            this.request({
                url: url.resolve(this.config.url, "/users.json"),
                method: "GET",
                body: {
                    key: this.config.api_key,
                    name: name
                }
            }, function(err, res, body) {
                if(self.checkResponse(err, res, cb)) {
                    if(body.total_count == 0) {
                        cb("user does not exist");
                    } else {
                        self.users[name] = body.users[0];
                        cb(null, body.users[0]);
                    }
                }
            });
        }
    };

    this.getStatus = function(name, cb) {
        var key = name.toLowerCase();
        var self = this;

        var ret = function() {
            if(key in self.statuses) {
                cb(null, self.statuses[key]);
            } else {
                console.log(self.statuses);
                cb("status does not exist");
            }
        };

        if(this.statuses == null) {
            this.request({
                uri: url.resolve(this.config.url, "/issue_statuses.json"),
                method: "GET",
                body: {
                    key: this.config.api_key
                }
            }, function(err, res, body) {
                if(self.checkResponse(err, res, cb)) {
                    self.statuses = {};
                    for(var i in body.issue_statuses) {
                        var status = body.issue_statuses[i];
                        status.key = status.name.toLowerCase();
                        self.statuses[status.key] = status;
                    }
                    ret();
                }
            });
        } else {
            ret();
        }
    };

    this.getRedmineProject = function(name, cb) {
        if(name in this.projects) {
            cb(null, this.projects[name]);
        } else {
            //TODO
        }
    };

    this.updateIssue = function(id, body, impersonate) {
        var req = {
            url: url.resolve(this.config.url , "/issue/" + id + ".json"),
            method: "PUT",
            body: _.defaults({}, body, {key: this.config.api_key})
        };

        if(impersonate) {
            req.headers = {
                "X-Redmine-Switch-User": impersonate
            };
        }

        this.request(req, function(err, res, body) {
            if(this.checkResponse(err, res, cb)) {

            }
        });
    };
};

module.exports = Redmine;
<|endoftext|>


<commit_before>programs.push({
    name: "Reminders",
    initiate: function () {
        var rem = makeWindow("Remiders", 600, 700);
        var add_rem = function (text, ind) {
            var el = document.createElement("div");
            el.className = "reminderprg-rem";
            el.innerHTML = text;
            rem.content.insertBefore(el, rem.content.firstChild);
            var ar = JSON.parse(localStorage.remindersprg_items);
            el.id = "remindersprg-rem-" + (ind ? ind - 1 : ar.length) + "-win-" + windows.indexOf(rem);
            if(!ind) {
                ar.push(text);
            }
            localStorage.remindersprg_items = JSON.stringify(ar);
            el.onclick = function () {
                var ar = JSON.parse(localStorage.remindersprg_items);
                console.log(this.id.split("-win-")[0].substr(17));
                ar.splice(this.id.split("-win-")[0].substr(17), 1);
                localStorage.remindersprg_items = JSON.stringify(ar);
                this.parentElement.removeChild(this);
            };
        };
        var inf = document.createElement("div");
        inf.className = "reminderprg-rem add";
        var sp = document.createElement("span");
        sp.innerHTML = "Add a reminder...";
        var plus = UI.symbols("+");
        inf.appendChild(plus.elem);
        inf.appendChild(sp);
        rem.content.appendChild(inf);
        inf.onclick = function (e) {
            if(sp.contentEditable !== "true") {
                sp.innerHTML = "";
                sp.contentEditable = true;
                sp.focus();
            }
        };
        sp.onkeydown = function (e) {
            if(this.contentEditable === "true" && e.keyCode === 13) {
                add_rem(sp.innerHTML);
                sp.contentEditable = false;
                sp.innerHTML = "Add a reminder...";
            }
        };
        plus.elem.onclick = function (e) {
            if(sp.contentEditable === "true") {
                add_rem(sp.innerHTML);
                sp.contentEditable = false;
                sp.innerHTML = "Add a reminder...";
            }
        };
        if(!localStorage.remindersprg_items) localStorage.remindersprg_items = JSON.stringify([]);
        var dat = JSON.parse(localStorage.remindersprg_items);
        for(var i = 0; i < dat.length; i++) {
            add_rem(dat[i], i + 1);
        }
    }
});
<commit_msg>Update reminder.js<commit_after>programs.push({
    name: "Reminders",
    initiate: function () {
        var rem = makeWindow("Remiders", 600, 500);
        var add_rem = function (text, ind) {
            var el = document.createElement("div");
            el.className = "reminderprg-rem";
            el.innerHTML = text;
            rem.content.insertBefore(el, rem.content.firstChild);
            var ar = JSON.parse(localStorage.remindersprg_items);
            el.id = "remindersprg-rem-" + (ind ? ind - 1 : ar.length) + "-win-" + windows.indexOf(rem);
            if(!ind) {
                ar.push(text);
            }
            localStorage.remindersprg_items = JSON.stringify(ar);
            el.onclick = function () {
                var ar = JSON.parse(localStorage.remindersprg_items);
                console.log(this.id.split("-win-")[0].substr(17));
                ar.splice(this.id.split("-win-")[0].substr(17), 1);
                localStorage.remindersprg_items = JSON.stringify(ar);
                this.parentElement.removeChild(this);
            };
        };
        var inf = document.createElement("div");
        inf.className = "reminderprg-rem add";
        var sp = document.createElement("span");
        sp.innerHTML = "Add a reminder...";
        var plus = UI.symbols("+");
        inf.appendChild(plus.elem);
        inf.appendChild(sp);
        rem.content.appendChild(inf);
        inf.onclick = function (e) {
            if(sp.contentEditable !== "true") {
                sp.innerHTML = "";
                sp.contentEditable = true;
                sp.focus();
            }
        };
        sp.onkeydown = function (e) {
            if(this.contentEditable === "true" && e.keyCode === 13) {
                add_rem(sp.innerHTML);
                sp.contentEditable = false;
                sp.innerHTML = "Add a reminder...";
            }
        };
        plus.elem.onclick = function (e) {
            if(sp.contentEditable === "true") {
                add_rem(sp.innerHTML);
                sp.contentEditable = false;
                sp.innerHTML = "Add a reminder...";
            }
        };
        if(!localStorage.remindersprg_items) localStorage.remindersprg_items = JSON.stringify([]);
        var dat = JSON.parse(localStorage.remindersprg_items);
        for(var i = 0; i < dat.length; i++) {
            add_rem(dat[i], i + 1);
        }
    }
});
<|endoftext|>


<commit_before>import { AuthType, RequestMethod, KinveyRequest } from 'kinvey-node-sdk/dist/request';
import { Client } from 'kinvey-node-sdk/dist/client';
import { User } from 'kinvey-node-sdk/dist/entity';
import { isDefined } from 'kinvey-node-sdk/dist/utils';
import { KinveyError } from 'kinvey-node-sdk/dist/errors';
import Device from './device';
import { EventEmitter } from 'events';
import localStorage from 'local-storage';
import Promise from 'es6-promise';
import url from 'url';
const pushNamespace = process.env.KINVEY_PUSH_NAMESPACE || 'push';
const notificationEvent = process.env.KINVEY_NOTIFICATION_EVENT || 'notification';

class Push extends EventEmitter {
  get pathname() {
    return `/${pushNamespace}/${this.client.appKey}`;
  }

  get client() {
    if (!this._client) {
      return Client.sharedInstance();
    }

    return this._client;
  }

  set client(client) {
    if (!(client instanceof Client)) {
      throw new Error('client must be an instance of Client.');
    }

    this._client = client;
  }

  isSupported() {
    return Device.isPhoneGap() && (Device.isiOS() || Device.isAndroid());
  }

  onNotification(listener) {
    return this.on(notificationEvent, listener);
  }

  onceNotification(listener) {
    return this.once(notificationEvent, listener);
  }

  register(options = {}) {
    return Device.ready()
      .then(() => {
        if (this.isSupported() === false) {
          throw new KinveyError('Kinvey currently only supports push notifications on iOS and Android platforms.');
        }

        if (isDefined(global.device) === false) {
          throw new KinveyError('Cordova Device Plugin is not installed.',
            'Please refer to http://devcenter.kinvey.com/phonegap/guides/push#ProjectSetUp for help with'
            + ' setting up your project.');
        }

        if (isDefined(global.PushNotification) === false) {
          throw new KinveyError('PhoneGap Push Notification Plugin is not installed.',
            'Please refer to http://devcenter.kinvey.com/phonegap/guides/push#ProjectSetUp for help with'
            + ' setting up your project.');
        }

        return this.unregister(options)
          .catch(() => null);
      })
      .then(() => {
        return new Promise((resolve, reject) => {
          this.phonegapPush = global.PushNotification.init(options);

          this.phonegapPush.on(notificationEvent, (data) => {
            this.emit(notificationEvent, data);
          });

          this.phonegapPush.on('registration', (data) => {
            resolve(data.registrationId);
          });

          this.phonegapPush.on('error', (error) => {
            reject(new KinveyError('An error occurred registering this device for push notifications.', error));
          });
        });
      })
      .then((deviceId) => {
        if (isDefined(deviceId) === false) {
          throw new KinveyError('Unable to retrieve the device id to register this device for push notifications.');
        }

        const user = User.getActiveUser(this.client);
        const request = new KinveyRequest({
          method: RequestMethod.POST,
          url: url.format({
            protocol: this.client.protocol,
            host: this.client.host,
            pathname: `${this.pathname}/register-device`
          }),
          properties: options.properties,
          authType: user ? AuthType.Session : AuthType.Master,
          data: {
            platform: global.device.platform.toLowerCase(),
            framework: 'phonegap',
            deviceId: deviceId,
            userId: user ? undefined : options.userId
          },
          timeout: options.timeout,
          client: this.client
        });
        return request.execute()
          .then(response => response.data)
          .then((data) => {
            const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
            localStorage.set(key, { deviceId: deviceId });
            return data;
          });
      });
  }

  unregister(options = {}) {
    return Device.ready()
      .then(() => {
        if (this.isSupported() === false) {
          return null;
        }

        return new Promise((resolve) => {
          if (this.phonegapPush) {
            return this.phonegapPush.unregister(() => {
              this.phonegapPush = null;
              resolve();
            }, () => {
              resolve();
            });
          }

          return resolve();
        });
      })
      .then(() => {
        const user = User.getActiveUser(this.client);
        const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
        return localStorage.get(key);
      })
      .then((pushConfig) => {
        let deviceId;

        if (isDefined(pushConfig)) {
          deviceId = pushConfig.deviceId;
        }

        if (isDefined(deviceId) === false) {
          return null;
        }

        const user = User.getActiveUser(this.client);
        const request = new KinveyRequest({
          method: RequestMethod.POST,
          url: url.format({
            protocol: this.client.protocol,
            host: this.client.host,
            pathname: `${this.pathname}/unregister-device`
          }),
          properties: options.properties,
          authType: user ? AuthType.Session : AuthType.Master,
          data: {
            platform: global.device.platform.toLowerCase(),
            framework: 'phonegap',
            deviceId: deviceId,
            userId: user ? undefined : options.userId
          },
          timeout: options.timeout,
          client: this.client
        });
        return request.execute()
          .then(response => response.data);
      })
      .then((data) => {
        const user = User.getActiveUser(this.client);
        const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
        localStorage.remove(key);
        return data;
      });
  }
}

// Export
export { Push };
export default new Push();
<commit_msg>MLIBZ-161 Don't unregister before registering for push<commit_after>import { AuthType, RequestMethod, KinveyRequest } from 'kinvey-node-sdk/dist/request';
import { Client } from 'kinvey-node-sdk/dist/client';
import { User } from 'kinvey-node-sdk/dist/entity';
import { isDefined } from 'kinvey-node-sdk/dist/utils';
import { KinveyError } from 'kinvey-node-sdk/dist/errors';
import Device from './device';
import { EventEmitter } from 'events';
import localStorage from 'local-storage';
import Promise from 'es6-promise';
import url from 'url';
const PUSH_NAMESPACE = process.env.KINVEY_PUSH_NAMESPACE || 'push';
const NOTIFICATION_EVENT = process.env.KINVEY_NOTIFICATION_EVENT || 'notification';

class Push extends EventEmitter {
  get pathname() {
    return `/${PUSH_NAMESPACE}/${this.client.appKey}`;
  }

  get client() {
    if (!this._client) {
      return Client.sharedInstance();
    }

    return this._client;
  }

  set client(client) {
    if (!(client instanceof Client)) {
      throw new Error('client must be an instance of Client.');
    }

    this._client = client;
  }

  isSupported() {
    return Device.isPhoneGap() && (Device.isiOS() || Device.isAndroid());
  }

  onNotification(listener) {
    return this.on(NOTIFICATION_EVENT, listener);
  }

  onceNotification(listener) {
    return this.once(NOTIFICATION_EVENT, listener);
  }

  register(options = {}) {
    return Device.ready()
      .then(() => {
        if (this.isSupported() === false) {
          throw new KinveyError('Kinvey currently only supports push notifications on iOS and Android platforms.');
        }

        if (isDefined(global.device) === false) {
          throw new KinveyError('Cordova Device Plugin is not installed.',
            'Please refer to http://devcenter.kinvey.com/phonegap/guides/push#ProjectSetUp for help with'
            + ' setting up your project.');
        }

        if (isDefined(global.PushNotification) === false) {
          throw new KinveyError('PhoneGap Push Notification Plugin is not installed.',
            'Please refer to http://devcenter.kinvey.com/phonegap/guides/push#ProjectSetUp for help with'
            + ' setting up your project.');
        }

        return new Promise((resolve, reject) => {
          this.phonegapPush = global.PushNotification.init(options);

          this.phonegapPush.on(NOTIFICATION_EVENT, (data) => {
            this.emit(NOTIFICATION_EVENT, data);
          });

          this.phonegapPush.on('registration', (data) => {
            resolve(data.registrationId);
          });

          this.phonegapPush.on('error', (error) => {
            reject(new KinveyError('An error occurred registering this device for push notifications.', error));
          });
        });
      })
      .then((deviceId) => {
        if (isDefined(deviceId) === false) {
          throw new KinveyError('Unable to retrieve the device id to register this device for push notifications.');
        }

        const user = User.getActiveUser(this.client);
        const request = new KinveyRequest({
          method: RequestMethod.POST,
          url: url.format({
            protocol: this.client.protocol,
            host: this.client.host,
            pathname: `${this.pathname}/register-device`
          }),
          properties: options.properties,
          authType: user ? AuthType.Session : AuthType.Master,
          data: {
            platform: global.device.platform.toLowerCase(),
            framework: 'phonegap',
            deviceId: deviceId,
            userId: user ? undefined : options.userId
          },
          timeout: options.timeout,
          client: this.client
        });
        return request.execute()
          .then(response => response.data)
          .then((data) => {
            const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
            localStorage.set(key, { deviceId: deviceId });
            return data;
          });
      });
  }

  unregister(options = {}) {
    return Device.ready()
      .then(() => {
        if (this.isSupported() === false) {
          return null;
        }

        return new Promise((resolve) => {
          if (this.phonegapPush) {
            return this.phonegapPush.unregister(() => {
              this.phonegapPush = null;
              resolve();
            }, () => {
              resolve();
            });
          }

          return resolve();
        });
      })
      .then(() => {
        const user = User.getActiveUser(this.client);
        const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
        return localStorage.get(key);
      })
      .then((pushConfig) => {
        let deviceId;

        if (isDefined(pushConfig)) {
          deviceId = pushConfig.deviceId;
        }

        if (isDefined(deviceId) === false) {
          return null;
        }

        const user = User.getActiveUser(this.client);
        const request = new KinveyRequest({
          method: RequestMethod.POST,
          url: url.format({
            protocol: this.client.protocol,
            host: this.client.host,
            pathname: `${this.pathname}/unregister-device`
          }),
          properties: options.properties,
          authType: user ? AuthType.Session : AuthType.Master,
          data: {
            platform: global.device.platform.toLowerCase(),
            framework: 'phonegap',
            deviceId: deviceId,
            userId: user ? undefined : options.userId
          },
          timeout: options.timeout,
          client: this.client
        });
        return request.execute()
          .then(response => response.data);
      })
      .then((data) => {
        const user = User.getActiveUser(this.client);
        const key = user ? `${this.pathname}_${user._id}` : `${this.pathname}_${options.userId}`;
        localStorage.remove(key);
        return data;
      });
  }
}

// Export
export { Push };
export default new Push();
<|endoftext|>


<commit_before>#!/usr/bin/env node
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed 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.
'use strict';

// This package inspired by
// https://github.com/angular/clang-format/blob/master/index.js
const fs = require('fs');
const os = require('os');
const path = require('path');
const spawn = require('child_process').spawn;

function main(args) {
  const arch = {
    'x64': 'amd64',
  }[os.arch()];
  // Filter the platform based on the platforms that are build/included.
  const platform = {
    'darwin': 'darwin',
    'linux': 'linux',
    'windows': 'windows',
  }[os.platform()];

  if (arch == undefined || platform == undefined) {
    console.error(`FATAL: Your platform/architecture combination ${
        os.platform() - os.arch()} is not yet supported.
    Follow install instructions at https://github.com/bazelbuild/bazel-watcher/blob/master/README.md to compile for your system.`);
    return Promise.resolve(1);
  }

  // By default, use the ibazel binary underneath this script
  var basePath = __dirname;

  const dirs = process.cwd().split(path.sep);

  // Walk up the cwd, looking for a local ibazel installation
  for (var i = dirs.length; i > 0; i--) {
    var attemptedBasePath = [...dirs.slice(0, i), 'node_modules', '@bazel', 'ibazel'].join(path.sep);

    // If we find a local installation, use that one instead
    if (fs.existsSync(path.join(attemptedBasePath, 'bin', `${platform}_${arch}`, 'ibazel'))) {
      basePath = attemptedBasePath;
      break;
    }
  }
  if (basePath === __dirname) {
    console.error(`WARNING: no ibazel version found in your node_modules.
        We recommend installing a devDependency on ibazel so you use the same
        version as other engineers on this project.
        Using the globally installed version at ${__dirname}`);
  }

  const binary = path.join(basePath, 'bin', `${platform}_${arch}`, 'ibazel');
  const ibazel = spawn(binary, args, {stdio: 'inherit'});

  function shutdown() {
    ibazel.kill("SIGTERM")
    process.exit();
  }

  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);

  ibazel.on('close', e => process.exitCode = e);
}

if (require.main === module) {
  main(process.argv.slice(2));
}
<commit_msg>Fix npm warning logic (#185)<commit_after>#!/usr/bin/env node
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed 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.
'use strict';

// This package inspired by
// https://github.com/angular/clang-format/blob/master/index.js
const fs = require('fs');
const os = require('os');
const path = require('path');
const spawn = require('child_process').spawn;

function main(args) {
  const arch = {
    'x64': 'amd64',
  }[os.arch()];
  // Filter the platform based on the platforms that are build/included.
  const platform = {
    'darwin': 'darwin',
    'linux': 'linux',
    'windows': 'windows',
  }[os.platform()];

  if (arch == undefined || platform == undefined) {
    console.error(`FATAL: Your platform/architecture combination ${
        os.platform() - os.arch()} is not yet supported.
    Follow install instructions at https://github.com/bazelbuild/bazel-watcher/blob/master/README.md to compile for your system.`);
    return Promise.resolve(1);
  }

  // By default, use the ibazel binary underneath this script
  var basePath = __dirname;
  var foundLocalInstallation = false;

  const dirs = process.cwd().split(path.sep);

  // Walk up the cwd, looking for a local ibazel installation
  for (var i = dirs.length; i > 0; i--) {
    var attemptedBasePath = [...dirs.slice(0, i), 'node_modules', '@bazel', 'ibazel'].join(path.sep);

    // If we find a local installation, use that one instead
    if (fs.existsSync(path.join(attemptedBasePath, 'bin', `${platform}_${arch}`, 'ibazel'))) {
      basePath = attemptedBasePath;
      foundLocalInstallation = true;
      break;
    }
  }

  if (!foundLocalInstallation) {
    console.error(`WARNING: no ibazel version found in your node_modules.
        We recommend installing a devDependency on ibazel so you use the same
        version as other engineers on this project.
        Using the globally installed version at ${__dirname}`);
  }

  const binary = path.join(basePath, 'bin', `${platform}_${arch}`, 'ibazel');
  const ibazel = spawn(binary, args, {stdio: 'inherit'});

  function shutdown() {
    ibazel.kill("SIGTERM")
    process.exit();
  }

  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);

  ibazel.on('close', e => process.exitCode = e);
}

if (require.main === module) {
  main(process.argv.slice(2));
}
<|endoftext|>


<commit_before>Effect.Mutate = function(from, into){
	from = $(from);
	from.insert({before: $(into) || into});

	into = from.previous();

	var style,
		fromWidth	= from.getWidth(),
		fromHeight	= from.getHeight(),
		intoWidth	= into.getWidth(),
		intoHeight	= into.getHeight();

	if (fromWidth != intoWidth)		style += 'width: ' + intoWidth + 'px; ';
	if (fromHeight != intoHeight)	style += 'height: ' + intoHeight + 'px; ';

	return new Effect.Parallel([
		new Effect.Morph(from, {sync: true, style: style + 'opacity: 0.0;'}),
		new Effect.Morph(into, {sync: true, style: style + 'opacity: 1.0;'})
	], Object.extend({
		beforeStartInternal: function(){
			from.absolutize();
			from.makeClipping();

			into.setStyle({width: fromWidth + 'px', height: intoWidth + 'px' });
			into.makeClipping();
			into.setOpacity(0.0);
			into.show();
		},
		afterFinishInternal: function(e){
			into.undoClipping();
			into.style.width = null;
			into.style.height = null;
			into = null;

			if (e.options.repace){
				from.remove();
				from = null;
				return;
			}

			from.relativize();
			from.undoClipping();
			from.style.width = null;
			from.style.height = null;
			from.hide();
		}
	}, arguments[2] || {}));
};

Effect.FadeBlind = function(element){
	return new Effect.Parallel([Effect.BlindUp(element, {sync: true}), Effect.Fade(element, {sync: true})], arguments[1] || {});
};
Effect.AppearBlind = function(element){
	return new Effect.Parallel([Effect.BlindDown(element, {sync: true}), Effect.Appear(element, {sync: true})], arguments[1] || {});
};

// enable Effect.toggle(element, 'fading_blind');
Effect.PAIRS['fading_blind'] = ['AppearBlind', 'FadeBlind'];

Element.addMethods({
	fadeBlind: function(element, options){
		element = $(element);
		Effect.FadeBlind(element, options);
		return element;
	},
	appearBlind: function(element, options){
		element = $(element);
		Effect.AppearBlind(element, options);
		return element;
	},
	mutateTo: function(element, into, options){
		element = $(element)
		Effect.Mutate(element, into, options)
		return element;
	},
	removeWithEffect: function(element, effect, options){
		element = $(element);
		options = options || {};

		options.afterFinish = 'afterFinish' in options ?
			options.afterFinish.wrap(function(callback, e){ callback(e); element.remove(); }) :
			function(){ element.remove(); };

		effect = effect.camelize();
		effect = effect.charAt(0).toUpperCase() + effect.substring(1);
		effect = Effect[effect];

		if (effect.prototype.initialize){
			new effect(element, options);
		} else {
			effect(element, options);
		}

		return element;
	}
});
<commit_msg>bug fixing<commit_after>Effect.Mutate = function(from, into){
	from = $(from);
	from.insert({after: $(into) || into});

	into = from.next();

	var style		= '',
		fromWidth	= from.getWidth(),
		fromHeight	= from.getHeight(),
		intoWidth	= into.getWidth(),
		intoHeight	= into.getHeight();

	if (fromWidth != intoWidth)		style += 'width: ' + intoWidth + 'px; ';
	if (fromHeight != intoHeight)	style += 'height: ' + intoHeight + 'px; ';

	return new Effect.Parallel([
		new Effect.Morph(from, {sync: true, style: style + 'opacity: 0.0;'}),
		new Effect.Morph(into, {sync: true, style: style + 'opacity: 1.0;'})
	], Object.extend({
		beforeStartInternal: function(){
			from.absolutize();
			from.makeClipping();

			into.setStyle({width: fromWidth + 'px', height: fromHeight + 'px' });
			into.makeClipping();
			into.setOpacity(0.0);
			into.show();
		},
		afterFinishInternal: function(e){
			into.undoClipping();
			into.style.width = null;
			into.style.height = null;
			into = null;

			if (e.options.replace){
				from.remove();
				from = null;
				return;
			}

			from.relativize();
			from.undoClipping();
			from.style.width = null;
			from.style.height = null;
			from.hide();
		}
	}, arguments[2] || {}));
};

Effect.FadeBlind = function(element){
	return new Effect.Parallel([Effect.BlindUp(element, {sync: true}), Effect.Fade(element, {sync: true})], arguments[1] || {});
};
Effect.AppearBlind = function(element){
	return new Effect.Parallel([Effect.BlindDown(element, {sync: true}), Effect.Appear(element, {sync: true})], arguments[1] || {});
};

// enable Effect.toggle(element, 'fading_blind');
Effect.PAIRS['fading_blind'] = ['AppearBlind', 'FadeBlind'];

Element.addMethods({
	fadeBlind: function(element, options){
		element = $(element);
		Effect.FadeBlind(element, options);
		return element;
	},
	appearBlind: function(element, options){
		element = $(element);
		Effect.AppearBlind(element, options);
		return element;
	},
	mutateTo: function(element, into, options){
		element = $(element)
		Effect.Mutate(element, into, options)
		return element;
	},
	removeWithEffect: function(element, effect, options){
		element = $(element);
		options = options || {};

		options.afterFinish = 'afterFinish' in options ?
			options.afterFinish.wrap(function(callback, e){ callback(e); element.remove(); }) :
			function(){ element.remove(); };

		effect = effect.camelize();
		effect = effect.charAt(0).toUpperCase() + effect.substring(1);
		effect = Effect[effect];

		if (effect.prototype.initialize){
			new effect(element, options);
		} else {
			effect(element, options);
		}

		return element;
	}
});
<|endoftext|>


<commit_before>/// <reference path="../lib/jquery-2.1.1.min.js" />
/// <reference path="../lib/qunit-git.js" />

/*
 * This file is part of "ZenQuery", (c) Kenshin Himura, 2013.
 *
 * "ZenQuery" is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * "ZenQuery" is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with "ZenQuery".  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function (window) {
    var ZenQuery,
        config,
        hasOwn = Object.prototype.hasOwnProperty;
    ZenQuery = {
        //Renders a given zen coding string as html
        render: function (string) {
            if (arguments.length != 1)
                throw new Error('Incorrect Number of Arguments');
            if (typeof string == 'undefined' || string == null || (typeof string != 'string' && !(string instanceof String)))
                throw new Error('Invalid Arguments');
            //If no element, make div the default element
            var element = string.match(/^[a-z-]+/);
            if (!element)
                element = 'div';
            var classes = string.match(/\.[a-z-]+/g);
            if (classes && classes.length > 0)
                classes = ' class="' + classes.join(' ').replace(/\./g, '') + '"';
            var id = string.match(/#[a-z-]+/);
            if (id && id.length > 0)
                id = ' id="' + id.join('').replace('#', '') + '"';
            var prefix = '<' + element;
            if (id && id.length > 0)
                prefix += id;
            if (classes && classes.length > 0)
                prefix += classes;
            prefix += '>';
            var suffix = '</' + element + '>';
            var html = prefix + suffix;
            return html;
        },
    };

    // We use the prototype to distinguish between properties that should
    // be exposed as globals (and in exports) and those that shouldn't
    (function () {
        function F() { };
        F.prototype = ZenQuery;
        ZenQuery = new F();

        // Make F QUnit's constructor so that we can add to the prototype later
        ZenQuery.constructor = F;
    }());

    //Extend
    function extend(a, b) {
        for (var prop in b) {
            if (hasOwn.call(b, prop)) {
                // Avoid "Member not found" error in IE8 caused by messing with window.constructor
                if (!(prop === "constructor" && a === window)) {
                    if (b[prop] === undefined) {
                        delete a[prop];
                    } else {
                        a[prop] = b[prop];
                    }
                }
            }
        }
        return a;
    }

    //Config
    config = {
        symbols: ['#', '.'],
    };

    //Add config to ZenQUery
    extend(ZenQuery, { config: config });

    // For browser, export only select globals
    if (typeof window !== "undefined" && window != null) {
        (function() {
            var i,
                l,
                keys = [
                ];
            for (i = 0, l = keys.length; i < l; i++) {
                window[keys[i]] = QUnit[keys[i]];
            }
        })();
        window.ZenQuery = ZenQuery;
    }

    // Get a reference to the global object, like window in browsers
}((function () {
    return this;
})()));
<commit_msg>Added some helpers<commit_after>/// <reference path="../lib/jquery-2.1.1.min.js" />
/// <reference path="../lib/qunit-git.js" />

/*
 * This file is part of "ZenQuery", (c) Kenshin Himura, 2013.
 *
 * "ZenQuery" is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * "ZenQuery" is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with "ZenQuery".  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function (window) {
    var ZenQuery,
        config,
        hasOwn = Object.prototype.hasOwnProperty;
    ZenQuery = {
        //Renders a given zen coding string as html
        render: function (string) {
            if (arguments.length != 1)
                throw new Error('Incorrect Number of Arguments');
            if (!ZenQuery.is('string',string))
                throw new Error('Invalid Arguments');
            var matches = config.matches;
            //If no element, make div the default element
            var element = string.match(matches.element);
            if (!element)
                element = 'div';
            var classes = string.match(matches.classes);
            if (classes && classes.length > 0)
                classes = ' class="' + classes.join(' ').replace(/\./g, '') + '"';
            var id = string.match(matches.id);
            if (id && id.length > 0)
                id = ' id="' + id.join('').replace('#', '') + '"';
            var prefix = '<' + element;
            if (id && id.length > 0)
                prefix += id;
            if (classes && classes.length > 0)
                prefix += classes;
            prefix += '>';
            var suffix = '</' + element + '>';
            var html = prefix + suffix;
            return html;
        },
    };

    // We use the prototype to distinguish between properties that should
    // be exposed as globals (and in exports) and those that shouldn't
    (function () {
        function F() { };
        F.prototype = ZenQuery;
        ZenQuery = new F();

        // Make F QUnit's constructor so that we can add to the prototype later
        ZenQuery.constructor = F;
    }());

    //Extend - from jQuery
    function extend() {
        var options, name, src, copy, copyIsArray, clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

        // Handle a deep copy situation
        if ( typeof target === "boolean" ) {
            deep = target;

            // skip the boolean and the target
            target = arguments[ i ] || {};
            i++;
        }

        // Handle case when target is a string or something (possible in deep copy)
        if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
            target = {};
        }

        // extend jQuery itself if only one argument is passed
        if ( i === length ) {
            target = this;
            i--;
        }

        for ( ; i < length; i++ ) {
            // Only deal with non-null/undefined values
            if ( (options = arguments[ i ]) != null ) {
                // Extend the base object
                for ( name in options ) {
                    src = target[ name ];
                    copy = options[ name ];

                    // Prevent never-ending loop
                    if ( target === copy ) {
                        continue;
                    }

                    // Recurse if we're merging plain objects or arrays
                    if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                        if ( copyIsArray ) {
                            copyIsArray = false;
                            clone = src && jQuery.isArray(src) ? src : [];

                        } else {
                            clone = src && jQuery.isPlainObject(src) ? src : {};
                        }

                        // Never move original objects, clone them
                        target[ name ] = jQuery.extend( deep, clone, copy );

                        // Don't bring in undefined values
                    } else if ( copy !== undefined ) {
                        target[ name ] = copy;
                    }
                }
            }
        }

        // Return the modified object
        return target;
    };

    //Config
    config = {
        matches: {
            element: /^[a-z-]+/,
            id: /#[a-z-]+/,
            classes: /\.[a-z-]+/g
        },
        html: {
            prefix: '',
            suffix: ''
        }
    };

    //Add stuff to ZenQuery
    extend(ZenQuery, {

        //config object
        config: config,

        // Safe object type checking - from QUnit
        is: function (type, obj) {
            return QUnit.objectType(obj) === type;
        },
        objectType: function (obj) {
            if (typeof obj === "undefined") {
                return "undefined";
            }

            // Consider: typeof null === object
            if (obj === null) {
                return "null";
            }

            var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
                type = match && match[1] || "";

            switch (type) {
                case "Number":
                    if (isNaN(obj)) {
                        return "nan";
                    }
                    return "number";
                case "String":
                case "Boolean":
                case "Array":
                case "Date":
                case "RegExp":
                case "Function":
                    return type.toLowerCase();
            }
            if (typeof obj === "object") {
                return "object";
            }
            return undefined;
        },

        //extend
        extend: extend,
    });

    // Add private stuff to ZenQuery
    extend(ZenQuery.constructor.prototype, {

        // Complex render method
        html: function (string, options) {
            var html = '';
            if (hasOwn.call(options, 'prefix') || hasOwn.call(options, 'suffix')) {
                var defaults = ZenQuery.config.html;
                html = extend({}, defaults, options);
            }
            return html;
        }
    });

    // For browser, export only select globals
    if (typeof window !== "undefined" && window != null) {
        (function() {
            var i,
                l,
                keys = [
                ];
            for (i = 0, l = keys.length; i < l; i++) {
                window[keys[i]] = QUnit[keys[i]];
            }
        })();
        window.ZenQuery = ZenQuery;
    }

    // Get a reference to the global object, like window in browsers
}((function () {
    return this;
})()));
<|endoftext|>


<commit_before>var nodegit = require("nodegit");
var path = require("path");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
fse.ensureDir = promisify(fse.ensureDir);

var fileName = "newFile.txt";
var fileContent = "hello world";

var repository;
var remote;
var oid;

var signature = nodegit.Signature.create("Foo bar",
  "foo@bar.com", 123456789, 60);

// Load up the repository index and make our initial commit to HEAD
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
  .then(function(repoResult) {
    repository = repoResult;

    return repository.refreshIndex();
  })
  .then(function(index) {
    return index.addAll()
      .then(function() {
        return index.write();
      })
      .then(function() {
        return index.writeTree();
      });
  })
  .then(function(oidResult) {
    oid = oidResult;
    return nodegit.Reference.nameToId(repository, "HEAD");
  })
  .then(function(head) {
    return repository.getCommit(head);
  })
  .then(function(parent) {
    return repository.createCommit("HEAD", signature, signature,
      "commit 111", oid, [parent]);
  })
  .then(function(){
    console.log(repository);
    // return repository.openIndex();
  })
  .then(function(){
    return repo.getRemote("origin");
  })
  .then(function(remoteResult){
    console.log('remote Loaded');
      remote = remoteResult;
      remote.setCallbacks({
          credentials: function(url, userName) {
              return nodegit.Cred.sshKeyFromAgent(userName);
          }
      });
      console.log('remote Configured');
      return remote.connect(nodegit.Enums.DIRECTION.PUSH);
  })
  .then(function(){
    console.log('remote Connected?', remote.connected())

    return remote.push(
              ["refs/heads/master:refs/heads/master"],
              null,
              repo.defaultSignature(),
              "Push to master")
  })
  .then(function() {
      console.log('remote Pushed!')
  })
  // // Add a new remote
  // .then(function() {
  //   return nodegit.Remote.create(repository, "origin",
  //     "git@github.com:tlqylzn/gitnode.git")
  //   .then(function(remoteResult) {
  //     remote = remoteResult;

  //     remote.setCallbacks({
  //       credentials: function(url, userName) {
  //         return nodegit.Cred.sshKeyFromAgent(userName);
  //       }
  //     });
  //     return remote.connect(nodegit.Enums.DIRECTION.PUSH);
  //   });
  // })
  // .then(function(){
  //   // Create the push object for this remote
  //   return remote.push(
  //     ["refs/heads/master:refs/heads/master"],
  //     {
  //       callbacks: {
  //         credentials: function(url, userName) {
  //           return nodegit.Cred.sshKeyFromAgent(userName);
  //         }
  //       }
  //     }
  //   );
  // })
  // .done(function() {
  //   console.log("Done!");
  // })
  .catch(function(reason) {
    console.log(reason);
  });
<commit_msg>commit 111<commit_after>var nodegit = require("nodegit");
var path = require("path");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
fse.ensureDir = promisify(fse.ensureDir);

var fileName = "newFile.txt";
var fileContent = "hello world";

var repository;
var remote;
var oid;

var signature = nodegit.Signature.create("Foo bar",
  "foo@bar.com", 123456789, 60);

// Load up the repository index and make our initial commit to HEAD
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
  .then(function(repoResult) {
    repository = repoResult;

    return repository.refreshIndex();
  })
  .then(function(index) {
    return index.addAll()
      .then(function() {
        return index.write();
      })
      .then(function() {
        return index.writeTree();
      });
  })
  .then(function(oidResult) {
    oid = oidResult;
    return nodegit.Reference.nameToId(repository, "HEAD");
  })
  .then(function(head) {
    return repository.getCommit(head);
  })
  .then(function(parent) {
    return repository.createCommit("HEAD", signature, signature,
      "commit 111", oid, [parent]);
  })
  .then(function(){
    console.log(repository);
    // return repository.openIndex();
  })
  .then(function(){
    return repository.getRemote("origin");
  })
  .then(function(remoteResult){
    console.log('remote Loaded');
      remote = remoteResult;
      remote.setCallbacks({
          credentials: function(url, userName) {
              return nodegit.Cred.sshKeyFromAgent(userName);
          }
      });
      console.log('remote Configured');
      return remote.connect(nodegit.Enums.DIRECTION.PUSH);
  })
  .then(function(){
    console.log('remote Connected?', remote.connected())

    return remote.push(
              ["refs/heads/master:refs/heads/master"],
              null,
              repository.defaultSignature(),
              "Push to master")
  })
  .then(function() {
      console.log('remote Pushed!')
  })
  // // Add a new remote
  // .then(function() {
  //   return nodegit.Remote.create(repository, "origin",
  //     "git@github.com:tlqylzn/gitnode.git")
  //   .then(function(remoteResult) {
  //     remote = remoteResult;

  //     remote.setCallbacks({
  //       credentials: function(url, userName) {
  //         return nodegit.Cred.sshKeyFromAgent(userName);
  //       }
  //     });
  //     return remote.connect(nodegit.Enums.DIRECTION.PUSH);
  //   });
  // })
  // .then(function(){
  //   // Create the push object for this remote
  //   return remote.push(
  //     ["refs/heads/master:refs/heads/master"],
  //     {
  //       callbacks: {
  //         credentials: function(url, userName) {
  //           return nodegit.Cred.sshKeyFromAgent(userName);
  //         }
  //       }
  //     }
  //   );
  // })
  // .done(function() {
  //   console.log("Done!");
  // })
  .catch(function(reason) {
    console.log(reason);
  });
<|endoftext|>