<commit_before>/*
Copyright (C) 2011 by Gregory Burlet, Alastair Porter

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * Creates a staff
 * @class Represents a Staff
 *
 * @param {Array} bb [ulx, uly, lrx, lry] staff bounding box
 * (.) <ulx,uly>        (.)
 *
 *
 * (.)        <lrx,lry> (.)
 *
 * @param {Object} options [numlines {Number}, interact {Boolean}]
 *
 * The staff has list of elements on the staff, sorted by horizontal position.
 * The staff model is a generic container to accomodate staffless glyphs without pitch.
 */
Toe.Model.Staff = function(bb, options) {
    // prevent construction of prototype object without parameters
    if (!arguments.length) return;

    // default 4 stafflines
    this.props = {
        numLines: 4,
        interact: false
    };

    $.extend(this.props, options);

    // set position
    if(!Toe.validBoundingBox(bb)) {
        throw new Error("Staff: invalid bounding box");
    }

    this.zone = new Object();
    this.zone.ulx = bb[0];
    this.zone.uly = bb[1];
    this.zone.lrx = bb[2];
    this.zone.lry = bb[3];

    // cache delta y: pixels between stafflines
    if (this.props.numLines > 1) {
        this.delta_y = Math.abs(this.zone.lry - this.zone.uly) / (this.props.numLines-1);
    }

    // id of the staff
    this.id = null;

    this.elements = new Array();
}

Toe.Model.Staff.prototype.constructor = Toe.Model.Staff;

Toe.Model.Staff.prototype.setID = function(sid) {
    this.id = sid;
}

/**
 * Sets the bounding box of the staff
 *
 * @methodOf Toe.Model.Staff
 * @param {Array} bb [ulx,uly,lrx,lry]
 */
Toe.Model.Staff.prototype.setBoundingBox = function(bb) {
    if(!Toe.validBoundingBox(bb)) {
        throw new Error("Staff: invalid bounding box");
    }

    bb = $.map(bb, Math.round);

    this.zone.ulx = bb[0];
    this.zone.uly = bb[1];
    this.zone.lrx = bb[2];
    this.zone.lry = bb[3];

    // update delta_y cache
    if (this.props.numLines > 1) {
        this.delta_y = Math.abs(this.zone.lry - this.zone.uly) / (this.props.numLines-1);
    }
}

// sort based on ulx bounding box position
Toe.Model.Staff.prototype.sortElements = function() {
    this.elements.sort(function(el1, el2) {
        return el1.zone.ulx - el2.zone.ulx;
    });
}

// insert element in the element list (sorted in ascending order
// by x position).
Toe.Model.Staff.prototype.insertElement = function(ele) {
    // by default, we should push to the end of the array
    var iInsert = this.elements.length;
    for (var i = 0; i < this.elements.length; i++) {
        if (ele.zone.ulx <= this.elements[i].zone.ulx) {
            iInsert = i;
            break;
        }
    }

    this.elements.splice(iInsert,0, ele);

    return iInsert;
}

// Remove element by ID
Toe.Model.Staff.prototype.removeElementByID = function(eleID) {
    for (var i = this.elements.length-1; i >= 0; i--) {
        if (this.elements[i].id == eleID) {
            // remove drawing
            $(this.elements[i]).trigger("vEraseDrawing");
            this.elements.splice(i,1);
        }
    }
}

// remove element by reference
Toe.Model.Staff.prototype.removeElementByRef = function(ele) {
    var eleInd = $.inArray(ele, this.elements);

    if (eleInd >= 0) {
        // remove drawing
        $(this.elements[eleInd]).trigger("vEraseDrawing");
        this.elements.splice(eleInd, 1);
    }
}

/**
 * Get clef acting on an element
 *
 * @methodOf Toe.Model.staff
 */
Toe.Model.Staff.prototype.getActingClefByEle = function(element) {
    var eleInd = $.inArray(element, this.elements);
    // look backwards for first clef
    for (var i = eleInd; i >= 0; i--) {
        var e = this.elements[i];
        if (e instanceof Toe.Model.Clef) {
            return e;
        }
    }

    // if no clef is on the staff
    return null;
}

Toe.Model.Staff.prototype.getActingClefByCoords = function(coords) {
    // look backwards from end of element list for first clef
    for (var i = this.elements.length; i >= 0; i--) {
        var e = this.elements[i];
        if (e instanceof Toe.Model.Clef && coords.x > e.zone.lrx) {
            return e;
        }
    }

    // if no clef is found
    return null;
}

// Given a clef mounted on this staff, get the previous acting clef
Toe.Model.Staff.prototype.getPreviousClef = function(clef) {
    var oldClefInd = $.inArray(clef, this.elements);
    // only search if the clef is not the first clef, and is mounted on this staff
    if (oldClefInd > 0) {
        for (var i = oldClefInd-1; i >= 0; i--) {
            if (this.elements[i] instanceof Toe.Model.Clef) {
                return this.elements[i];
            }
        }
    }

    // if no clef is found
    return null;
}

/**
 * Given a set of coordinates, returns snapped coordinates
 * to lines or spaces within the staff.
 *
 * @methodOf Toe.Model.Staff
 * @param {Object} coords {x: ,y: }
 * @returns {Object} snappedCoords {x: xprime, y: yprime}
 */
Toe.Model.Staff.prototype.ohSnap = function(coords, width, options) {
    var opts = {
        ignoreEle: null,
        x: true,
        y: true
    };

    $.extend(opts, options);

    var coordsPrime = coords;

    if (opts.y) {
        // CALCULATE NEW VERTICAL POSITION
        var linesRoot = this.zone.uly;
        var spacesRoot = this.zone.uly + this.delta_y/2;

        // calculate multiple of lines or spaces
        var lineMult = (coords.y - linesRoot) / this.delta_y;
        var lineErr = Math.abs(Math.round(Math.abs(lineMult)) - Math.abs(lineMult));
        var spaceMult = (coords.y - spacesRoot) / this.delta_y;
        var spaceErr = Math.abs(Math.round(Math.abs(spaceMult)) - Math.abs(spaceMult));

        // find the minimum error for lines or spaces
        var minError = Math.min(lineErr, spaceErr);
        // there really should be an argmin in javascript ... sigh
        if (minError == lineErr) {
            // we should snap to the line!
            coordsPrime.y = linesRoot + Math.round(lineMult)*this.delta_y;
        }
        else {
            // we should snap to the space!
            coordsPrime.y = spacesRoot + Math.round(spaceMult)*this.delta_y;
        }
    }

    if (opts.x) {
        // CALCULATE NEW HORIZONTAL POSITION
        // go through each element in staff element list to see if the inserted element
        // temporally intersects with others. If so, offset it.
        var left = coords.x-(width/2);
        var right = coords.x+(width/2);
        for (var i = 0; i < this.elements.length; i++) {
            if (this.elements[i] == opts.ignoreEle) {
                continue;
            }

            var ulx = this.elements[i].zone.ulx;
            var lrx = this.elements[i].zone.lrx;

            if (left >= lrx) {
                continue;
            }
            else {
                if ((left >= ulx && left < lrx) || (right >= ulx && right < lrx) || (ulx > left && lrx < right)) {
                    // uh oh - we've intersected a drawn element
                    var bbCentre = ulx + (lrx-ulx)/2;
                    // figure out if we should move it to the left or right
                    if (coords.x < bbCentre) {
                        // move left
                        // TODO: check that other elements aren't drawn here
                        coordsPrime.x = ulx - width/2;
                    }
                    else {
                        // move right
                        // TODO: check that other elements aren't drawn here
                        coordsPrime.x = lrx + width/2;
                    }
                }
                else {
                    coordsPrime.x = coords.x;
                }
                break;
            }
        }

        // check left staff boundary
        if (this.elements.length && this.elements[0] instanceof Toe.Model.Clef && left <= this.elements[0].zone.lrx) {
            coordsPrime.x = this.elements[0].zone.lrx + width/2 + 1;
        }
        else if (left <= this.zone.ulx) {
            coordsPrime.x = this.zone.ulx + width/2 + 1;
        }

        // check right staff boundary
        if (this.custos && opts.ignoreEle != this.custos && right >= this.custos.zone.ulx) {
            coordsPrime.x = this.custos.zone.ulx - width/2 - 3;
        }
        else if (right >= this.zone.lrx) {
            coordsPrime.x = this.zone.lrx - width/2 - 3;
        }
    }

    return coordsPrime;
}
<commit_msg>Staff bounding box<commit_after>/*
Copyright (C) 2011 by Gregory Burlet, Alastair Porter

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * Creates a staff
 * @class Represents a Staff
 *
 * @param {Array} bb [ulx, uly, lrx, lry] staff bounding box
 * (.) <ulx,uly>        (.)
 *
 *
 * (.)        <lrx,lry> (.)
 *
 * @param {Object} options [numlines {Number}, interact {Boolean}]
 *
 * The staff has list of elements on the staff, sorted by horizontal position.
 * The staff model is a generic container to accomodate staffless glyphs without pitch.
 */
Toe.Model.Staff = function(bb, options) {
    // prevent construction of prototype object without parameters
    if (!arguments.length) return;

    // default 4 stafflines
    this.props = {
        numLines: 4,
        interact: false
    };

    $.extend(this.props, options);

    // set position
    if(!Toe.validBoundingBox(bb)) {
        throw new Error("Staff: invalid bounding box");
    }

    this.zone = new Object();
    this.zone.ulx = bb[0];
    this.zone.uly = bb[1];
    this.zone.lrx = bb[2];
    this.zone.lry = bb[3];

    // cache delta y: pixels between stafflines
    if (this.props.numLines > 1) {
        this.delta_y = Math.abs(this.zone.lry - this.zone.uly) / (this.props.numLines-1);
    }

    // id of the staff
    this.id = null;

    this.elements = new Array();
}

Toe.Model.Staff.prototype.constructor = Toe.Model.Staff;

Toe.Model.Staff.prototype.setID = function(sid) {
    this.id = sid;
}

/**
 * Sets the bounding box of the staff
 *
 * @methodOf Toe.Model.Staff
 * @param {Array} bb [ulx,uly,lrx,lry]
 */
Toe.Model.Staff.prototype.setBoundingBox = function(bb) {
    if(!Toe.validBoundingBox(bb)) {
        throw new Error("Staff: invalid bounding box");
    }

    bb = $.map(bb, Math.round);

    this.zone.ulx = bb[0];
    this.zone.uly = bb[1];
    this.zone.lrx = bb[2];
    this.zone.lry = bb[3];

    // update delta_y cache
    if (this.props.numLines > 1) {
        this.delta_y = Math.abs(this.zone.lry - this.zone.uly) / (this.props.numLines-1);
    }
}

// sort based on ulx bounding box position
Toe.Model.Staff.prototype.sortElements = function() {
    this.elements.sort(function(el1, el2) {
        return el1.zone.ulx - el2.zone.ulx;
    });
}

// insert element in the element list (sorted in ascending order
// by x position).
Toe.Model.Staff.prototype.insertElement = function(ele) {
    // by default, we should push to the end of the array
    var iInsert = this.elements.length;
    for (var i = 0; i < this.elements.length; i++) {
        if (ele.zone.ulx <= this.elements[i].zone.ulx) {
            iInsert = i;
            break;
        }
    }

    this.elements.splice(iInsert,0, ele);

    return iInsert;
}

// Remove element by ID
Toe.Model.Staff.prototype.removeElementByID = function(eleID) {
    for (var i = this.elements.length-1; i >= 0; i--) {
        if (this.elements[i].id == eleID) {
            // remove drawing
            $(this.elements[i]).trigger("vEraseDrawing");
            this.elements.splice(i,1);
        }
    }
}

// remove element by reference
Toe.Model.Staff.prototype.removeElementByRef = function(ele) {
    var eleInd = $.inArray(ele, this.elements);

    if (eleInd >= 0) {
        // remove drawing
        $(this.elements[eleInd]).trigger("vEraseDrawing");
        this.elements.splice(eleInd, 1);
    }
}

/**
 * Get clef acting on an element
 *
 * @methodOf Toe.Model.staff
 */
Toe.Model.Staff.prototype.getActingClefByEle = function(element) {
    var eleInd = $.inArray(element, this.elements);
    // look backwards for first clef
    for (var i = eleInd; i >= 0; i--) {
        var e = this.elements[i];
        if (e instanceof Toe.Model.Clef) {
            return e;
        }
    }

    // if no clef is on the staff
    return null;
}

Toe.Model.Staff.prototype.getActingClefByCoords = function(coords) {
    // look backwards from end of element list for first clef
    for (var i = this.elements.length; i >= 0; i--) {
        var e = this.elements[i];
        if (e instanceof Toe.Model.Clef && coords.x > e.zone.lrx) {
            return e;
        }
    }

    // if no clef is found
    return null;
}

// Given a clef mounted on this staff, get the previous acting clef
Toe.Model.Staff.prototype.getPreviousClef = function(clef) {
    var oldClefInd = $.inArray(clef, this.elements);
    // only search if the clef is not the first clef, and is mounted on this staff
    if (oldClefInd > 0) {
        for (var i = oldClefInd-1; i >= 0; i--) {
            if (this.elements[i] instanceof Toe.Model.Clef) {
                return this.elements[i];
            }
        }
    }

    // if no clef is found
    return null;
}

/**
 * Given a set of coordinates, returns snapped coordinates
 * to lines or spaces within the staff.
 *
 * @methodOf Toe.Model.Staff
 * @param {Object} coords {x: ,y: }
 * @returns {Object} snappedCoords {x: xprime, y: yprime}
 */
Toe.Model.Staff.prototype.ohSnap = function(coords, width, options) {
    var opts = {
        ignoreEle: null,
        x: true,
        y: true
    };

    $.extend(opts, options);

    var coordsPrime = coords;

    if (opts.y) {
        // CALCULATE NEW VERTICAL POSITION
        var linesRoot = this.zone.uly;
        var spacesRoot = this.zone.uly + this.delta_y/2;

        // calculate multiple of lines or spaces
        var lineMult = (coords.y - linesRoot) / this.delta_y;
        var lineErr = Math.abs(Math.round(Math.abs(lineMult)) - Math.abs(lineMult));
        var spaceMult = (coords.y - spacesRoot) / this.delta_y;
        var spaceErr = Math.abs(Math.round(Math.abs(spaceMult)) - Math.abs(spaceMult));

        // find the minimum error for lines or spaces
        var minError = Math.min(lineErr, spaceErr);
        // there really should be an argmin in javascript ... sigh
        if (minError == lineErr) {
            // we should snap to the line!
            coordsPrime.y = linesRoot + Math.round(lineMult)*this.delta_y;
        }
        else {
            // we should snap to the space!
            coordsPrime.y = spacesRoot + Math.round(spaceMult)*this.delta_y;
        }
    }

    if (opts.x) {
        // CALCULATE NEW HORIZONTAL POSITION
        // go through each element in staff element list to see if the inserted element
        // intersects with others. If so, offset it.
        var left = coords.x-(width/2);
        var right = coords.x+(width/2);
        for (var i = 0; i < this.elements.length; i++) {
            if (this.elements[i] == opts.ignoreEle) {
                continue;
            }

            var ulx = this.elements[i].zone.ulx;
            var lrx = this.elements[i].zone.lrx;

            if (left >= lrx) {
                continue;
            }
            else {
                if ((left >= ulx && left < lrx) || (right >= ulx && right < lrx) || (ulx > left && lrx < right)) {
                    // uh oh - we've intersected a drawn element
                    var bbCentre = ulx + (lrx-ulx)/2;
                    // figure out if we should move it to the left or right
                    if (coords.x < bbCentre) {
                        // move left
                        // TODO: check that other elements aren't drawn here
                        coordsPrime.x = ulx - width/2;
                    }
                    else {
                        // move right
                        // TODO: check that other elements aren't drawn here
                        coordsPrime.x = lrx + width/2;
                    }
                }
                else {
                    coordsPrime.x = coords.x;
                }
                break;
            }
        }

        // check left staff boundary
        if (this.elements.length && this.elements[0] instanceof Toe.Model.Clef && left <= this.elements[0].zone.lrx) {
            coordsPrime.x = this.elements[0].zone.lrx + width/2 + 1;
        }
        else if (left <= this.zone.ulx) {
            coordsPrime.x = this.zone.ulx + width/2 + 1;
        }

        // check right staff boundary
        if (this.custos && opts.ignoreEle != this.custos && right >= this.custos.zone.ulx) {
            coordsPrime.x = this.custos.zone.ulx - width/2 - 3;
        }
        else if (right >= this.zone.lrx) {
            coordsPrime.x = this.zone.lrx - width/2 - 3;
        }
    }

    return coordsPrime;
}
<|endoftext|>


<commit_before>import isFunction from 'lodash/isFunction';
import conformsTo from 'lodash/conformsTo';
import isNil from 'lodash/isNil';

const optsShape = {
  select: isFunction,
  dispatch: isFunction
};

const promiseShape = {
  then: isFunction
};

const rootStore = {
  select(query) {
    throw new Error(`No selector found for ${query}`);
  }
  dispatch(msg) {
    throw new Error(`No dispatcher found for ${msg}`);
  }
  subscribe(callback) {
    return () => {};
  }
};

class Store {
  constructor(opts, parent = rootStore) {
    if (!conformsTo(opts, optsShape)) {
      throw new TypeError(`${opts} TODO`);
    }
    const parent = parent;
    this.unsubscribeParent = parent.subscribe(() => this.notify());
    this.parent = parent;
    this.opts = opts;
    this.state = state;
    this.subscribers = new Set();
    this.notifyScheduled = false;
  }
  notify() {
    this.notifyScheduled = false;
    const subscribers = new Set(this.subscribers);
    for(const callback of subscribers) {
      callback();
    }
  }
  scheduleNotify() {
    if (!this.notifyScheduled) {
      setImmediate(() => this.notify());
      this.notifyScheduled = true;
    }
  }
  select(query) {
    const select = query => this.select(query);
    const selectParent = query => this.parent.select(query);
    const selector = this.opts.select(
      query,
      select,
      selectParent);
    if (isFunction(selector)) {
      return () => selector(this.state);
    }
    else {
      throw new TypeError(`${selector} must be a selector.`)
    }
  }
  dispatch(msg) {
    const dispatch = msg => this.dispatch(msg);
    const dispatchParent = msg => this.parent.dispatch(msg);
    const transformerOrSaga = this.opts.dispatch(
      msg,
      dispatch,
      dispatchParent);
    if (isFunction(transformerOrSaga)) {
      const transformer = transformerOrSaga;
      const state = transformer(this.state);
      this.setState(state);
      return promise.resolve(true);
    }
    else if (isPromise(transformerOrSaga)) {
      const saga = transformerOrSaga;
      return saga.then(true);
    }
    else {
      throw new TypeError(`${transformerOrSaga} must be either a transformer a saga.`)
    }
  }
  getState() {
    return this.state;
  }
  setState(state) {
    if (this.state !== state) {
      this.state = state;
      this.scheduleNotify();
    }
    return this;
  }
  subscribe(callback) {
    this.subscribers.add(callback);
    return () => {
      this.subscribers.delete(callback);
    };
  }
  destroy() {

  }
  store(name) {
    const spawner = this.opts.store;
    const store = spawner(name);
    return store;
  }
}

const store = opts =>
  new Store(opts);

export default store;
<commit_msg>add deps<commit_after>import isFunction from 'lodash/isFunction';
import conformsTo from 'lodash/conformsTo';
import promise from 'bluebird';

const optsShape = {
  select: isFunction,
  dispatch: isFunction
};

const promiseShape = {
  then: isFunction
};

const isPromise = x =>
  conformsTo(x, promiseShape);

const rootStore = {
  select(query) {
    throw new Error(`No selector found for ${query}`);
  }
  dispatch(msg) {
    throw new Error(`No dispatcher found for ${msg}`);
  }
  subscribe(callback) {
    return () => {};
  }
};

class Store {
  constructor(opts, parent = rootStore) {
    if (!conformsTo(opts, optsShape)) {
      throw new TypeError(`${opts} TODO`);
    }
    const parent = parent;
    this.unsubscribeParent = parent.subscribe(() => this.notify());
    this.parent = parent;
    this.opts = opts;
    this.state = state;
    this.subscribers = new Set();
    this.notifyScheduled = false;
  }
  notify() {
    this.notifyScheduled = false;
    const subscribers = new Set(this.subscribers);
    for(const callback of subscribers) {
      callback();
    }
  }
  scheduleNotify() {
    if (!this.notifyScheduled) {
      setImmediate(() => this.notify());
      this.notifyScheduled = true;
    }
  }
  select(query) {
    const select = query => this.select(query);
    const selectParent = query => this.parent.select(query);
    const selector = this.opts.select(
      query,
      select,
      selectParent);
    if (isFunction(selector)) {
      return () => selector(this.state);
    }
    else {
      throw new TypeError(`${selector} must be a selector.`)
    }
  }
  dispatch(msg) {
    const dispatch = msg => this.dispatch(msg);
    const dispatchParent = msg => this.parent.dispatch(msg);
    const transformerOrSaga = this.opts.dispatch(
      msg,
      dispatch,
      dispatchParent);
    if (isFunction(transformerOrSaga)) {
      const transformer = transformerOrSaga;
      const state = transformer(this.state);
      this.setState(transformer(this.state));
      return promise.resolve(true);
    }
    else if (isPromise(transformerOrSaga)) {
      const saga = transformerOrSaga;
      return saga.then(true);
    }
    else {
      throw new TypeError(`${transformerOrSaga} must be either a transformer a saga.`)
    }
  }
  getState() {
    return this.state;
  }
  setState(state) {
    if (this.state !== state) {
      this.state = state;
      this.scheduleNotify();
    }
    return this;
  }
  subscribe(callback) {
    this.subscribers.add(callback);
    return () => {
      this.subscribers.delete(callback);
    };
  }
  destroy() {

  }
  store(name) {
    const spawner = this.opts.store;
    const store = spawner(name);
    return store;
  }
}

const store = opts =>
  new Store(opts);

export default store;
<|endoftext|>


<commit_before>"use strict"

module.exports = (function() {
	// Store.js
	var store = {},
		win = (typeof window != 'undefined' ? window : global),
		doc = win.document,
		localStorageName = 'localStorage',
		scriptTag = 'script',
		storage

	store.disabled = false
	store.version = '1.3.20'
	store.set = function(key, value) {}
	store.get = function(key, defaultVal) {}
	store.has = function(key) { return store.get(key) !== undefined }
	store.remove = function(key) {}
	store.clear = function() {}
	store.transact = function(key, defaultVal, transactionFn) {
		if (transactionFn == null) {
			transactionFn = defaultVal
			defaultVal = null
		}
		if (defaultVal == null) {
			defaultVal = {}
		}
		var val = store.get(key, defaultVal)
		transactionFn(val)
		store.set(key, val)
	}
	store.getAll = function() {}
	store.forEach = function() {}

	store.serialize = function(value) {
		return JSON.stringify(value)
	}
	store.deserialize = function(value) {
		if (typeof value != 'string') { return undefined }
		try { return JSON.parse(value) }
		catch(e) { return value || undefined }
	}

	// Functions to encapsulate questionable FireFox 3.6.13 behavior
	// when about.config::dom.storage.enabled === false
	// See https://github.com/marcuswestin/store.js/issues#issue/13
	function isLocalStorageNameSupported() {
		try { return (localStorageName in win && win[localStorageName]) }
		catch(err) { return false }
	}

	if (isLocalStorageNameSupported()) {
		storage = win[localStorageName]
		store.set = function(key, val) {
			if (val === undefined) { return store.remove(key) }
			storage.setItem(key, store.serialize(val))
			return val
		}
		store.get = function(key, defaultVal) {
			var val = store.deserialize(storage.getItem(key))
			return (val === undefined ? defaultVal : val)
		}
		store.remove = function(key) { storage.removeItem(key) }
		store.clear = function() { storage.clear() }
		store.getAll = function() {
			var ret = {}
			store.forEach(function(key, val) {
				ret[key] = val
			})
			return ret
		}
		store.forEach = function(callback) {
			for (var i=0; i<storage.length; i++) {
				var key = storage.key(i)
				callback(key, store.get(key))
			}
		}
	} else if (doc && doc.documentElement.addBehavior) {
		var storageOwner,
			storageContainer
		// Since #userData storage applies only to specific paths, we need to
		// somehow link our data to a specific path.  We choose /favicon.ico
		// as a pretty safe option, since all browsers already make a request to
		// this URL anyway and being a 404 will not hurt us here.  We wrap an
		// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
		// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
		// since the iframe access rules appear to allow direct access and
		// manipulation of the document element, even for a 404 page.  This
		// document can be used instead of the current document (which would
		// have been limited to the current path) to perform #userData storage.
		try {
			storageContainer = new ActiveXObject('htmlfile')
			storageContainer.open()
			storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'>')
			storageContainer.close()
			storageOwner = storageContainer.w.frames[0].document
			storage = storageOwner.createElement('div')
		} catch(e) {
			// somehow ActiveXObject instantiation failed (perhaps some special
			// security settings or otherwse), fall back to per-path storage
			storage = doc.createElement('div')
			storageOwner = doc.body
		}
		var withIEStorage = function(storeFunction) {
			return function() {
				var args = Array.prototype.slice.call(arguments, 0)
				args.unshift(storage)
				// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
				// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
				storageOwner.appendChild(storage)
				storage.addBehavior('#default#userData')
				storage.load(localStorageName)
				var result = storeFunction.apply(store, args)
				storageOwner.removeChild(storage)
				return result
			}
		}

		// In IE7, keys cannot start with a digit or contain certain chars.
		// See https://github.com/marcuswestin/store.js/issues/40
		// See https://github.com/marcuswestin/store.js/issues/83
		var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
		var ieKeyFix = function(key) {
			return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___')
		}
		store.set = withIEStorage(function(storage, key, val) {
			key = ieKeyFix(key)
			if (val === undefined) { return store.remove(key) }
			storage.setAttribute(key, store.serialize(val))
			storage.save(localStorageName)
			return val
		})
		store.get = withIEStorage(function(storage, key, defaultVal) {
			key = ieKeyFix(key)
			var val = store.deserialize(storage.getAttribute(key))
			return (val === undefined ? defaultVal : val)
		})
		store.remove = withIEStorage(function(storage, key) {
			key = ieKeyFix(key)
			storage.removeAttribute(key)
			storage.save(localStorageName)
		})
		store.clear = withIEStorage(function(storage) {
			var attributes = storage.XMLDocument.documentElement.attributes
			storage.load(localStorageName)
			for (var i=attributes.length-1; i>=0; i--) {
				storage.removeAttribute(attributes[i].name)
			}
			storage.save(localStorageName)
		})
		store.getAll = function(storage) {
			var ret = {}
			store.forEach(function(key, val) {
				ret[key] = val
			})
			return ret
		}
		store.forEach = withIEStorage(function(storage, callback) {
			var attributes = storage.XMLDocument.documentElement.attributes
			for (var i=0, attr; attr=attributes[i]; ++i) {
				callback(attr.name, store.deserialize(storage.getAttribute(attr.name)))
			}
		})
	}

	try {
		var testKey = '__storejs__'
		store.set(testKey, testKey)
		if (store.get(testKey) != testKey) { store.disabled = true }
		store.remove(testKey)
	} catch(e) {
		store.disabled = true
	}
	store.enabled = !store.disabled

	return store
}())
<commit_msg>Update store.js<commit_after>"use strict"

module.exports = (function() {
	// Store.js
	var store = {},
		win = (typeof window != 'undefined' ? window : global),
		doc = win.document,
		localStorageName = 'localStorage',
		scriptTag = 'script',
		storage

	store.disabled = false
	store.version = '1.3.20'
	store.set = function(key, value) {}
	store.get = function(key, defaultVal) {}
	store.has = function(key) { return store.get(key) !== undefined }
	store.remove = function(key) {}
	store.clear = function() {}
	store.transact = function(key, defaultVal, transactionFn) {
		if (transactionFn == null) {
			transactionFn = defaultVal
			defaultVal = null
		}
		if (defaultVal == null) {
			defaultVal = {}
		}
		var val = store.get(key, defaultVal)
		transactionFn(val)
		store.set(key, val)
	}
	store.getAll = function() {
		var ret = {}
		store.forEach(function(key, val) {
			ret[key] = val
		})
		return ret
	}
	store.forEach = function() {}
	store.serialize = function(value) {
		return JSON.stringify(value)
	}
	store.deserialize = function(value) {
		if (typeof value != 'string') { return undefined }
		try { return JSON.parse(value) }
		catch(e) { return value || undefined }
	}

	// Functions to encapsulate questionable FireFox 3.6.13 behavior
	// when about.config::dom.storage.enabled === false
	// See https://github.com/marcuswestin/store.js/issues#issue/13
	function isLocalStorageNameSupported() {
		try { return (localStorageName in win && win[localStorageName]) }
		catch(err) { return false }
	}

	if (isLocalStorageNameSupported()) {
		storage = win[localStorageName]
		store.set = function(key, val) {
			if (val === undefined) { return store.remove(key) }
			storage.setItem(key, store.serialize(val))
			return val
		}
		store.get = function(key, defaultVal) {
			var val = store.deserialize(storage.getItem(key))
			return (val === undefined ? defaultVal : val)
		}
		store.remove = function(key) { storage.removeItem(key) }
		store.clear = function() { storage.clear() }
		store.forEach = function(callback) {
			for (var i=0; i<storage.length; i++) {
				var key = storage.key(i)
				callback(key, store.get(key))
			}
		}
	} else if (doc && doc.documentElement.addBehavior) {
		var storageOwner,
			storageContainer
		// Since #userData storage applies only to specific paths, we need to
		// somehow link our data to a specific path.  We choose /favicon.ico
		// as a pretty safe option, since all browsers already make a request to
		// this URL anyway and being a 404 will not hurt us here.  We wrap an
		// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
		// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
		// since the iframe access rules appear to allow direct access and
		// manipulation of the document element, even for a 404 page.  This
		// document can be used instead of the current document (which would
		// have been limited to the current path) to perform #userData storage.
		try {
			storageContainer = new ActiveXObject('htmlfile')
			storageContainer.open()
			storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'>')
			storageContainer.close()
			storageOwner = storageContainer.w.frames[0].document
			storage = storageOwner.createElement('div')
		} catch(e) {
			// somehow ActiveXObject instantiation failed (perhaps some special
			// security settings or otherwse), fall back to per-path storage
			storage = doc.createElement('div')
			storageOwner = doc.body
		}
		var withIEStorage = function(storeFunction) {
			return function() {
				var args = Array.prototype.slice.call(arguments, 0)
				args.unshift(storage)
				// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
				// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
				storageOwner.appendChild(storage)
				storage.addBehavior('#default#userData')
				storage.load(localStorageName)
				var result = storeFunction.apply(store, args)
				storageOwner.removeChild(storage)
				return result
			}
		}

		// In IE7, keys cannot start with a digit or contain certain chars.
		// See https://github.com/marcuswestin/store.js/issues/40
		// See https://github.com/marcuswestin/store.js/issues/83
		var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
		var ieKeyFix = function(key) {
			return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___')
		}
		store.set = withIEStorage(function(storage, key, val) {
			key = ieKeyFix(key)
			if (val === undefined) { return store.remove(key) }
			storage.setAttribute(key, store.serialize(val))
			storage.save(localStorageName)
			return val
		})
		store.get = withIEStorage(function(storage, key, defaultVal) {
			key = ieKeyFix(key)
			var val = store.deserialize(storage.getAttribute(key))
			return (val === undefined ? defaultVal : val)
		})
		store.remove = withIEStorage(function(storage, key) {
			key = ieKeyFix(key)
			storage.removeAttribute(key)
			storage.save(localStorageName)
		})
		store.clear = withIEStorage(function(storage) {
			var attributes = storage.XMLDocument.documentElement.attributes
			storage.load(localStorageName)
			for (var i=attributes.length-1; i>=0; i--) {
				storage.removeAttribute(attributes[i].name)
			}
			storage.save(localStorageName)
		})
		store.forEach = withIEStorage(function(storage, callback) {
			var attributes = storage.XMLDocument.documentElement.attributes
			for (var i=0, attr; attr=attributes[i]; ++i) {
				callback(attr.name, store.deserialize(storage.getAttribute(attr.name)))
			}
		})
	}

	try {
		var testKey = '__storejs__'
		store.set(testKey, testKey)
		if (store.get(testKey) != testKey) { store.disabled = true }
		store.remove(testKey)
	} catch(e) {
		store.disabled = true
	}
	store.enabled = !store.disabled

	return store
}())
<|endoftext|>


<commit_before>var http = require('http');
var querystring = require('querystring');

// constructor function
function ConceptNet(host, port, version){

  // if not invoked as a constructor call
  if (!(this instanceof ConceptNet)){
    return new ConceptNet(host, port, version);
  }

  this.host = host || 'conceptnet5.media.mit.edu';
  this.version = version || '5.2'
  this.port = parseInt(port || 80)
}

ConceptNet.prototype.buildOptions = function(path){
  var options = {};
  options.hostname = this.host;
  options.port = this.port;
  options.path = path;
  return options;
}

ConceptNet.prototype.lookup = function(URI, params, callback){

  var limit = params.limit || 50;
  var offset = params.offset || 0;

  var path = "/data/" + this.version + String(URI) + "?limit=" + limit + "&offset=" + offset;
  if (params.filter === "core") path += "&filter=core";

  this.makeHtppRequest(this.buildOptions(path), callback);
};

ConceptNet.prototype.search = function(params, callback){
  var path = "/data/" + this.version + "/search?";

  var str = querystring.stringify(params);
  str = querystring.unescape(str);
  path += str;

  this.makeHtppRequest(this.buildOptions(path), callback);
};

function isConceptNetURI(uri){
  var  myRegEx = /\/(?:[acdelrs]|and|or)\/[a-zA-Z]{2}\/\w+/;
  return (myRegEx.test(uri) ? true : false);
}

function isValidTermPath(path){
  var myRegEx = /\/list\/[a-zA-Z]{2}\/\w+(?:@[-+]?[0-9]*\.?[0-9]+)?(,\w+(?:@[-+]?[0-9]*\.?[0-9]+)?)*/;
  return (myRegEx.test(path) ? true : false);
}

ConceptNet.prototype.association = function(input, params, callback){

    if(!isConceptNetURI(input) && !isValidTermPath(input)){
      var err = new Error("The input argument must be either a valid ConceptNet URI or a path of the form " +
          "/list/<language>/<term list>");
      return callback(err);
    }

    var path = "/data/" + this.version + "/assoc" + String(input) + "?limit" + limit;
    var limit = params.limit || 10;

    if (params.filter){
      if (isConceptNetURI(params.filter)) path += "&filter" + params.filter;
      else{
        var err2 = new Error("The GET argument filter must be a valid ConceptNet URI.");
        return callback(err2);
      }
    }

    this.makeHtppRequest(this.buildOptions(path), callback);
};

ConceptNet.prototype.makeHtppRequest = function(options, callback){
  var retrieve = function(response){
    var str = '';
    response.on('data', function (chunk) {
      str += chunk;
    });

    response.on('end', function () {
        callback(undefined, JSON.parse(str));
    });
  };

  http.request(options, retrieve).end();
};

// export node module
module.exports = ConceptNet;
<commit_msg>[FIX] bug, indentation<commit_after>'use strict';

var http = require('http');
var querystring = require('querystring');

// constructor function
function ConceptNet(host, port, version) {

    // if not invoked as a constructor call
    if ( !(this instanceof ConceptNet) ){
        return new ConceptNet(host, port, version);
    }

    this.host = host || 'conceptnet5.media.mit.edu';
    this.version = version || '5.2';
    this.port = parseInt(port || 80);
}

ConceptNet.prototype.buildOptions = function(path) {
    var options = {};
    options.hostname = this.host;
    options.port = this.port;
    options.path = path;
    return options;
};

ConceptNet.prototype.lookup = function(URI, params, callback) {

    var limit = params.limit || 50;
    var offset = params.offset || 0;

    var path = "/data/" + this.version + String(URI) + "?limit=" + limit + "&offset=" + offset;
    if ( params.filter === "core" ) {
        path += "&filter=core";
    }

    this.makeHtppRequest(this.buildOptions(path), callback);
};

ConceptNet.prototype.search = function(params, callback) {

    var path = "/data/" + this.version + "/search?";
    var str = querystring.stringify(params);
    str = querystring.unescape(str);
    path += str;

    this.makeHtppRequest(this.buildOptions(path), callback);

};

function isConceptNetURI(uri) {

    var  myRegEx = /\/(?:[acdelrs]|and|or)\/[a-zA-Z]{2}\/\w+/;
    return (myRegEx.test(uri) ? true : false);

}

function isValidTermPath(path) {

    var myRegEx = /\/list\/[a-zA-Z]{2}\/\w+(?:@[-+]?[0-9]*\.?[0-9]+)?(,\w+(?:@[-+]?[0-9]*\.?[0-9]+)?)*/;
    return (myRegEx.test(path) ? true : false);

}

ConceptNet.prototype.association = function(input, params, callback) {

    if( !isConceptNetURI(input) && !isValidTermPath(input) ) {
      var err = new Error("The input argument must be either a valid ConceptNet URI or a path of the form " +
          "/list/<language>/<term list>");
      return callback(err);
    }

    var limit = params.limit || 10;
    var path = "/data/" + this.version + "/assoc" + String(input) + "?limit" + limit;

    if ( params.filter ) {
        if ( isConceptNetURI(params.filter) ) {
            path += "&filter" + params.filter;
        } else {
            var err2 = new Error("The GET argument filter must be a valid ConceptNet URI.");
            return callback(err2);
        }
    }

    this.makeHtppRequest( this.buildOptions(path), callback );
};

ConceptNet.prototype.makeHtppRequest = function(options, callback) {
    var retrieve = function(response) {
        var str = '';
        response.on('data', function (chunk) {
            str += chunk;
        });

        response.on('end', function () {
            callback(undefined, JSON.parse(str));
        });
    };

    http.request( options, retrieve ).end();
};

// export node module
module.exports = ConceptNet;
<|endoftext|>


<commit_before>var $F = Ti.Filesystem,
	fs = exports,
	util = require('util');

var MODE_MAP = {};
MODE_MAP['r'] = MODE_MAP['r+'] = MODE_MAP['rs'] = MODE_MAP['rs+'] = $F.MODE_READ;
MODE_MAP['w'] = MODE_MAP['w+'] = MODE_MAP['wx'] = MODE_MAP['wx+'] = $F.MODE_WRITE;
MODE_MAP['a'] = MODE_MAP['a+'] = MODE_MAP['ax'] = MODE_MAP['ax+'] = $F.MODE_APPEND;

fs.Stats = function Stats(path) {
	this.__file = null;
	this.dev = 0;
	this.ino = 0;
	this.nlink = 0;
	this.uid = 0;
	this.gid = 0;
	this.rdev = 0;
	this.size = 0;
	this.blksize = 4096;
	this.blocks = 8;
	this.ctime = this.atime = this.mtime = 0;

	if (path) {
		this.__file = $F.getFile(path);
		this.size = this.__file.size;
		this.mode = 0;
		this.ctime = new Date(this.__file.createTimestamp());
		this.atime = this.mtime = new Date(this.__file.modificationTimestamp());
	}
};

fs.Stats.prototype.isDirectory = function(property) {
	return this.__file.isDirectory();
};

fs.Stats.prototype.isFile = function(property) {
	return this.__file.isFile();
};

fs.Stats.prototype.isBlockDevice = function(property) {
	return false;
};

fs.Stats.prototype.isCharacterDevice = function(property) {
	return false;
};

fs.Stats.prototype.isSymbolicLink = function(property) {
	return this.__file.symbolicLink;
};

fs.Stats.prototype.isFIFO = function(property) {
	return false;
};

fs.Stats.prototype.isSocket = function(property) {
	return false;
};

fs.exists = function exists(path, callback) {
	setTimeout(function() {
		return callback(fs.existsSync(path));
	}, 0);
};

fs.existsSync = function existsSync(path) {
	return $F.getFile(path).exists();
};

fs.readFile = function readFile(path, options, callback_) {
	throw new Error('readFile not yet implemented');
};

fs.readFileSync = function readFileSync(path, options) {
	// if (!options) {
 //    options = { encoding: null, flag: 'r' };
 //  } else if (util.isString(options)) {
 //    options = { encoding: options, flag: 'r' };
 //  } else if (!util.isObject(options)) {
 //    throw new TypeError('Bad arguments');
 //  }

 //  var encoding = options.encoding,
 //  	flag = options.flag || 'r';
 //  assertEncoding(options.encoding);

 //  var fd = fs.openSync(path, flag /*, mode */),
 //  	size = fs.fstatSync(fd).size;

 //  fs.closeSync(fd);
};

fs.close = function close(fd, callback) {
	setTimeout(function() {
		var err = null;
		try {
			fd.close();
		} catch (e) {
			err = e;
		}
		return callback(err);
	}, 0);
};

fs.closeSync = function closeSync(fd) {
	fd.close();
};

fs.open = function open(path, flags, mode, callback) {
	callback = maybeCallback(arguments[arguments.length-1]);
	if (!mode || util.isFunction(mode)) {
		mode = null;
	}

	setTimeout(function() {
		var fd = null,
			err = null;
		try {
			fd = fs.openSync(path, flags, mode);
		} catch (e) {
			err = e;
		}
		return callback(err, fd);
	}, 0);
};

fs.openSync = function openSync(path, flags, mode) {
	var tiMode = assertFlags(flags),
		file = $F.getFile(path),
		fd = file.open(tiMode);
	fd.__path = path;
	return fd;
};

fs.read = function read(fd, buffer, offset, length, position, callback) {
	// position is not handled in Titanium streams
	callback = maybeCallback(arguments[arguments.length-1]);
	if (util.isFunction(position)) { position = undefined; }
	if (util.isFunction(length)) { length = undefined; }
	if (util.isFunction(offset)) { offset = undefined; }

	// TODO: This should be Ti.Stream.read(), but it doesn't appear to do
	// anything when targeting a FileStream, despite the docs.
	setTimeout(function() {
		var bytes = null,
			err = null;
		try {
			bytes = fs.readSync(fd, buffer, offset, length, position);
		} catch (e) {
			err = e;
		}
		return callback(err, bytes, buffer);
	}, 0);
};

fs.readSync = function readSync(fd, buffer, offset, length, position) {
	// position is not handled in Titanium streams
	return fd.read(buffer, offset, length);
};

fs.write = function write(fd, buffer, offset, length, position, callback) {
	throw new Error('write not yet implemented');
};

fs.writeSync = function writeSync(fd, buffer, offset, length, position) {
	throw new Error('writeSync not yet implemented');
};

fs.rename = function rename(oldPath, newPath, callback) {
	throw new Error('rename not yet implemented');
};

fs.renameSync = function renameSync(oldPath, newPath) {
	throw new Error('renameSync not yet implemented');
};

fs.truncate = function truncate(path, len, callback) {
	throw new Error('truncate not yet implemented');
};

fs.truncateSync = function truncateSync(path, len) {
	throw new Error('truncateSync not yet implemented');
};

fs.ftruncate = function ftruncate(fd, len, callback) {
	throw new Error('ftruncate not yet implemented');
};

fs.ftruncateSync = function ftruncateSync(fd, len) {
	throw new Error('ftruncateSync not yet implemented');
};

fs.rmdir = function rmdir(path, callback) {
	throw new Error('rmdir not yet implemented');
};

fs.rmdirSync = function rmdirSync(path) {
	throw new Error('rmdirSync not yet implemented');
};

fs.fdatasync = function fdatasync(fd, callback) {
	throw new Error('fdatasync not yet implemented');
};

fs.fdatasyncSync = function fdatasyncSync(fd) {
	throw new Error('fdatasyncSync not yet implemented');
};

fs.fsync = function fsync(fd, callback) {
	throw new Error('fsync not yet implemented');
};

fs.fsyncSync = function fsyncSync(fd) {
	throw new Error('fsyncSync not yet implemented');
};

fs.mkdir = function mkdir(path, mode, callback) {
	throw new Error('mkdir not yet implemented');
};

fs.mkdirSync = function mkdirSync(path, mode) {
	throw new Error('mkdirSync not yet implemented');
};

fs.readdir = function readdir(path, callback) {
	throw new Error('readdir not yet implemented');
};

fs.readdirSync = function readdirSync(path) {
	throw new Error('readdirSync not yet implemented');
};

fs.fstat = function fstat(fd, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.fstatSync(fd);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.lstat = function lstat(path, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.lstatSync(path);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.stat = function stat(path, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.statSync(path);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.fstatSync = function fstatSync(fd) {
	if (fd.__path) {
		return fs.statSync(fd.__path);
	} else {
		throw new Error('invalid file descriptor');
	}
};

fs.lstatSync = function lstatSync(path) {
	return fs.statSync(path);
};

fs.statSync = function statSync(path) {
	return new fs.Stats(path);
};

fs.readlink = function readlink(path, callback) {
	throw new Error('readlink not yet implemented');
};

fs.readlinkSync = function readlinkSync(path) {
	throw new Error('readlinkSync not yet implemented');
};

fs.symlink = function symlink(destination, path, type_, callback) {
	throw new Error('symlink not yet implemented');
};

fs.symlinkSync = function symlinkSync(destination, path, type) {
	throw new Error('symlinkSync not yet implemented');
};

fs.link = function link(srcpath, dstpath, callback) {
	throw new Error('link not yet implemented');
};

fs.linkSync = function linkSync(srcpath, dstpath) {
	throw new Error('linkSync not yet implemented');
};

fs.unlink = function unlink(path, callback) {
	throw new Error('unlink not yet implemented');
};

fs.unlinkSync = function unlinkSync(path) {
	throw new Error('unlinkSync not yet implemented');
};

fs.fchmod = function fchmod(fd, mode, callback) {
	throw new Error('fchmod not yet implemented');
};

fs.fchmodSync = function fchmodSync(fd, mode) {
	throw new Error('fchmodSync not yet implemented');
};

fs.lchmod = function lchmod(path, mode, callback) {
	throw new Error('lchmod not yet implemented');
};

fs.lchmodSync = function lchmodSync(path, mode) {
	throw new Error('lchmodSync not yet implemented');
};

fs.chmod = function chmod(path, mode, callback) {
	throw new Error('chmod not yet implemented');
};

fs.chmodSync = function chmodSync(path, mode) {
	throw new Error('chmodSync not yet implemented');
};

fs.lchown = function lchown(path, uid, gid, callback) {
	throw new Error('lchown not yet implemented');
};

fs.lchownSync = function lchownSync(path, uid, gid) {
	throw new Error('lchownSync not yet implemented');
};

fs.fchown = function fchown(fd, uid, gid, callback) {
	throw new Error('fchown not yet implemented');
};

fs.fchownSync = function fchownSync(fd, uid, gid) {
	throw new Error('fchownSync not yet implemented');
};

fs.chown = function chown(path, uid, gid, callback) {
	throw new Error('chown not yet implemented');
};

fs.chownSync = function chownSync(path, uid, gid) {
	throw new Error('chownSync not yet implemented');
};

fs._toUnixTimestamp = function _toUnixTimestamp(time) {
	throw new Error('_toUnixTimestamp not yet implemented');
};

fs.utimes = function utimes(path, atime, mtime, callback) {
	throw new Error('utimes not yet implemented');
};

fs.utimesSync = function utimesSync(path, atime, mtime) {
	throw new Error('utimesSync not yet implemented');
};

fs.futimes = function futimes(fd, atime, mtime, callback) {
	throw new Error('futimes not yet implemented');
};

fs.futimesSync = function futimesSync(fd, atime, mtime) {
	throw new Error('futimesSync not yet implemented');
};

fs.writeFile = function writeFile(path, data, options, callback) {
	throw new Error('writeFile not yet implemented');
};

fs.writeFileSync = function writeFileSync(path, data, options) {
	throw new Error('writeFileSync not yet implemented');
};

fs.appendFile = function appendFile(path, data, options, callback_) {
	throw new Error('appendFile not yet implemented');
};

fs.appendFileSync = function appendFileSync(path, data, options) {
	throw new Error('appendFileSync not yet implemented');
};

fs.watch = function watch(filename) {
	throw new Error('watch not yet implemented');
};

fs.watchFile = function watchFile(filename) {
	throw new Error('watchFile not yet implemented');
};

fs.unwatchFile = function unwatchFile(filename, listener) {
	throw new Error('unwatchFile not yet implemented');
};

fs.realpathSync = function realpathSync(p, cache) {
	throw new Error('realpathSync not yet implemented');
};

fs.realpath = function realpath(p, cache, cb) {
	throw new Error('realpath not yet implemented');
};

fs.createReadStream = function createReadStream(path, options) {
	throw new Error('createReadStream not yet implemented');
};

fs.ReadStream = function ReadStream(path, options) {
	throw new Error('ReadStream not yet implemented');
};

fs.FileReadStream = function FileReadStream(path, options) {
	throw new Error('FileReadStream not yet implemented');
};

fs.createWriteStream = function createWriteStream(path, options) {
	throw new Error('createWriteStream not yet implemented');
};

fs.WriteStream = function WriteStream(path, options) {
	throw new Error('WriteStream not yet implemented');
};

fs.FileWriteStream = function FileWriteStream(path, options) {
	throw new Error('FileWriteStream not yet implemented');
};

fs.SyncWriteStream = function SyncWriteStream(fd, options) {
	throw new Error('SyncWriteStream not yet implemented');
};

function maybeCallback(o) {
	return o && util.isFunction(o) ? o : function(err) {
		if (err) { throw err; }
	};
}

function assertFlags(flags) {
	var tiMode = MODE_MAP[flags];
	if (!tiMode) {
		throw new Error('Unknown file open flag: ' + flags);
	}
	return tiMode;
}

function assertEncoding(encoding) {
	if (encoding && !Buffer.isEncoding(encoding)) {
		throw new Error('Unknown encoding: ' + encoding);
	}
}
<commit_msg>buffer and encoding conversions<commit_after>var $F = Ti.Filesystem,
	fs = exports,
	util = require('util');

var MODE_MAP = {};
MODE_MAP['r'] = MODE_MAP['r+'] = MODE_MAP['rs'] = MODE_MAP['rs+'] = $F.MODE_READ;
MODE_MAP['w'] = MODE_MAP['w+'] = MODE_MAP['wx'] = MODE_MAP['wx+'] = $F.MODE_WRITE;
MODE_MAP['a'] = MODE_MAP['a+'] = MODE_MAP['ax'] = MODE_MAP['ax+'] = $F.MODE_APPEND;

fs.Stats = function Stats(path) {
	this.__file = null;
	this.dev = 0;
	this.ino = 0;
	this.nlink = 0;
	this.uid = 0;
	this.gid = 0;
	this.rdev = 0;
	this.size = 0;
	this.blksize = 4096;
	this.blocks = 8;
	this.ctime = this.atime = this.mtime = 0;

	if (path) {
		this.__file = $F.getFile(path);
		this.size = this.__file.size;
		this.mode = 0;
		this.ctime = new Date(this.__file.createTimestamp());
		this.atime = this.mtime = new Date(this.__file.modificationTimestamp());
	}
};

fs.Stats.prototype.isDirectory = function(property) {
	return this.__file.isDirectory();
};

fs.Stats.prototype.isFile = function(property) {
	return this.__file.isFile();
};

fs.Stats.prototype.isBlockDevice = function(property) {
	return false;
};

fs.Stats.prototype.isCharacterDevice = function(property) {
	return false;
};

fs.Stats.prototype.isSymbolicLink = function(property) {
	return this.__file.symbolicLink;
};

fs.Stats.prototype.isFIFO = function(property) {
	return false;
};

fs.Stats.prototype.isSocket = function(property) {
	return false;
};

fs.exists = function exists(path, callback) {
	setTimeout(function() {
		return callback(fs.existsSync(path));
	}, 0);
};

fs.existsSync = function existsSync(path) {
	return $F.getFile(path).exists();
};

fs.readFile = function readFile(path, options, callback_) {
	throw new Error('readFile not yet implemented');
};

fs.readFileSync = function readFileSync(path, options) {
	// if (!options) {
 //    options = { encoding: null, flag: 'r' };
 //  } else if (util.isString(options)) {
 //    options = { encoding: options, flag: 'r' };
 //  } else if (!util.isObject(options)) {
 //    throw new TypeError('Bad arguments');
 //  }

 //  var encoding = options.encoding,
 //  	flag = options.flag || 'r';
 //  assertEncoding(options.encoding);

 //  var fd = fs.openSync(path, flag /*, mode */),
 //  	size = fs.fstatSync(fd).size;

 //  fs.closeSync(fd);
};

fs.close = function close(fd, callback) {
	setTimeout(function() {
		var err = null;
		try {
			fd.close();
		} catch (e) {
			err = e;
		}
		return callback(err);
	}, 0);
};

fs.closeSync = function closeSync(fd) {
	fd.close();
};

fs.open = function open(path, flags, mode, callback) {
	callback = maybeCallback(arguments[arguments.length-1]);
	if (!mode || util.isFunction(mode)) {
		mode = null;
	}

	setTimeout(function() {
		var fd = null,
			err = null;
		try {
			fd = fs.openSync(path, flags, mode);
		} catch (e) {
			err = e;
		}
		return callback(err, fd);
	}, 0);
};

fs.openSync = function openSync(path, flags, mode) {
	var tiMode = assertFlags(flags),
		file = $F.getFile(path),
		fd = file.open(tiMode);
	fd.__path = path;
	return fd;
};

fs.read = function read(fd, buffer, offset, length, position, callback) {
	// position is not handled in Titanium streams
	callback = maybeCallback(arguments[arguments.length-1]);
	if (util.isFunction(position)) { position = undefined; }
	if (util.isFunction(length)) { length = undefined; }
	if (util.isFunction(offset)) { offset = undefined; }

	// TODO: This should be Ti.Stream.read(), but it doesn't appear to do
	// anything when targeting a FileStream, despite the docs.
	setTimeout(function() {
		var bytes = null,
			err = null;
		try {
			bytes = fs.readSync(fd, buffer, offset, length, position);
		} catch (e) {
			err = e;
		}
		return callback(err, bytes, buffer);
	}, 0);
};

fs.readSync = function readSync(fd, buffer, offset, length, position) {
	// position is not handled in Titanium streams
	return fd.read(buffer, offset, length);
};

fs.write = function write(fd, buffer, offset, length, position, callback) {
	throw new Error('write not yet implemented');
};

fs.writeSync = function writeSync(fd, buffer, offset, length, position) {
	throw new Error('writeSync not yet implemented');
};

fs.rename = function rename(oldPath, newPath, callback) {
	throw new Error('rename not yet implemented');
};

fs.renameSync = function renameSync(oldPath, newPath) {
	throw new Error('renameSync not yet implemented');
};

fs.truncate = function truncate(path, len, callback) {
	throw new Error('truncate not yet implemented');
};

fs.truncateSync = function truncateSync(path, len) {
	throw new Error('truncateSync not yet implemented');
};

fs.ftruncate = function ftruncate(fd, len, callback) {
	throw new Error('ftruncate not yet implemented');
};

fs.ftruncateSync = function ftruncateSync(fd, len) {
	throw new Error('ftruncateSync not yet implemented');
};

fs.rmdir = function rmdir(path, callback) {
	throw new Error('rmdir not yet implemented');
};

fs.rmdirSync = function rmdirSync(path) {
	throw new Error('rmdirSync not yet implemented');
};

fs.fdatasync = function fdatasync(fd, callback) {
	throw new Error('fdatasync not yet implemented');
};

fs.fdatasyncSync = function fdatasyncSync(fd) {
	throw new Error('fdatasyncSync not yet implemented');
};

fs.fsync = function fsync(fd, callback) {
	throw new Error('fsync not yet implemented');
};

fs.fsyncSync = function fsyncSync(fd) {
	throw new Error('fsyncSync not yet implemented');
};

fs.mkdir = function mkdir(path, mode, callback) {
	throw new Error('mkdir not yet implemented');
};

fs.mkdirSync = function mkdirSync(path, mode) {
	throw new Error('mkdirSync not yet implemented');
};

fs.readdir = function readdir(path, callback) {
	throw new Error('readdir not yet implemented');
};

fs.readdirSync = function readdirSync(path) {
	throw new Error('readdirSync not yet implemented');
};

fs.fstat = function fstat(fd, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.fstatSync(fd);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.lstat = function lstat(path, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.lstatSync(path);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.stat = function stat(path, callback) {
	setTimeout(function() {
		var stats = null,
			err = null;
		try {
			stats = fs.statSync(path);
		} catch (e) {
			err = e;
		}
		return callback(err, stats);
	}, 0);
};

fs.fstatSync = function fstatSync(fd) {
	if (fd.__path) {
		return fs.statSync(fd.__path);
	} else {
		throw new Error('invalid file descriptor');
	}
};

fs.lstatSync = function lstatSync(path) {
	return fs.statSync(path);
};

fs.statSync = function statSync(path) {
	return new fs.Stats(path);
};

fs.readlink = function readlink(path, callback) {
	throw new Error('readlink not yet implemented');
};

fs.readlinkSync = function readlinkSync(path) {
	throw new Error('readlinkSync not yet implemented');
};

fs.symlink = function symlink(destination, path, type_, callback) {
	throw new Error('symlink not yet implemented');
};

fs.symlinkSync = function symlinkSync(destination, path, type) {
	throw new Error('symlinkSync not yet implemented');
};

fs.link = function link(srcpath, dstpath, callback) {
	throw new Error('link not yet implemented');
};

fs.linkSync = function linkSync(srcpath, dstpath) {
	throw new Error('linkSync not yet implemented');
};

fs.unlink = function unlink(path, callback) {
	throw new Error('unlink not yet implemented');
};

fs.unlinkSync = function unlinkSync(path) {
	throw new Error('unlinkSync not yet implemented');
};

fs.fchmod = function fchmod(fd, mode, callback) {
	throw new Error('fchmod not yet implemented');
};

fs.fchmodSync = function fchmodSync(fd, mode) {
	throw new Error('fchmodSync not yet implemented');
};

fs.lchmod = function lchmod(path, mode, callback) {
	throw new Error('lchmod not yet implemented');
};

fs.lchmodSync = function lchmodSync(path, mode) {
	throw new Error('lchmodSync not yet implemented');
};

fs.chmod = function chmod(path, mode, callback) {
	throw new Error('chmod not yet implemented');
};

fs.chmodSync = function chmodSync(path, mode) {
	throw new Error('chmodSync not yet implemented');
};

fs.lchown = function lchown(path, uid, gid, callback) {
	throw new Error('lchown not yet implemented');
};

fs.lchownSync = function lchownSync(path, uid, gid) {
	throw new Error('lchownSync not yet implemented');
};

fs.fchown = function fchown(fd, uid, gid, callback) {
	throw new Error('fchown not yet implemented');
};

fs.fchownSync = function fchownSync(fd, uid, gid) {
	throw new Error('fchownSync not yet implemented');
};

fs.chown = function chown(path, uid, gid, callback) {
	throw new Error('chown not yet implemented');
};

fs.chownSync = function chownSync(path, uid, gid) {
	throw new Error('chownSync not yet implemented');
};

fs._toUnixTimestamp = function _toUnixTimestamp(time) {
	throw new Error('_toUnixTimestamp not yet implemented');
};

fs.utimes = function utimes(path, atime, mtime, callback) {
	throw new Error('utimes not yet implemented');
};

fs.utimesSync = function utimesSync(path, atime, mtime) {
	throw new Error('utimesSync not yet implemented');
};

fs.futimes = function futimes(fd, atime, mtime, callback) {
	throw new Error('futimes not yet implemented');
};

fs.futimesSync = function futimesSync(fd, atime, mtime) {
	throw new Error('futimesSync not yet implemented');
};

fs.writeFile = function writeFile(path, data, options, callback) {
	throw new Error('writeFile not yet implemented');
};

fs.writeFileSync = function writeFileSync(path, data, options) {
	throw new Error('writeFileSync not yet implemented');
};

fs.appendFile = function appendFile(path, data, options, callback_) {
	throw new Error('appendFile not yet implemented');
};

fs.appendFileSync = function appendFileSync(path, data, options) {
	throw new Error('appendFileSync not yet implemented');
};

fs.watch = function watch(filename) {
	throw new Error('watch not yet implemented');
};

fs.watchFile = function watchFile(filename) {
	throw new Error('watchFile not yet implemented');
};

fs.unwatchFile = function unwatchFile(filename, listener) {
	throw new Error('unwatchFile not yet implemented');
};

fs.realpathSync = function realpathSync(p, cache) {
	throw new Error('realpathSync not yet implemented');
};

fs.realpath = function realpath(p, cache, cb) {
	throw new Error('realpath not yet implemented');
};

fs.createReadStream = function createReadStream(path, options) {
	throw new Error('createReadStream not yet implemented');
};

fs.ReadStream = function ReadStream(path, options) {
	throw new Error('ReadStream not yet implemented');
};

fs.FileReadStream = function FileReadStream(path, options) {
	throw new Error('FileReadStream not yet implemented');
};

fs.createWriteStream = function createWriteStream(path, options) {
	throw new Error('createWriteStream not yet implemented');
};

fs.WriteStream = function WriteStream(path, options) {
	throw new Error('WriteStream not yet implemented');
};

fs.FileWriteStream = function FileWriteStream(path, options) {
	throw new Error('FileWriteStream not yet implemented');
};

fs.SyncWriteStream = function SyncWriteStream(fd, options) {
	throw new Error('SyncWriteStream not yet implemented');
};

function maybeCallback(o) {
	return o && util.isFunction(o) ? o : function(err) {
		if (err) { throw err; }
	};
}

function assertFlags(flags) {
	var tiMode = MODE_MAP[flags];
	if (!tiMode) {
		throw new Error('Unknown file open flag: ' + flags);
	}
	return tiMode;
}

var ENCODINGS = ['ascii','utf8','utf-8','base64','binary','blob'];
function assertEncoding(encoding) {
	if (encoding && ENCODINGS.indexOf(encoding.toLowerCase()) === -1) {
		throw new Error('Unknown encoding: ' + encoding);
	}
}

function convertBuffer(buffer, encoding) {
	switch(encoding.toLowerCase()) {
		case 'ascii':
		case 'binary':
			var ret = '';
			for (var i = 0; i < buffer.length; i++) {
				ret += String.fromCharCode(Ti.Codec.decodeNumber({
					source: buffer,
					type: Ti.Codec.TYPE_BYTE,
					position: i
				}));
			}
			return ret;
		case 'utf8':
		case 'utf-8':
			return buffer.toString();
		case 'base64':
			return Ti.Utils.base64encode(buffer.toString()).toString();
		case 'blob':
			return buffer.toBlob();
		default:
			throw new Error('Unknown encoding: ' + encoding);
	}
}
<|endoftext|>


<commit_before>// Packages
const ghgot = require('gh-got');
const moment = require('moment');

// Mine
const getResponse = query => {
  const token = require('../config.json').token || false;

  if (!token) {
    throw new Error(`token is not defined`);
  }

  return ghgot('https://api.github.com/graphql', {
    json: true,
    headers: { authorization: `bearer ${token}` },
    body: { query }
  });
};

exports.tools = {
  status: () => {
    return new Promise((resolve, reject) => {
      ghgot('https://status.github.com/api/last-message.json')
        .then(response => {
          let data = response.body;

          resolve({
            status: `${data.status} 🦄`,
            msg: data.body,
            date: moment(data.created_on).format('MMMM DD YYYY HH:mm')
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  radar: () => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          issues(first: 1, labels: "O: radar", states: OPEN) {
            edges {
              node {
                url
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.issues.edges[0].node.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  repo: repo => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "${repo}") {
          url
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  territory: territory => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          issues(first: 100, states: OPEN, labels: "ST: ${territory}") {
            totalCount
          }
          url,
          projects(first: 10, search: "ST: EMEA") {
            nodes {
              url
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          resolve({
            url: response.body.data.repository.url
              ? `${response.body.data.repository.url}/issues?q=is:open is:issue label:"ST: ${territory}"`
              : null,
            count: Number.parseInt(
              response.body.data.repository.issues.totalCount
            ),
            project: response.body.data.repository.projects.nodes[0].url
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};
<commit_msg>Refine territory query<commit_after>// Packages
const ghgot = require('gh-got');
const moment = require('moment');

// Mine
const getResponse = query => {
  const token = require('../config.json').token || false;

  if (!token) {
    throw new Error(`token is not defined`);
  }

  return ghgot('https://api.github.com/graphql', {
    json: true,
    headers: { authorization: `bearer ${token}` },
    body: { query }
  });
};

exports.tools = {
  status: () => {
    return new Promise((resolve, reject) => {
      ghgot('https://status.github.com/api/last-message.json')
        .then(response => {
          let data = response.body;

          resolve({
            status: `${data.status} 🦄`,
            msg: data.body,
            date: moment(data.created_on).format('MMMM DD YYYY HH:mm')
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  radar: () => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          issues(first: 1, labels: "O: radar", states: OPEN) {
            edges {
              node {
                url
              }
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.issues.edges[0].node.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  repo: repo => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "${repo}") {
          url
        }
      }`;

      getResponse(query)
        .then(response => {
          let url = response.body.data.repository.url;

          resolve(`${url}`);
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  territory: territory => {
    return new Promise((resolve, reject) => {
      let query = `query {
        repository(owner: "github", name: "services") {
          url
          issues(states: OPEN, labels: "ST: ${territory}") {
            totalCount
          }
          projects(search: "ST: ${territory}") {
            nodes {
              url
            }
          }
        }
      }`;

      getResponse(query)
        .then(response => {
          resolve({
            url: response.body.data.repository.url
              ? `${response.body.data.repository.url}/issues?q=is:open is:issue label:"ST: ${territory}"`
              : null,
            count: Number.parseInt(
              response.body.data.repository.issues.totalCount
            ),
            project: response.body.data.repository.projects.nodes[0].url
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};
<|endoftext|>


<commit_before>/**
 * TODO: Better Docs -- TomF is a terrible person
 * @desc track() send prop to sitecat
 */
import log from './log';

function track(prop, goalName) {
  log('goal:', prop, goalName);
  if (!window.s) return log('goal error: window.s undefined');
  if (!s.tl) return log('goal error: s.tl undefined');
  s.linkTrackVars = prop;
  s.linkTrackEvents = 'None';
  s[prop] = goalName; // unique
  s.tl(true, 'o', 'Clearhead Goal'); // static params / do not update
}

export default track;
<commit_msg>Update track.js<commit_after>/**
 * @desc track() send prop to sitecat
 */
import log from './log';

function track(prop, goalName) {
  log('goal:', prop, goalName);
  if (!window.s) return log('goal error: window.s undefined');
  if (!s.tl) return log('goal error: s.tl undefined');
  s.linkTrackVars = prop;
  s.linkTrackEvents = 'None';
  s[prop] = goalName; // unique
  s.tl(true, 'o', 'Clearhead Goal'); // static params / do not update
}

export default track;
<|endoftext|>


<commit_before>import path  from 'path';

/**
 * @exports
 * @class Util
 * @desc Implements utility methods
 */
export default class Util {
    /**
     * Checks if given object is instance of Object
     * @param {Object|*} obj
     * @returns {boolean} true if obj is instance of Object class
     * @static
     */
    static isObject(obj) {
        return !!obj && typeof obj === 'object';
    }

    /**
     * Checks if given object is instance of Function
     * @param {Object|*} obj
     * @returns {boolean} true if obj is Function
     * @static
     */
    static isFunction(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
    }

    /**
     * Checks if given object is instance of String
     * @param {Object|*} obj
     * @returns {boolean} true if obj is String
     * @static
     */
    static isString(obj) {
        return typeof obj === 'string' || obj instanceof String;
    }

    static getConfigurationDirectory() {
        return path.join(process.cwd(), './configs');
    }
}
<commit_msg>Add utility method for resolving path to reports folder<commit_after>import path  from 'path';

/**
 * @exports
 * @class Util
 * @desc Implements utility methods
 */
export default class Util {
    /**
     * Checks if given object is instance of Object
     * @param {Object|*} obj
     * @returns {boolean} true if obj is instance of Object class
     * @static
     */
    static isObject(obj) {
        return !!obj && typeof obj === 'object';
    }

    /**
     * Checks if given object is instance of Function
     * @param {Object|*} obj
     * @returns {boolean} true if obj is Function
     * @static
     */
    static isFunction(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
    }

    /**
     * Checks if given object is instance of String
     * @param {Object|*} obj
     * @returns {boolean} true if obj is String
     * @static
     */
    static isString(obj) {
        return typeof obj === 'string' || obj instanceof String;
    }

    static getConfigurationDirectory() {
        return path.join(process.cwd(), './configs');
    }

    static getReportsDirectory() {
        return path.join(process.cwd(), './reports');
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of his
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

define([], function() {
  "use strict";

  /**
   * Copy an object 1 level deep
   * @param {object} src object to copy
   * @return {object} the copy
   */
  function shallowCopy(src) {
    var dst = {};
    Object.keys(src).forEach(function(key) {
      dst[key] = src[key];
    });
    return dst;
  }

  /**
   * Copy named properties
   *
   * @param {string[]} names names of properties to copy
   * @param {object} src object to copy properties from
   * @param {object} dst object to copy properties to
   */
  function copyNamedProperties(names, src, dst) {
    names.forEach(function(name) {
      var value = src[name];
      if (value !== undefined) {
        dst[name] = value;
      }
    });
  }

  /**
   * Copies properties from source to dest only if a matching key is in dest
   *
   * @param {Object.<string, ?>} src the source
   * @param {Object.<string, ?>} dst the dest
   */
  function copyExistingProperties(src, dst) {
    Object.keys(dst).forEach(function(key) {
      if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) {
        dst[key] = src[key];
      }
    });
  }

  /**
   * Gets the gl version as a number
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {number} version of gl
   */
  //function getVersionAsNumber(gl) {
  //  return parseFloat(gl.getParameter(gl.VERSION).substr(6));
  //}

  /**
   * Check if context is WebGL 2.0
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {bool} true if it's WebGL 2.0
   * @memberOf module:twgl
   */
  function isWebGL2(gl) {
    // This is the correct check but it's slow
    //return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0") === 0;
    // This might also be the correct check but I'm assuming it's slow-ish
    // return gl instanceof WebGL2RenderingContext;
    return !!gl.texStorage2D;
  }

  /**
   * Check if context is WebGL 1.0
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {bool} true if it's WebGL 1.0
   * @memberOf module:twgl
   */
  function isWebGL1(gl) {
    // This is the correct check but it's slow
    //var version = getVersionAsNumber(gl);
    //return version <= 1.0 && version > 0.0;  // because as of 2016/5 Edge returns 0.96
    // This might also be the correct check but I'm assuming it's slow-ish
    // return gl instanceof WebGLRenderingContext;
    return !gl.texStorage2D;
  }

  var error =
      (    window.console
        && window.console.error
        && typeof window.console.error === "function"
      )
      ? window.console.error.bind(window.console)
      : function() { };

  var warn =
      (    window.console
        && window.console.warn
        && typeof window.console.warn === "function"
      )
      ? window.console.warn.bind(window.console)
      : function() { };

  return {
    copyExistingProperties: copyExistingProperties,
    copyNamedProperties: copyNamedProperties,
    shallowCopy: shallowCopy,
    isWebGL1: isWebGL1,
    isWebGL2: isWebGL2,
    error: error,
    warn: warn,
  };
});

<commit_msg>formatting<commit_after>/*
 * Copyright 2015, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of his
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

define([], function() {
  "use strict";

  /**
   * Copy an object 1 level deep
   * @param {object} src object to copy
   * @return {object} the copy
   */
  function shallowCopy(src) {
    var dst = {};
    Object.keys(src).forEach(function(key) {
      dst[key] = src[key];
    });
    return dst;
  }

  /**
   * Copy named properties
   *
   * @param {string[]} names names of properties to copy
   * @param {object} src object to copy properties from
   * @param {object} dst object to copy properties to
   */
  function copyNamedProperties(names, src, dst) {
    names.forEach(function(name) {
      var value = src[name];
      if (value !== undefined) {
        dst[name] = value;
      }
    });
  }

  /**
   * Copies properties from source to dest only if a matching key is in dest
   *
   * @param {Object.<string, ?>} src the source
   * @param {Object.<string, ?>} dst the dest
   */
  function copyExistingProperties(src, dst) {
    Object.keys(dst).forEach(function(key) {
      if (dst.hasOwnProperty(key) && src.hasOwnProperty(key)) {
        dst[key] = src[key];
      }
    });
  }

  /**
   * Gets the gl version as a number
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {number} version of gl
   */
  //function getVersionAsNumber(gl) {
  //  return parseFloat(gl.getParameter(gl.VERSION).substr(6));
  //}

  /**
   * Check if context is WebGL 2.0
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {bool} true if it's WebGL 2.0
   * @memberOf module:twgl
   */
  function isWebGL2(gl) {
    // This is the correct check but it's slow
    //  return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0") === 0;
    // This might also be the correct check but I'm assuming it's slow-ish
    // return gl instanceof WebGL2RenderingContext;
    return !!gl.texStorage2D;
  }

  /**
   * Check if context is WebGL 1.0
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @return {bool} true if it's WebGL 1.0
   * @memberOf module:twgl
   */
  function isWebGL1(gl) {
    // This is the correct check but it's slow
    //var version = getVersionAsNumber(gl);
    //return version <= 1.0 && version > 0.0;  // because as of 2016/5 Edge returns 0.96
    // This might also be the correct check but I'm assuming it's slow-ish
    // return gl instanceof WebGLRenderingContext;
    return !gl.texStorage2D;
  }

  var error =
      (    window.console
        && window.console.error
        && typeof window.console.error === "function"
      )
      ? window.console.error.bind(window.console)
      : function() { };

  var warn =
      (    window.console
        && window.console.warn
        && typeof window.console.warn === "function"
      )
      ? window.console.warn.bind(window.console)
      : function() { };

  return {
    copyExistingProperties: copyExistingProperties,
    copyNamedProperties: copyNamedProperties,
    shallowCopy: shallowCopy,
    isWebGL1: isWebGL1,
    isWebGL2: isWebGL2,
    error: error,
    warn: warn,
  };
});

<|endoftext|>