<commit_before>'use strict';

// MODULES //

var arrayLike = require( 'validate.io-array-like' ),
	typeName = require( 'type-name' ),
	dtype = require( 'dstructs-array-dtype' ),
	getCtor = require( 'dstructs-array-constructors' );

// CAST //

/**
* FUNCTION: cast( x, type )
*	Casts an input array or array-like object to a specified type.
*
* @param {Object|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} x - value to cast
* @param {String|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} type - type to which to cast or a value from which the desired type should be inferred
* @returns {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} casted value
*/
function cast( x, type ) {
	/* jshint newcap:false */
	var ctor,
		len,
		d,
		i;

	if ( !arrayLike( x ) ) {
		throw new TypeError( 'invalid input argument. First argument must be an array-like object. Value: `' + x + '`.' );
	}
	if ( typeof type === 'string' ) {
		ctor = getCtor( type );
	} else {
		ctor = getCtor( dtype( typeName( type ) ) );
	}
	if ( ctor === null ) {
		throw new Error( 'invalid input argument. Unrecognized/unsupported type to which to cast. Value: `' + type + '`.' );
	}
	len = x.length;
	d = new ctor( len );
	for ( i = 0; i < len; i++ ) {
		d[ i ] = x[ i ];
	}
	return d;
} // end FUNCTION cast()

// EXPORTS //

module.exports = cast;
<commit_msg>Add string to accepted input types since array-like<commit_after>'use strict';

// MODULES //

var arrayLike = require( 'validate.io-array-like' ),
	typeName = require( 'type-name' ),
	dtype = require( 'dstructs-array-dtype' ),
	getCtor = require( 'dstructs-array-constructors' );

// CAST //

/**
* FUNCTION: cast( x, type )
*	Casts an input array or array-like object to a specified type.
*
* @param {String|Object|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} x - value to cast
* @param {String|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} type - type to which to cast or a value from which the desired type should be inferred
* @returns {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} casted value
*/
function cast( x, type ) {
	/* jshint newcap:false */
	var ctor,
		len,
		d,
		i;

	if ( !arrayLike( x ) ) {
		throw new TypeError( 'invalid input argument. First argument must be an array-like object. Value: `' + x + '`.' );
	}
	if ( typeof type === 'string' ) {
		ctor = getCtor( type );
	} else {
		ctor = getCtor( dtype( typeName( type ) ) );
	}
	if ( ctor === null ) {
		throw new Error( 'invalid input argument. Unrecognized/unsupported type to which to cast. Value: `' + type + '`.' );
	}
	len = x.length;
	d = new ctor( len );
	for ( i = 0; i < len; i++ ) {
		d[ i ] = x[ i ];
	}
	return d;
} // end FUNCTION cast()

// EXPORTS //

module.exports = cast;
<|endoftext|>


<commit_before>'use strict';

var remove        = require('es5-ext/lib/Array/prototype/remove')
  , isFunction    = require('es5-ext/lib/Function/is-function')
  , d             = require('es5-ext/lib/Object/descriptor')
  , extend        = require('es5-ext/lib/Object/extend-properties')
  , combineErrors = require('../utils/combine-errors')
  , serialize     = require('../utils/serialize')
  , getIndexKey   = require('../utils/get-index-key')
  , objects       = require('../objects')
  , proto         = require('../_proto')
  , relation      = require('../_relation')
  , RelTransport  = require('../_relation/transport')

  , slice = Array.prototype.slice
  , create = Object.create, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getPrototypeOf = Object.getPrototypeOf

  , nameRe = /^[A-Z][0-9a-zA-Z]*$/
  , Base, baseProto, rel, setRelationProto, setItemProto;

setItemProto = function (item) {
	var old = getPrototypeOf(item), nu = this._setItem_;

	remove.call(old._children_, item);
	item.__proto__ = nu;
	if (!nu.hasOwnProperty('_children_')) {
		defineProperty(nu, '_children_', d('', []));
	}
	nu._children_.push(item);

	item._forEachRelation_(setRelationProto.bind(nu));
};

setRelationProto = function (rel) {
	var nu = this['_' + rel.name], old = getPrototypeOf(rel), key, index;

	// Clear old setup
	remove.call(old._children_, rel);

	// Update
	rel.__proto__ = nu;

	// Setup new
	if (!nu.hasOwnProperty('_children_')) {
		defineProperty(nu, '_children_', d('', []));
	}
	nu._children_.push(rel);

	// Fix indexing
	if (rel.hasOwnProperty('__index_')) {
		rel.__index_.setParent(nu._selfIndex_);
	} else if ((key = getIndexKey(rel.__value))) {
		if (old.__index_) old.__index_.delete(key, rel.obj);
		if ((index = rel._index_)) index.add(key, rel.obj);
	}

	// Update value if inherited
	if (!rel.hasOwnProperty('_value')) rel._update_();

	// Update base set item proto
	if (rel.hasOwnProperty('__setItem_')) setItemProto.call(nu, rel.__setItem_);

	// Update relations proto
	rel._forEachRelation_(setRelationProto.bind(nu));
};

Base = module.exports = objects.Base = function Self(value) {
	return Self.is(value) ? value :
			Self.prototype.create.apply(Self.prototype, arguments);
};
Base.__proto__ = proto;
extend(Base, Function.prototype);
delete Base.toString;

defineProperties(Base, {
	_id_: d('', 'Base'),
	_type_: d('c', 'namespace'),
	_childType_: d('c', 'primitive'),
	Base: d('ce', Base),
	create: d('c', function (name) {
		var error = this.validateCreate.apply(this, arguments);
		if (error) throw error;
		return this.$create.apply(this, arguments);
	}),
	validateCreate: d('c', function (name) {
		if (!nameRe.test(name)) return new Error(name + " is not a valid name");
		if (name in Base) return new Error(name + " is already taken");
		return this.validateConstruction.apply(this, slice.call(arguments, 1));
	}),
	$create: d('c', function (name) {
		var constructor = this.$$create(name);
		constructor._signal_(this);
		constructor.$construct.apply(constructor, slice.call(arguments, 1));
		return constructor;
	}),
	$$create: d('c', function (id) {
		var constructor = function Self(value) {
			return Self.is(value) ? value :
					Self.prototype.create.apply(Self.prototype, arguments);
		};
		constructor.__proto__ = this;
		objects[id] = defineProperty(constructor, '_id_', d('', id));
		objects[id + '#'] = constructor.prototype = create(this.prototype, {
			constructor: d(constructor),
			ns: d(constructor),
			_id_: d('', id + '#')
		});
		if (!this.hasOwnProperty('_children_')) {
			defineProperty(this, '_children_', d('', []));
		}
		if (!this.prototype.hasOwnProperty('_children_')) {
			defineProperty(this.prototype, '_children_', d('', []));
		}
		this._children_.push(constructor);
		this.prototype._children_.push(constructor.prototype);
		return (Base[id] = constructor);
	}),
	$$setValue: d('c', function (nu) {
		var old = getPrototypeOf(this);
		if (!nu) nu = Base;
		if (old === nu) return;

		this.__proto__ = nu;
		this.prototype.__proto__ = nu.prototype;

		remove.call(old._children_, this);
		remove.call(old.prototype._children_, this.prototype);
		if (!nu.hasOwnProperty('_children_')) {
			defineProperty(nu, '_children_', d('', []));
		}
		if (!nu.prototype.hasOwnProperty('_children_')) {
			defineProperty(nu.prototype, '_children_', d('', []));
		}
		nu._children_.push(this);
		nu.prototype._children_.push(this);

		if (old === Base) Base[this._id_] = this;
		if (nu === Base) delete Base[this._id_];

		// Fix relations proto
		this._forEachRelation_(setRelationProto.bind(nu));
		this.prototype._forEachRelation_(setRelationProto.bind(nu.prototype));
	}),
	rel: d('c', function (data) {
		if (data == null) return this;
		return new RelTransport(this, data);
	}),
	required: d.gs('c', function () {
		return new RelTransport(this, { required: true });
	}),
	_serialize_: d('c', serialize)
});

objects['Base#'] = baseProto = Base.prototype = create(proto, {
	_id_: d('', 'Base#'),
	_type_: d('prototype'),
	constructor: d(Base),
	ns: d(Base),
	create: d(Base.create),
	validateCreate: d(function (value) {
		if (!serialize(value)) {
			return new TypeError(value + ' is not valid dbjs value');
		}
		return null;
	}),
	$create: d(function (value) { return value; }),
	$$create: d(function (id) {
		var obj, ns;
		obj = proto.$$create.call(this, id);
		if (this._type_ === 'prototype') defineProperty(obj, '_type_', d('object'));
		ns = this.ns;
		while (ns._type_ && (ns !== Base)) {
			ns[id] = obj;
			ns = getPrototypeOf(ns);
		}
		return obj;
	}),
	$$setValue: d(function (nu) {
		var ns, old, id;
		if (!nu) nu = baseProto;
		old = getPrototypeOf(this);
		if (old === nu) return;
		this.__proto__ = nu;

		remove.call(old._children_, this);
		if (!nu.hasOwnProperty('_children_')) {
			defineProperty(nu, '_children_', d('', []));
		}
		nu._children_.push(this);

		ns = old.ns;
		id = this._id_;
		while (ns._type_ && (ns !== Base)) {
			delete ns[id];
			ns = getPrototypeOf(ns);
		}
		ns = nu.ns;
		while (ns._type_ && (ns !== Base)) {
			ns[id] = this;
			ns = getPrototypeOf(ns);
		}

		// Fix relations proto
		this._forEachRelation_(setRelationProto.bind(nu));
	})
});
proto._children_.push(Base, Base.prototype);

relation.__ns.$$setValue(Base);
rel = Base._getRel_('$construct');
rel.$$setValue(function (construct, nsProps, objProps) {
	if (!isFunction(construct)) {
		objProps = nsProps;
		nsProps = construct;
		construct = null;
	} else if (!nsProps) {
		nsProps = { $construct: construct };
	} else {
		nsProps.$construct = construct;
	}

	if (nsProps) this.$setProperties(nsProps);
	if (objProps) this.prototype.$setProperties(objProps);
});
rel._required.$$setValue(true);

rel = Base._getRel_('validateConstruction');
rel.$$setValue(function (construct, nsProps, objProps) {
	var error;
	if (!isFunction(construct)) {
		objProps = nsProps;
		nsProps = construct;
		construct = null;
	} else if (!nsProps) {
		nsProps = { construct: construct };
	} else {
		nsProps.construct = construct;
	}

	error = combineErrors(nsProps && this.validateCreateProperties(nsProps),
		objProps && this.prototype.validateCreateProperties(objProps));
	if (!error) return null;
	error.message = "Invalid properties";
	return error;
});
rel._required.$$setValue(true);

rel = Base._getRel_('is');
rel.$$setValue(function (value) { return true; });
rel._required.$$setValue(true);

rel = Base._getRel_('normalize');
rel.$$setValue(function (value) { return value; });
rel._required.$$setValue(true);

Base._toString.$$setValue(Function.prototype.toString);
<commit_msg>Fix index proto fix logic<commit_after>'use strict';

var remove        = require('es5-ext/lib/Array/prototype/remove')
  , isFunction    = require('es5-ext/lib/Function/is-function')
  , d             = require('es5-ext/lib/Object/descriptor')
  , extend        = require('es5-ext/lib/Object/extend-properties')
  , combineErrors = require('../utils/combine-errors')
  , serialize     = require('../utils/serialize')
  , getIndexKey   = require('../utils/get-index-key')
  , objects       = require('../objects')
  , proto         = require('../_proto')
  , relation      = require('../_relation')
  , RelTransport  = require('../_relation/transport')

  , slice = Array.prototype.slice
  , create = Object.create, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getPrototypeOf = Object.getPrototypeOf

  , nameRe = /^[A-Z][0-9a-zA-Z]*$/
  , Base, baseProto, rel, setRelationProto, setItemProto;

setItemProto = function (item) {
	var old = getPrototypeOf(item), nu = this._setItem_;

	remove.call(old._children_, item);
	item.__proto__ = nu;
	if (!nu.hasOwnProperty('_children_')) {
		defineProperty(nu, '_children_', d('', []));
	}
	nu._children_.push(item);

	item._forEachRelation_(setRelationProto.bind(nu));
};

setRelationProto = function (rel) {
	var nu = this['_' + rel.name], old = getPrototypeOf(rel), key, index;

	// Clear old setup
	remove.call(old._children_, rel);

	// Update
	rel.__proto__ = nu;

	// Setup new
	if (!nu.hasOwnProperty('_children_')) {
		defineProperty(nu, '_children_', d('', []));
	}
	nu._children_.push(rel);

	// Fix indexing
	if (rel.obj && (rel.obj._type_ === 'prototype')) {
		if (rel.hasOwnProperty('__index_')) rel.__index_.setParent(nu._selfIndex_);
	} else if (rel.obj && (rel.obj._type_ === 'object')) {
		if ((key = getIndexKey(rel.__value))) {
			if (old.__index_) old.__index_.delete(key, rel.obj);
			if ((index = rel._index_)) index.add(key, rel.obj);
		}
	}

	// Update value if inherited
	if (!rel.hasOwnProperty('_value')) rel._update_();

	// Update base set item proto
	if (rel.hasOwnProperty('__setItem_')) setItemProto.call(nu, rel.__setItem_);

	// Update relations proto
	rel._forEachRelation_(setRelationProto.bind(nu));
};

Base = module.exports = objects.Base = function Self(value) {
	return Self.is(value) ? value :
			Self.prototype.create.apply(Self.prototype, arguments);
};
Base.__proto__ = proto;
extend(Base, Function.prototype);
delete Base.toString;

defineProperties(Base, {
	_id_: d('', 'Base'),
	_type_: d('c', 'namespace'),
	_childType_: d('c', 'primitive'),
	Base: d('ce', Base),
	create: d('c', function (name) {
		var error = this.validateCreate.apply(this, arguments);
		if (error) throw error;
		return this.$create.apply(this, arguments);
	}),
	validateCreate: d('c', function (name) {
		if (!nameRe.test(name)) return new Error(name + " is not a valid name");
		if (name in Base) return new Error(name + " is already taken");
		return this.validateConstruction.apply(this, slice.call(arguments, 1));
	}),
	$create: d('c', function (name) {
		var constructor = this.$$create(name);
		constructor._signal_(this);
		constructor.$construct.apply(constructor, slice.call(arguments, 1));
		return constructor;
	}),
	$$create: d('c', function (id) {
		var constructor = function Self(value) {
			return Self.is(value) ? value :
					Self.prototype.create.apply(Self.prototype, arguments);
		};
		constructor.__proto__ = this;
		objects[id] = defineProperty(constructor, '_id_', d('', id));
		objects[id + '#'] = constructor.prototype = create(this.prototype, {
			constructor: d(constructor),
			ns: d(constructor),
			_id_: d('', id + '#')
		});
		if (!this.hasOwnProperty('_children_')) {
			defineProperty(this, '_children_', d('', []));
		}
		if (!this.prototype.hasOwnProperty('_children_')) {
			defineProperty(this.prototype, '_children_', d('', []));
		}
		this._children_.push(constructor);
		this.prototype._children_.push(constructor.prototype);
		return (Base[id] = constructor);
	}),
	$$setValue: d('c', function (nu) {
		var old = getPrototypeOf(this);
		if (!nu) nu = Base;
		if (old === nu) return;

		this.__proto__ = nu;
		this.prototype.__proto__ = nu.prototype;

		remove.call(old._children_, this);
		remove.call(old.prototype._children_, this.prototype);
		if (!nu.hasOwnProperty('_children_')) {
			defineProperty(nu, '_children_', d('', []));
		}
		if (!nu.prototype.hasOwnProperty('_children_')) {
			defineProperty(nu.prototype, '_children_', d('', []));
		}
		nu._children_.push(this);
		nu.prototype._children_.push(this);

		if (old === Base) Base[this._id_] = this;
		if (nu === Base) delete Base[this._id_];

		// Fix relations proto
		this._forEachRelation_(setRelationProto.bind(nu));
		this.prototype._forEachRelation_(setRelationProto.bind(nu.prototype));
	}),
	rel: d('c', function (data) {
		if (data == null) return this;
		return new RelTransport(this, data);
	}),
	required: d.gs('c', function () {
		return new RelTransport(this, { required: true });
	}),
	_serialize_: d('c', serialize)
});

objects['Base#'] = baseProto = Base.prototype = create(proto, {
	_id_: d('', 'Base#'),
	_type_: d('prototype'),
	constructor: d(Base),
	ns: d(Base),
	create: d(Base.create),
	validateCreate: d(function (value) {
		if (!serialize(value)) {
			return new TypeError(value + ' is not valid dbjs value');
		}
		return null;
	}),
	$create: d(function (value) { return value; }),
	$$create: d(function (id) {
		var obj, ns;
		obj = proto.$$create.call(this, id);
		if (this._type_ === 'prototype') defineProperty(obj, '_type_', d('object'));
		ns = this.ns;
		while (ns._type_ && (ns !== Base)) {
			ns[id] = obj;
			ns = getPrototypeOf(ns);
		}
		return obj;
	}),
	$$setValue: d(function (nu) {
		var ns, old, id;
		if (!nu) nu = baseProto;
		old = getPrototypeOf(this);
		if (old === nu) return;
		this.__proto__ = nu;

		remove.call(old._children_, this);
		if (!nu.hasOwnProperty('_children_')) {
			defineProperty(nu, '_children_', d('', []));
		}
		nu._children_.push(this);

		ns = old.ns;
		id = this._id_;
		while (ns._type_ && (ns !== Base)) {
			delete ns[id];
			ns = getPrototypeOf(ns);
		}
		ns = nu.ns;
		while (ns._type_ && (ns !== Base)) {
			ns[id] = this;
			ns = getPrototypeOf(ns);
		}

		// Fix relations proto
		this._forEachRelation_(setRelationProto.bind(nu));
	})
});
proto._children_.push(Base, Base.prototype);

relation.__ns.$$setValue(Base);
rel = Base._getRel_('$construct');
rel.$$setValue(function (construct, nsProps, objProps) {
	if (!isFunction(construct)) {
		objProps = nsProps;
		nsProps = construct;
		construct = null;
	} else if (!nsProps) {
		nsProps = { $construct: construct };
	} else {
		nsProps.$construct = construct;
	}

	if (nsProps) this.$setProperties(nsProps);
	if (objProps) this.prototype.$setProperties(objProps);
});
rel._required.$$setValue(true);

rel = Base._getRel_('validateConstruction');
rel.$$setValue(function (construct, nsProps, objProps) {
	var error;
	if (!isFunction(construct)) {
		objProps = nsProps;
		nsProps = construct;
		construct = null;
	} else if (!nsProps) {
		nsProps = { construct: construct };
	} else {
		nsProps.construct = construct;
	}

	error = combineErrors(nsProps && this.validateCreateProperties(nsProps),
		objProps && this.prototype.validateCreateProperties(objProps));
	if (!error) return null;
	error.message = "Invalid properties";
	return error;
});
rel._required.$$setValue(true);

rel = Base._getRel_('is');
rel.$$setValue(function (value) { return true; });
rel._required.$$setValue(true);

rel = Base._getRel_('normalize');
rel.$$setValue(function (value) { return value; });
rel._required.$$setValue(true);

Base._toString.$$setValue(Function.prototype.toString);
<|endoftext|>


<commit_before>/** @jsx React.DOM */

var App = React.createClass({

  getInitialState: function() {
    return {data: this.props.data};
  },

  sort: function(colors, dragging) {
    var data = this.state.data;
    data.colors = colors;
    data.dragging = dragging;
    this.setState({data: data});
  },

  render: function() {

    var listItems = this.props.data.colors.map(function(item, i) {
      return (
        <SortableListItem
          sort={this.sort}
          data={this.state.data}
          key={i}
          item={item} />
      );
    }, this);

    var gridItems = this.props.data.colors.map(function(item, i) {
      return (
        <SortableGridItem style={{background: item}}
           sort={this.sort}
           data={this.state.data}
           key={i}
           item={item} />
      );
    }, this);

    return (

{listItems}

{gridItems}

        <StateView data={this.state.data}/>

    )
  }
});
<commit_msg>fix broken demo<commit_after>/** @jsx React.DOM */

var App = React.createClass({

  getInitialState: function() {
    return {data: this.props.data};
  },

  sort: function(items, dragging) {
    var data = this.state.data;
    data.items = items;
    data.dragging = dragging;
    this.setState({data: data});
  },

  render: function() {

    var listItems = this.state.data.items.map(function(item, i) {
      return (
        <SortableListItem
          sort={this.sort}
          data={this.state.data}
          key={i}
          item={item} />
      );
    }, this);

    var gridItems = this.state.data.items.map(function(item, i) {
      return (
        <SortableGridItem style={{background: item}}
           sort={this.sort}
           data={this.state.data}
           key={i}
           item={item} />
      );
    }, this);

    return (

{listItems}

{gridItems}

        <StateView data={this.state.data}/>

    )
  }
});
<|endoftext|>


<commit_before>apos.widgetPlayers.rss = function($widget) {
  var data = apos.getWidgetData($widget);
  if (!data._ajax) {
    // The server already populated it for us
    return;
  }

  $.get(
    '/apos-rss/render-feed',
    data,
    function(result) {
      console.log(result);
      $widget.html(result);
    }
  );
};
<commit_msg>Removed extraneous console.log<commit_after>apos.widgetPlayers.rss = function($widget) {
  var data = apos.getWidgetData($widget);
  if (!data._ajax) {
    // The server already populated it for us
    return;
  }

  $.get(
    '/apos-rss/render-feed',
    data,
    function(result) {
      $widget.html(result);
    }
  );
};
<|endoftext|>


<commit_before>// Dependencies
var Config = require("../conf")
  , Table = require("le-table")
  , Overlap = require("overlap")
  , Profile = require("../api/profile")
  , Utils = require(Config.root + "/lib/utils")
  , ImageToAscii = require("image-to-ascii")
  , Moment = require("moment")
  ;

/*!
 * getAvatar
 * Gets the avatar in ascii format.
 *
 * @name getAvatar
 * @function
 * @param {Object} userObj User resource object
 * @param {Function} callback The callback function
 * @return {undefined}
 */
function getAvatar(userObj, callback) {
    var fCache = Config.cache.avatars[userObj.login];
    if (fCache) {
        return callback(null, fCache);
    }

    var size = parseInt(process.stdout.rows * 0.7);
    ImageToAscii({
        path: userObj.avatar_url
      , size: { height: size, width: size * 2 }
      , pxWidth: 1
    }, function (err, cAvatar) {
        if (err) { return callback(err); }
        callback(null, Config.cache.avatars[userObj.login] = cAvatar);
    });
}

/**
 * Profile
 * Shows the profile view.
 *
 * @name Profile
 * @function
 * @param {Object} options The options object.
 * @param {Function} progress The progress function.
 * @param {Function} callback The callback function
 * @return {undefined}
 */
module.exports = function (options, progress, callback) {
    Profile(options, progress, function (err, data) {
        if (err) { return callback(err); }
        getAvatar(data, function (err, cAvatar) {

            // Profile
            var profileScreen = Overlap({
                who: Config.background.toString()
              , with: cAvatar
              , where: {
                    x: 3
                  , y: 2
                }
            });
            var info = []
              , name = data.name + " (@" + data.login + ")"
              , separator = Array(name.length).join("-")
              ;

            info.push(separator);
            info.push(name)
            info.push(separator);
            if (data.company) { info.push("♟  " + data.company); }
            if (data.location) { info.push("༐ " + data.location); }
            if (data.email) { info.push("✉ " + data.email); }
            if (data.blog) { info.push("⊜  " + data.blog); }
            if (data.created_at) { info.push("⇴ Joined on " + Moment(data.created_at).format("LL")); }
            if (data.followers) {
                info.push(separator);
                info.push("Followers: " + data.followers);
                info.push("Following: " + data.following);
            }

            profileScreen = Utils.overlap(profileScreen, info, cAvatar.split("\n").length + 2, 3);

            // Repositories
            var repos = new Table();
            repos.addRow(["#", "Type", "Name", "SSH URL"]);
            var show = Math.floor((Config.cli.h - 3) / 2) - 3;
            if (show > data.repos.length) {
                show = data.repos.length;
            }

            for (var i = 0; i < show; ++i) {
                var cRepo = data.repos[i]
                  , type = "source"
                  ;

                if (cRepo.fork) { type = "fork"; }
                if (cRepo.private) { type = "private"; }

                repos.addRow([i + 1, type, cRepo.name, cRepo.ssh_url]);
            }

            var cRepos = repos.toString().trim();
            profileScreen = Utils.overlap(profileScreen, [
                "Repositories"
              , cRepos
            ], 2, cAvatar.split("\n")[0].length + 5);

            // Organizations
            var orgs = new Table();
            orgs.addRow(["#", "Name"]);

            for (var i = 0; i < data.orgs.length; ++i) {
                var cOrg = data.orgs[i];
                orgs.addRow([i + 1, cOrg.login]);
            }

            if (data.orgs.length) {
                profileScreen = Utils.overlap(profileScreen, [
                    "Organizations"
                  , orgs.toString().trim()
                ], 2, cAvatar.split("\n")[0].length + 5 + cRepos.split("\n")[0].length + 3);
            }

            Config.currentFrame = "profile";

            Config.cli.update.render(profileScreen.trim(), true, {
                currentFrame: Config.currentFrame
            });
        });
    });
};
<commit_msg>Compute avatar size<commit_after>// Dependencies
var Config = require("../conf")
  , Table = require("le-table")
  , Overlap = require("overlap")
  , Profile = require("../api/profile")
  , Utils = require(Config.root + "/lib/utils")
  , ImageToAscii = require("image-to-ascii")
  , Moment = require("moment")
  ;

/*!
 * getAvatar
 * Gets the avatar in ascii format.
 *
 * @name getAvatar
 * @function
 * @param {Object} userObj User resource object
 * @param {Function} callback The callback function
 * @return {undefined}
 */
function getAvatar(userObj, callback) {
    var fCache = Config.cache.avatars[userObj.login];
    if (fCache) {
        return callback(null, fCache);
    }

    var size = parseInt(Config.cli.h * 0.7);
    ImageToAscii({
        path: userObj.avatar_url
      , size: { height: size, width: size * 2 }
      , pxWidth: 1
      , colored: false
    }, function (err, cAvatar) {
        if (err) { return callback(err); }
        callback(null, Config.cache.avatars[userObj.login] = cAvatar);
    });
}

/**
 * Profile
 * Shows the profile view.
 *
 * @name Profile
 * @function
 * @param {Object} options The options object.
 * @param {Function} progress The progress function.
 * @param {Function} callback The callback function
 * @return {undefined}
 */
module.exports = function (options, progress, callback) {
    Profile(options, progress, function (err, data) {
        if (err) { return callback(err); }
        getAvatar(data, function (err, cAvatar) {

            // Profile
            var profileScreen = Overlap({
                who: Config.background.toString()
              , with: cAvatar
              , where: {
                    x: 3
                  , y: 2
                }
            });
            var info = []
              , name = data.name + " (@" + data.login + ")"
              , separator = Array(name.length).join("-")
              ;

            info.push(separator);
            info.push(name)
            info.push(separator);
            if (data.company) { info.push("♟  " + data.company); }
            if (data.location) { info.push("༐ " + data.location); }
            if (data.email) { info.push("✉ " + data.email); }
            if (data.blog) { info.push("⊜  " + data.blog); }
            if (data.created_at) { info.push("⇴ Joined on " + Moment(data.created_at).format("LL")); }
            if (data.followers) {
                info.push(separator);
                info.push("Followers: " + data.followers);
                info.push("Following: " + data.following);
            }

            profileScreen = Utils.overlap(profileScreen, info, cAvatar.split("\n").length + 2, 3);

            // Repositories
            var repos = new Table();
            repos.addRow(["#", "Type", "Name", "SSH URL"]);
            var show = Math.floor((Config.cli.h - 3) / 2) - 3;
            if (show > data.repos.length) {
                show = data.repos.length;
            }

            for (var i = 0; i < show; ++i) {
                var cRepo = data.repos[i]
                  , type = "source"
                  ;

                if (cRepo.fork) { type = "fork"; }
                if (cRepo.private) { type = "private"; }

                repos.addRow([i + 1, type, cRepo.name, cRepo.ssh_url]);
            }

            var cRepos = repos.toString().trim();
            profileScreen = Utils.overlap(profileScreen, [
                "Repositories"
              , cRepos
            ], 2, cAvatar.split("\n")[0].length + 5);

            // Organizations
            var orgs = new Table();
            orgs.addRow(["#", "Name"]);

            for (var i = 0; i < data.orgs.length; ++i) {
                var cOrg = data.orgs[i];
                orgs.addRow([i + 1, cOrg.login]);
            }

            if (data.orgs.length) {
                profileScreen = Utils.overlap(profileScreen, [
                    "Organizations"
                  , orgs.toString().trim()
                ], 2, cAvatar.split("\n")[0].length + 5 + cRepos.split("\n")[0].length + 3);
            }

            Config.currentFrame = "profile";

            Config.cli.update.render(profileScreen.trim(), true, {
                currentFrame: Config.currentFrame
            });
        });
    });
};
<|endoftext|>


<commit_before>/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd
Copyright 2017 Michael Telatynski <7t3chguy@gmail.com>

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.
*/

// Squirrel on windows starts the app with various flags
// as hooks to tell us when we've been installed/uninstalled
// etc.
const checkSquirrelHooks = require('./squirrelhooks');
if (checkSquirrelHooks()) return;

const argv = require('minimist')(process.argv);
const electron = require('electron');
const AutoLaunch = require('auto-launch');

const tray = require('./tray');
const vectorMenu = require('./vectormenu');
const webContentsHandler = require('./webcontents-handler');
const updater = require('./updater');

const windowStateKeeper = require('electron-window-state');

if (argv.profile) {
    electron.app.setPath('userData', `${electron.app.getPath('userData')}-${argv.profile}`);
}

let vectorConfig = {};
try {
    vectorConfig = require('../../webapp/config.json');
} catch (e) {
    // it would be nice to check the error code here and bail if the config
    // is unparseable, but we get MODULE_NOT_FOUND in the case of a missing
    // file or invalid json, so node is just very unhelpful.
    // Continue with the defaults (ie. an empty config)
}

let mainWindow = null;
global.appQuitting = false;

// handle uncaught errors otherwise it displays
// stack traces in popup dialogs, which is terrible (which
// it will do any time the auto update poke fails, and there's
// no other way to catch this error).
// Assuming we generally run from the console when developing,
// this is far preferable.
process.on('uncaughtException', function(error) {
    console.log('Unhandled exception', error);
});

let focusHandlerAttached = false;
electron.ipcMain.on('setBadgeCount', function(ev, count) {
    electron.app.setBadgeCount(count);
    if (count === 0) {
        mainWindow.flashFrame(false);
    }
});

electron.ipcMain.on('loudNotification', function() {
    if (process.platform === 'win32' && mainWindow && !mainWindow.isFocused() && !focusHandlerAttached) {
        mainWindow.flashFrame(true);
        mainWindow.once('focus', () => {
            mainWindow.flashFrame(false);
            focusHandlerAttached = false;
        });
        focusHandlerAttached = true;
    }
});

let powerSaveBlockerId;
electron.ipcMain.on('app_onAction', function(ev, payload) {
    switch (payload.action) {
        case 'call_state':
            if (powerSaveBlockerId && electron.powerSaveBlocker.isStarted(powerSaveBlockerId)) {
                if (payload.state === 'ended') {
                    electron.powerSaveBlocker.stop(powerSaveBlockerId);
                }
            } else {
                if (payload.state === 'connected') {
                    powerSaveBlockerId = electron.powerSaveBlocker.start('prevent-display-sleep');
                }
            }
            break;
    }
});

electron.app.commandLine.appendSwitch('--enable-usermedia-screen-capturing');

const shouldQuit = electron.app.makeSingleInstance((commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (mainWindow) {
        if (!mainWindow.isVisible()) mainWindow.show();
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
    }
});

if (shouldQuit) {
    console.log('Other instance detected: exiting');
    electron.app.exit();
}

const launcher = new AutoLaunch({
    name: vectorConfig.brand || 'Riot',
    isHidden: true,
    mac: {
        useLaunchAgent: true,
    },
});

const settings = {
    'auto-launch': {
        get: launcher.isEnabled,
        set: function(bool) {
            if (bool) {
                return launcher.enable();
            } else {
                return launcher.disable();
            }
        },
    },
};

electron.ipcMain.on('settings_get', async function(ev) {
    const data = {};

    try {
        await Promise.all(Object.keys(settings).map(async function (setting) {
            data[setting] = await settings[setting].get();
        }));

        ev.sender.send('settings', data);
    } catch(e) { console.error(e); }
});

electron.ipcMain.on('settings_set', function(ev, key, value) {
    console.log(key, value);
    if (settings[key] && settings[key].set) {
        settings[key].set(value);
    }
});

electron.app.on('ready', () => {

    if (argv.devtools) {
        try {
            const { default: installExtension, REACT_DEVELOPER_TOOLS, REACT_PERF } = require('electron-devtools-installer');
            installExtension(REACT_DEVELOPER_TOOLS)
                .then((name) => console.log(`Added Extension: ${name}`))
                .catch((err) => console.log('An error occurred: ', err));
            installExtension(REACT_PERF)
                .then((name) => console.log(`Added Extension: ${name}`))
                .catch((err) => console.log('An error occurred: ', err));
        } catch(e) {console.log(e);}
    }

    if (vectorConfig.update_base_url) {
        console.log(`Starting auto update with base URL: ${vectorConfig.update_base_url}`);
        updater.start(vectorConfig.update_base_url);
    } else {
        console.log('No update_base_url is defined: auto update is disabled');
    }

    const iconPath = `${__dirname}/../img/riot.${process.platform === 'win32' ? 'ico' : 'png'}`;

    // Load the previous window state with fallback to defaults
    const mainWindowState = windowStateKeeper({
        defaultWidth: 1024,
        defaultHeight: 768,
    });

    mainWindow = global.mainWindow = new electron.BrowserWindow({
        icon: iconPath,
        show: false,
        autoHideMenuBar: true,

        x: mainWindowState.x,
        y: mainWindowState.y,
        width: mainWindowState.width,
        height: mainWindowState.height,
    });
    mainWindow.loadURL(`file://${__dirname}/../../webapp/index.html`);
    electron.Menu.setApplicationMenu(vectorMenu);

    // explicitly hide because setApplicationMenu on Linux otherwise shows...
    // https://github.com/electron/electron/issues/9621
    mainWindow.hide();

    // Create trayIcon icon
    tray.create({
        icon_path: iconPath,
        brand: vectorConfig.brand || 'Riot',
    });

    if (!argv.hidden) {
        mainWindow.once('ready-to-show', () => {
            mainWindow.show();
        });
    }

    mainWindow.on('closed', () => {
        mainWindow = global.mainWindow = null;
    });
    mainWindow.on('close', (e) => {
        if (!global.appQuitting && (tray.hasTray() || process.platform === 'darwin')) {
            // On Mac, closing the window just hides it
            // (this is generally how single-window Mac apps
            // behave, eg. Mail.app)
            e.preventDefault();
            mainWindow.hide();
            return false;
        }
    });

    if (process.platform === 'win32') {
        // Handle forward/backward mouse buttons in Windows
        mainWindow.on('app-command', (e, cmd) => {
            if (cmd === 'browser-backward' && mainWindow.webContents.canGoBack()) {
                mainWindow.webContents.goBack();
            } else if (cmd === 'browser-forward' && mainWindow.webContents.canGoForward()) {
                mainWindow.webContents.goForward();
            }
        });
    }

    webContentsHandler(mainWindow.webContents);
    mainWindowState.manage(mainWindow);
});

electron.app.on('window-all-closed', () => {
    electron.app.quit();
});

electron.app.on('activate', () => {
    mainWindow.show();
});

electron.app.on('before-quit', () => {
    global.appQuitting = true;
    if (mainWindow) {
        mainWindow.webContents.send('before-quit');
    }
});

// Set the App User Model ID to match what the squirrel
// installer uses for the shortcut icon.
// This makes notifications work on windows 8.1 (and is
// a noop on other platforms).
electron.app.setAppUserModelId('com.squirrel.riot-web.Riot');
<commit_msg>delint<commit_after>/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd
Copyright 2017 Michael Telatynski <7t3chguy@gmail.com>

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.
*/

// Squirrel on windows starts the app with various flags
// as hooks to tell us when we've been installed/uninstalled
// etc.
const checkSquirrelHooks = require('./squirrelhooks');
if (checkSquirrelHooks()) return;

const argv = require('minimist')(process.argv);
const electron = require('electron');
const AutoLaunch = require('auto-launch');

const tray = require('./tray');
const vectorMenu = require('./vectormenu');
const webContentsHandler = require('./webcontents-handler');
const updater = require('./updater');

const windowStateKeeper = require('electron-window-state');

if (argv.profile) {
    electron.app.setPath('userData', `${electron.app.getPath('userData')}-${argv.profile}`);
}

let vectorConfig = {};
try {
    vectorConfig = require('../../webapp/config.json');
} catch (e) {
    // it would be nice to check the error code here and bail if the config
    // is unparseable, but we get MODULE_NOT_FOUND in the case of a missing
    // file or invalid json, so node is just very unhelpful.
    // Continue with the defaults (ie. an empty config)
}

let mainWindow = null;
global.appQuitting = false;

// handle uncaught errors otherwise it displays
// stack traces in popup dialogs, which is terrible (which
// it will do any time the auto update poke fails, and there's
// no other way to catch this error).
// Assuming we generally run from the console when developing,
// this is far preferable.
process.on('uncaughtException', function(error) {
    console.log('Unhandled exception', error);
});

let focusHandlerAttached = false;
electron.ipcMain.on('setBadgeCount', function(ev, count) {
    electron.app.setBadgeCount(count);
    if (count === 0) {
        mainWindow.flashFrame(false);
    }
});

electron.ipcMain.on('loudNotification', function() {
    if (process.platform === 'win32' && mainWindow && !mainWindow.isFocused() && !focusHandlerAttached) {
        mainWindow.flashFrame(true);
        mainWindow.once('focus', () => {
            mainWindow.flashFrame(false);
            focusHandlerAttached = false;
        });
        focusHandlerAttached = true;
    }
});

let powerSaveBlockerId;
electron.ipcMain.on('app_onAction', function(ev, payload) {
    switch (payload.action) {
        case 'call_state':
            if (powerSaveBlockerId && electron.powerSaveBlocker.isStarted(powerSaveBlockerId)) {
                if (payload.state === 'ended') {
                    electron.powerSaveBlocker.stop(powerSaveBlockerId);
                }
            } else {
                if (payload.state === 'connected') {
                    powerSaveBlockerId = electron.powerSaveBlocker.start('prevent-display-sleep');
                }
            }
            break;
    }
});

electron.app.commandLine.appendSwitch('--enable-usermedia-screen-capturing');

const shouldQuit = electron.app.makeSingleInstance((commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (mainWindow) {
        if (!mainWindow.isVisible()) mainWindow.show();
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
    }
});

if (shouldQuit) {
    console.log('Other instance detected: exiting');
    electron.app.exit();
}

const launcher = new AutoLaunch({
    name: vectorConfig.brand || 'Riot',
    isHidden: true,
    mac: {
        useLaunchAgent: true,
    },
});

const settings = {
    'auto-launch': {
        get: launcher.isEnabled,
        set: function(bool) {
            if (bool) {
                return launcher.enable();
            } else {
                return launcher.disable();
            }
        },
    },
};

electron.ipcMain.on('settings_get', async function(ev) {
    const data = {};

    try {
        await Promise.all(Object.keys(settings).map(async function (setting) {
            data[setting] = await settings[setting].get();
        }));

        ev.sender.send('settings', data);
    } catch (e) {
        console.error(e);
    }
});

electron.ipcMain.on('settings_set', function(ev, key, value) {
    console.log(key, value);
    if (settings[key] && settings[key].set) {
        settings[key].set(value);
    }
});

electron.app.on('ready', () => {
    if (argv.devtools) {
        try {
            const { default: installExt, REACT_DEVELOPER_TOOLS, REACT_PERF } = require('electron-devtools-installer');
            installExt(REACT_DEVELOPER_TOOLS)
                .then((name) => console.log(`Added Extension: ${name}`))
                .catch((err) => console.log('An error occurred: ', err));
            installExt(REACT_PERF)
                .then((name) => console.log(`Added Extension: ${name}`))
                .catch((err) => console.log('An error occurred: ', err));
        } catch (e) {
            console.log(e);
        }
    }

    if (vectorConfig.update_base_url) {
        console.log(`Starting auto update with base URL: ${vectorConfig.update_base_url}`);
        updater.start(vectorConfig.update_base_url);
    } else {
        console.log('No update_base_url is defined: auto update is disabled');
    }

    const iconPath = `${__dirname}/../img/riot.${process.platform === 'win32' ? 'ico' : 'png'}`;

    // Load the previous window state with fallback to defaults
    const mainWindowState = windowStateKeeper({
        defaultWidth: 1024,
        defaultHeight: 768,
    });

    mainWindow = global.mainWindow = new electron.BrowserWindow({
        icon: iconPath,
        show: false,
        autoHideMenuBar: true,

        x: mainWindowState.x,
        y: mainWindowState.y,
        width: mainWindowState.width,
        height: mainWindowState.height,
    });
    mainWindow.loadURL(`file://${__dirname}/../../webapp/index.html`);
    electron.Menu.setApplicationMenu(vectorMenu);

    // explicitly hide because setApplicationMenu on Linux otherwise shows...
    // https://github.com/electron/electron/issues/9621
    mainWindow.hide();

    // Create trayIcon icon
    tray.create({
        icon_path: iconPath,
        brand: vectorConfig.brand || 'Riot',
    });

    if (!argv.hidden) {
        mainWindow.once('ready-to-show', () => {
            mainWindow.show();
        });
    }

    mainWindow.on('closed', () => {
        mainWindow = global.mainWindow = null;
    });
    mainWindow.on('close', (e) => {
        if (!global.appQuitting && (tray.hasTray() || process.platform === 'darwin')) {
            // On Mac, closing the window just hides it
            // (this is generally how single-window Mac apps
            // behave, eg. Mail.app)
            e.preventDefault();
            mainWindow.hide();
            return false;
        }
    });

    if (process.platform === 'win32') {
        // Handle forward/backward mouse buttons in Windows
        mainWindow.on('app-command', (e, cmd) => {
            if (cmd === 'browser-backward' && mainWindow.webContents.canGoBack()) {
                mainWindow.webContents.goBack();
            } else if (cmd === 'browser-forward' && mainWindow.webContents.canGoForward()) {
                mainWindow.webContents.goForward();
            }
        });
    }

    webContentsHandler(mainWindow.webContents);
    mainWindowState.manage(mainWindow);
});

electron.app.on('window-all-closed', () => {
    electron.app.quit();
});

electron.app.on('activate', () => {
    mainWindow.show();
});

electron.app.on('before-quit', () => {
    global.appQuitting = true;
    if (mainWindow) {
        mainWindow.webContents.send('before-quit');
    }
});

// Set the App User Model ID to match what the squirrel
// installer uses for the shortcut icon.
// This makes notifications work on windows 8.1 (and is
// a noop on other platforms).
electron.app.setAppUserModelId('com.squirrel.riot-web.Riot');
<|endoftext|>


<commit_before>require('jsio', ['Class', 'bind']);
require('jsio.interfaces');
require('jsio.logging')
require('jsio.protocols.delimited', ['DelimitedProtocol'])

var logger = jsio.logging.getLogger('RTJPProtocol')
exports.RTJPProtocol = Class(DelimitedProtocol, function(supr) {
    this.init = function() {
        supr(this, 'init', ['\n']);
        this.frameId = 0;
    }

    this.connectionMade = function() {
        logger.debug("connectionMade");
    }

    var error = function(e) {
        setTimeout(function() {
            throw e;
        }, 0);
        // TODO: send back an error?
    }

    // Inherit and overwrite
    this.frameReceived = function(id, name, args) {
    }

    // Public
    this.sendFrame = function(name, args) {
        if (!args) {
            args = {}
        }
        logger.debug('sendFrame', name, args);
        this.transport.write(JSON.stringify([++this.frameId, name, args]) + '\r\n');
        return this.frameId;
    }

    this.lineReceived = function(line) {
//        logger.debug("lineReceived", line);
        try {
            var frame = JSON.parse(line);
            if (frame.length != 3) {
                return error.call(this, "Invalid frame length");
            }
            if (typeof(frame[0]) != "number") {
                return error.call(this, "Invalid frame id");
            }
            if (typeof(frame[1]) != "string") {
                return error.call(this, "Invalid frame name");
            }
            if (typeof(frame[2]) != "object") {
                return error.call(this, "Invalid frame args");
            }
            logger.debug("frameReceived:", frame[0], frame[1], frame[2]);
            this.frameReceived(frame[0], frame[1], frame[2]);
        } catch(e) {
            error.call(this, e);
        }
    }

    this.connectionLost = function() {
        log('conn lost');
    }
});

<commit_msg>convert spaces -> tabs<commit_after>require('jsio', ['Class', 'bind']);
require('jsio.interfaces');
require('jsio.logging')
require('jsio.protocols.delimited', ['DelimitedProtocol'])

var logger = jsio.logging.getLogger('RTJPProtocol')
exports.RTJPProtocol = Class(DelimitedProtocol, function(supr) {
	this.init = function() {
		var delimiter = '\n';
		supr(this, 'init', [delimiter]);
		this.frameId = 0;
	}

	this.connectionMade = function() {
		logger.debug("connectionMade");
	}

	var error = function(e) {
		setTimeout(function() {
			throw e;
		}, 0);
		// TODO: send back an error?
	}

	// Inherit and overwrite
	this.frameReceived = function(id, name, args) {
	}

	// Public
	this.sendFrame = function(name, args) {
		if (!args) {
			args = {}
		}
		logger.debug('sendFrame', name, args);
		this.transport.write(JSON.stringify([++this.frameId, name, args]) + '\r\n');
		return this.frameId;
	}

	this.lineReceived = function(line) {
		// logger.debug("lineReceived", line);
		try {
			var frame = JSON.parse(line);
			if (frame.length != 3) {
				return error.call(this, "Invalid frame length");
			}
			if (typeof(frame[0]) != "number") {
				return error.call(this, "Invalid frame id");
			}
			if (typeof(frame[1]) != "string") {
				return error.call(this, "Invalid frame name");
			}
			if (typeof(frame[2]) != "object") {
				return error.call(this, "Invalid frame args");
			}
			logger.debug("frameReceived:", frame[0], frame[1], frame[2]);
			this.frameReceived(frame[0], frame[1], frame[2]);
		} catch(e) {
			error.call(this, e);
		}
	}

	this.connectionLost = function() {
		log('conn lost');
	}
});

<|endoftext|>


<commit_before>/**
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.

 * The Apereo Foundation licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* _____XOT POPCORN PLUGIN_____
Adds iframe containing XOT project

required: target start name url clearPanel* pauseMedia*
optional: end description page hide position* line

childNodes (synchXotChange):
required: page start
optional: pauseMedia*

*dealt with in mediaLesson.html

*/

(function (Popcorn) {
	Popcorn.plugin("xot", function(options) {

		// define plugin wide variables here
		var $target, $iframe;

		return {
			_setup: function(options) {
				// setup code, fire on initialisation
				$target = $("#" + options.target);
				if(options.overlayPan == "true"){
					$target.parent().hide()
					$target.hide();
					if(options.optional === "true") {
	                    var $showHolder  = $('
').appendTo($target);
						var size = options.attrib.hsSize;
						$showHs = $('
').addClass(options.attrib.icon).appendTo($showHolder);
						$showHs.css({
							"height"  : size * 0.8,
							"width"   : size * 0.8,
							"padding" : size * 0.1 + "%",
							"border-radius" : size / 2 + 1 + "%",
							"font-size" : size * 0.8 + "%",
							"background-color": options.attrib.colour1,
							"color": options.attrib.colour2,
						}).data({
							size: options.attrib.hsSize,
							colour2: options.attrib.colour1
						}).hover(function(){
							var $this = $(this);
							$this.css({
								'box-shadow': '0px 0px ' + ($this.data('size')/2) + 'px ' + $this.data('colour2'),
								'cursor': 'pointer',
								'z-index': 1000
							});
						},
						function() { // On end hover, remove glow effect
							$(this)
								.css({
									'box-shadow': 'none',
									'z-index': 1
								})
						});

						var $showLbl = $("
" + options.name + "
");

						if(options.attrib.tooltip == "label") {
							$showLbl.appendTo($showHolder);
							// Cap the fontsize to reasonable values
							var fs = size * 0.4 <= 12 ? 12 : size * 0.4 > 32 ? 32 : size * 0.4;
							$showLbl.css({
								"padding": 5,
								"padding-left": size * 0.55 + 5,
								"left": size * 0.5,
								"top": size * 0.5,
								"font-size": fs
							});
						}
						else if(options.attrib.tooltip == "tooltip"){
							$showLbl.removeClass("showLabel").addClass("tooltip").appendTo($showHolder).hide();
							$('
').appendTo($showLbl);
							$showHs.hover(function(){
								$showLbl.css({
									"left": $showLbl.outerWidth()  * -0.5 + size * 0.5,
									"top" : $showLbl.outerHeight() * -1,
									'box-shadow': 'none',
									"overflow" : 'hidden'
								}).show();
							}, function() {
								$showLbl.css({
									'box-shadow': 'none',
									'z-index': 1
								}).hide();
							});
						}
						$target.show();
						$showHolder
							.show()
                    	    .click(function () {
                        	    $showHolder.hide();
								if (options.name != "") {
									$target.prepend('
' + options.name + '
');
								}
								$target.parent().addClass("qWindow");
								//$target.parent().css({"padding": 5});
								$target.parent().css({
									"height": h,
									"width": w
								});
								$iframe.show();
                        	});
					// if not optional
               		} else {
						$target.parent().css({"padding": 5});
						if (options.name != "") {
							$target.prepend('
' + options.name + '
');
						}
					}
				}

				// has a xot iframe already been built here for this block? if not, build iframe
				if (!options.child && $target.children(".xotiframe").length == 0) {
					$target.addClass("xotHolder");

					$iframe = $('')
						.appendTo($target)
						.width("100%")
						.attr({
							"frameborder":	0,
							"scrolling":	"no"
						});

					if (options.description) {
						$iframe.attr("title", options.description);
					}

					// sort url to include extra parameters (display, hide)
					var params = options.url.split("?"),
						myURL = params[0];

					params.splice(0,1);

					if ($.isNumeric(options.page) == false) {
						delete options.page;
					}

					// check whether any params set in url should be used or if they are overridden by other xwd options
					if (params.length > 0) {
						params = params[0].split("&");

						// remove params from url if they're also set in xwd
						for (i=0; i<params.length; i++) {
							if (params[i].indexOf("display=") != -1) {
								// never include display param from url as it will be forced to 'fill'
								params.splice(i, 1);
								i-=1;

							} else if (params[i].indexOf("page=") != -1 || params[i].indexOf("pageID=") != -1 || params[i].indexOf("linkID=") != -1) {
								if (options.page) {
									params.splice(i, 1);
									i-=1;
								} else if (params[i].indexOf("page=") != -1) {
									options.page = Number(params[i].split("=")[1]);
									params.splice(i, 1);
									i-=1;
								}

							} else if (options.hide && params[i].indexOf("hide=") != -1) {
								params.splice(i, 1);
								i-=1;
							}
						}
					}

					if (!options.page) {
						options.page = 1;
					}

					params.push("display=fill");

					if (options.hide) {
						params.push("hide=" + options.hide);
					}

					// recreate url with all relevant parameters
					for (i=0; i<params.length; i++) {
						if (i == 0) {
							myURL += "?" + params[i];
						} else {
							myURL += "&" + params[i];
						}
					}

					// if project is being viewed as https then force iframe to be https too
					if (window.location.protocol == "https:" && myURL.indexOf("http:") == 0) {
						myURL = "https:" + myURL.substring(myURL.indexOf("http:") + 5);
					}

					$iframe.data({
						"url"	:myURL,
						"page"	:options.page
					});

					if (options.line == "true") {
						if (options.position == "top") {
							$target.append("
");
						} else {
							$target.prepend("
");
						}
					}

					// call function to set $iframe to use 100% of available height
					$iframe
						.addClass("fullH")
						.data("exclude", $target.find("h4"));
					eval(x_currentPageXML.nodeName).resizeContent($iframe);

				// if it's a child then at synch points the url stays the same but the project page can change
				} else if (options.child) {
					$iframe = $target.children(".xotiframe");
				}
				$iframe.hide();
				$target.hide();
			},

			start: function(event, options) {
				// fire on options.start

				var pageStr = "";
				if (options.page) {
					pageStr = $iframe.data("url").indexOf("?") == -1 ? "?" : "&";
					pageStr = String(options.page).indexOf("PG") == -1 ? pageStr + "page=" + options.page : pageStr + "linkID=" + options.page;
				}

				if ($iframe.attr("src") == undefined) {
					// it's the 1st url to load in iframe
					$iframe.attr("src", $iframe.data("url") + pageStr);

				} else if (options.page != undefined) {
					try {
						// if possible change page by calling xot function
						$iframe[0].contentWindow.x_changePage(options.page - 1);
					} catch(e) {
						// otherwise reset src for iframe
						$iframe.attr("src", $iframe.data("url") + pageStr);
					}
				}

				if (options.overlayPan) {
					var h = $target.parent().parent().height() - 20;
					var hs = h - 2 * $target.parent().css("padding").replace(/[^-\d\.]/g, '');
					var w = $target.parent().parent().width() - 20;

					if (options.optional == undefined || options.optional === "false") {
						$target.parent().addClass("qWindow");
						$target.parent().css({
							"height": h,
							"width": w
						}).show();
						$iframe.show();
					}
					else {
						$target.parent().css({
							"padding": 0,
							"height": "auto"
						});
					}

					$target.css("height", hs);
					if (options.name == "") {
						$iframe.css("height", h);
					}
					else {
						$iframe.css("height", hs - 33);
					}
				}
				$target.parent().show();
				$target.show();
			},

			end: function(event, options) {
				// fire on options.end
				if (options.overlayPan) {
					$target.parent().removeClass("qWindow");
					$target.parent().css({
						"top": 0,
						"left": 0,
						"padding": 0
					}).hide();
					$target.hide();
				}

				if (!options.child == true) {
					$target.hide();

				} else {
					// force back to original page (needed for when rewinding)
					var pageStr = $iframe.data("url").indexOf("?") == -1 ? "?" : "&";
					pageStr = String($iframe.data("page")).indexOf("PG") == -1 ? pageStr + "page=" + $iframe.data("page") : pageStr + "linkID=" + $iframe.data("page");

					try {
						// if possible change page by calling xot function
						$iframe[0].contentWindow.x_changePage($iframe.data("page") - 1);
					} catch(e) {
						// otherwise reset src for iframe
						$iframe.attr("src", $iframe.data("url") + pageStr);
					}
				}
			}
		};

	});
})(Popcorn);<commit_msg>fix voor niet werkende xot overlay<commit_after>/**
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.

 * The Apereo Foundation licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* _____XOT POPCORN PLUGIN_____
Adds iframe containing XOT project

required: target start name url clearPanel* pauseMedia*
optional: end description page hide position* line

childNodes (synchXotChange):
required: page start
optional: pauseMedia*

*dealt with in mediaLesson.html

*/

(function (Popcorn) {
	Popcorn.plugin("xot", function(options) {

		// define plugin wide variables here
		var $target, $iframe;

		return {
			_setup: function(options) {
				// setup code, fire on initialisation
				$target = $("#" + options.target);
				if(options.overlayPan == "true"){
					$target.parent().hide()
					$target.hide();
					if(options.optional === "true") {
	                    var $showHolder  = $('
').appendTo($target);
						var size = options.attrib.hsSize;
						$showHs = $('
').addClass(options.attrib.icon).appendTo($showHolder);
						$showHs.css({
							"height"  : size * 0.8,
							"width"   : size * 0.8,
							"padding" : size * 0.1,
							"border-radius" : size / 2 + 1,
							"font-size" : size * 0.8,
							"background-color": options.attrib.colour1,
							"color": options.attrib.colour2,
						}).data({
							size: options.attrib.hsSize,
							colour2: options.attrib.colour1
						}).hover(function(){
							var $this = $(this);
							$this.css({
								'box-shadow': '0px 0px ' + ($this.data('size')/2) + 'px ' + $this.data('colour2'),
								'cursor': 'pointer',
								'z-index': 1000
							});
						},
						function() { // On end hover, remove glow effect
							$(this)
								.css({
									'box-shadow': 'none',
									'z-index': 1
								})
						});

						var $showLbl = $("
" + options.name + "
");

						if(options.attrib.tooltip == "label") {
							$showLbl.appendTo($showHolder);
							// Cap the fontsize to reasonable values
							var fs = size * 0.4 <= 12 ? 12 : size * 0.4 > 32 ? 32 : size * 0.4;
							$showLbl.css({
								"padding": 5,
								"padding-left": size * 0.55 + 5,
								"left": size * 0.5,
								"top": size * 0.5,
								"font-size": fs
							});
						}
						else if(options.attrib.tooltip == "tooltip"){
							$showLbl.removeClass("showLabel").addClass("tooltip").appendTo($showHolder).hide();
							$('
').appendTo($showLbl);
							$showHs.hover(function(){
								$showLbl.css({
									"left": $showLbl.outerWidth()  * -0.5 + size * 0.5,
									"top" : $showLbl.outerHeight() * -1,
									'box-shadow': 'none',
									"overflow" : 'hidden'
								}).show();
							}, function() {
								$showLbl.css({
									'box-shadow': 'none',
									'z-index': 1
								}).hide();
							});
						}
						$target.show();
						$showHolder
							.show()
                    	    .click(function () {
                        	    $showHolder.hide();
								if (options.name != "") {
									$target.prepend('
' + options.name + '
');
								}
								$target.parent().addClass("qWindow");
								//$target.parent().css({"padding": 5});
								$target.parent().css({
									"height": h,
									"width": w
								});
								$iframe.show();
                        	});
					// if not optional
               		} else {
						$target.parent().css({"padding": 5});
						if (options.name != "") {
							$target.prepend('
' + options.name + '
');
						}
					}
				}

				// has a xot iframe already been built here for this block? if not, build iframe
				if (!options.child && $target.children(".xotiframe").length == 0) {
					$target.addClass("xotHolder");

					$iframe = $('')
						.appendTo($target)
						.width("100%")
						.attr({
							"frameborder":	0,
							"scrolling":	"no"
						});

					if (options.description) {
						$iframe.attr("title", options.description);
					}

					// sort url to include extra parameters (display, hide)
					var params = options.url.split("?"),
						myURL = params[0];

					params.splice(0,1);

					if ($.isNumeric(options.page) == false) {
						delete options.page;
					}

					// check whether any params set in url should be used or if they are overridden by other xwd options
					if (params.length > 0) {
						params = params[0].split("&");

						// remove params from url if they're also set in xwd
						for (i=0; i<params.length; i++) {
							if (params[i].indexOf("display=") != -1) {
								// never include display param from url as it will be forced to 'fill'
								params.splice(i, 1);
								i-=1;

							} else if (params[i].indexOf("page=") != -1 || params[i].indexOf("pageID=") != -1 || params[i].indexOf("linkID=") != -1) {
								if (options.page) {
									params.splice(i, 1);
									i-=1;
								} else if (params[i].indexOf("page=") != -1) {
									options.page = Number(params[i].split("=")[1]);
									params.splice(i, 1);
									i-=1;
								}

							} else if (options.hide && params[i].indexOf("hide=") != -1) {
								params.splice(i, 1);
								i-=1;
							}
						}
					}

					if (!options.page) {
						options.page = 1;
					}

					params.push("display=fill");

					if (options.hide) {
						params.push("hide=" + options.hide);
					}

					// recreate url with all relevant parameters
					for (i=0; i<params.length; i++) {
						if (i == 0) {
							myURL += "?" + params[i];
						} else {
							myURL += "&" + params[i];
						}
					}

					// if project is being viewed as https then force iframe to be https too
					if (window.location.protocol == "https:" && myURL.indexOf("http:") == 0) {
						myURL = "https:" + myURL.substring(myURL.indexOf("http:") + 5);
					}

					$iframe.data({
						"url"	:myURL,
						"page"	:options.page
					});

					if (options.line == "true") {
						if (options.position == "top") {
							$target.append("
");
						} else {
							$target.prepend("
");
						}
					}

					// call function to set $iframe to use 100% of available height
					$iframe
						.addClass("fullH")
						.data("exclude", $target.find("h4"));
					eval(x_currentPageXML.nodeName).resizeContent($iframe);

				// if it's a child then at synch points the url stays the same but the project page can change
				} else if (options.child) {
					$iframe = $target.children(".xotiframe");
				}
				$iframe.hide();
				$target.hide();
			},

			start: function(event, options) {
				// fire on options.start

				var pageStr = "";
				if (options.page) {
					pageStr = $iframe.data("url").indexOf("?") == -1 ? "?" : "&";
					pageStr = String(options.page).indexOf("PG") == -1 ? pageStr + "page=" + options.page : pageStr + "linkID=" + options.page;
				}

				if ($iframe.attr("src") == undefined) {
					// it's the 1st url to load in iframe
					$iframe.attr("src", $iframe.data("url") + pageStr);

				} else if (options.page != undefined) {
					try {
						// if possible change page by calling xot function
						$iframe[0].contentWindow.x_changePage(options.page - 1);
					} catch(e) {
						// otherwise reset src for iframe
						$iframe.attr("src", $iframe.data("url") + pageStr);
					}
				}

				if (options.overlayPan) {
					// if (options.optional == undefined || options.optional === "false")
					// {
					// 	$target.parent().addClass("qWindow");
					// }
					// else {
					// 	$target.parent().css({
					// 		"padding": 0
					// 	})
					// }
					var h = $target.parent().parent().height() - 20;
					var hs = h - 2 * $target.parent().css("padding").replace(/[^-\d\.]/g, '');
					var w = $target.parent().parent().width() - 20;

					if (options.optional == undefined || options.optional === "false") {
						$target.parent().addClass("qWindow");
						$target.parent().css({
							"max-width": '',
							"height": h,
							"width": w
						}).show();
						$iframe.show();
					}
					else {
						$target.parent().css({
							"padding": 0,
							"height": "auto"
						});
					}

					$target.css("height", hs);
					if (options.name == "") {
						$iframe.css("height", h);
					}
					else {
						$iframe.css("height", hs - 33);
					}
				}
				$target.parent().show();
				$target.show();
			},

			end: function(event, options) {
				// fire on options.end
				if (options.overlayPan) {
					$target.parent().removeClass("qWindow");
					$target.parent().css({
						"top": 0,
						"left": 0,
						"padding": 0
					}).hide();
					$target.hide();
				}

				if (!options.child == true) {
					$target.hide();

				} else {
					// force back to original page (needed for when rewinding)
					var pageStr = $iframe.data("url").indexOf("?") == -1 ? "?" : "&";
					pageStr = String($iframe.data("page")).indexOf("PG") == -1 ? pageStr + "page=" + $iframe.data("page") : pageStr + "linkID=" + $iframe.data("page");

					try {
						// if possible change page by calling xot function
						$iframe[0].contentWindow.x_changePage($iframe.data("page") - 1);
					} catch(e) {
						// otherwise reset src for iframe
						$iframe.attr("src", $iframe.data("url") + pageStr);
					}
				}
			}
		};

	});
})(Popcorn);<|endoftext|>


<commit_before>// TODO: a separate JS file for this since it's needed at all times
// and the editor is not (see editor.js vs. content.js). Letting people
// edit tends to sneak into sites so much that we might not bother
// with the distinction much in practice

apos.widgetPlayers.twitter = function($widget) {
  var data = apos.getWidgetData($widget);
  var account = data.account;
  var hashtag = data.hashtag;

  $.getJSON(
    // Note the trailing ? is significant. It tells jQuery to automatically
    // create a JSONP callback function and obtain the result via a cross-domain
    // script tag so we can talk to twitter in older browsers without a
    // security error
    '/apos-twitter/feed',
    {
      count: (data.limit || 5),
      username: account,
      hashtag: hashtag
    },
    function(tweets) {
      var $tweets = $widget.find('.apos-tweets, [data-apos-tweets]');

      if (!tweets.length) {
        $widget.trigger('aposTwitterNull');
        return;
      }
      $tweets.find('.apos-tweet:not(.apos-template), [data-apos-tweet-place-holer]').remove();
      _.each(tweets, function(tweet) {
        var text = tweet.text;
        var $li = $tweets.find('.apos-tweet.apos-template, [data-apos-tweet].apos-template').clone();

        var username = tweet.user.screen_name;
        var $username = $li.find('[data-apos-tweet-username]');
        $username.text("@"+username);

        var profileUrl = "http://twitter.com/"+ username;
        var $profileLink = $li.find('[data-apos-tweet-profile-link]');
        $profileLink.attr('href', profileUrl);

        var when = parseTwitterDate(tweet.created_at);
        // Months start at zero for use in arrays.
        var month = when.getMonth() + 1;
        if (month < 10) {
          month = '0' + month;
        }
        var day = when.getDate();
        if (day < 10) {
          day = '0' + day;
        }
        var url = "http://twitter.com/" + account + "/status/" + tweet.id_str;
        when = '' + month + '/' + day + '';
        $profileImage = $li.find('.apos-tweet-profile-image, [data-apos-tweet-profile-image]');
        $date = $li.find('.apos-tweet-date, [data-apos-tweet-date]');
        $date.append(when);

        var $link = $li.find('[data-apos-tweet-link]');
        $link.attr('href', url);
        var profileImage;
        if (document.location.href.substr(0, 5) === 'https') {
          profileImage = tweet.user.profile_image_url_https;
        } else {
          profileImage = tweet.user.profile_image_url;
        }
        $profileImage.css('background-image', 'url(' + profileImage + ')');

        // Grabbing any associated images
        var photos = (tweet.entities.media || []);
        if (photos.length) {
          photos.map(function(photo){
            var photoSrc;
            if (document.location.href.substr(0, 5) === 'https') {
              photoSrc = photo.media_url_https;
            } else {
              photoSrc = photo.media_url;
            }
            $li.find('[data-apos-tweet-images]').append('

');
          });
        };

        // Linkify URLs
        text = text.replace(/(https?\:\/\/[^ ]\S+)/g, '$1');
        // Tweets are pre-escaped for some reason in the JSON responses
        text = text.replace(/(^|[^@\w])@(\w{1,15})\b/g, '$1@$2');
        $li.find('.apos-tweet-text, [data-apos-tweet-text]').html(text);
        $li.removeClass('apos-template');
        $tweets.append($li);
      });
      $tweets.find('.apos-tweet.apos-template, [data-apos-tweet].apos-template').remove();
      $widget.trigger('aposTwitterReady');
    }
  );

  // Per http://stackoverflow.com/questions/3243546/problem-with-javascript-date-function-in-ie-7-returns-nan
  // Without this IE bombs
  function parseTwitterDate(str) {
    var v = str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
  }
};
<commit_msg>Udated the linkifier to remove trailing period if it's there.<commit_after>// TODO: a separate JS file for this since it's needed at all times
// and the editor is not (see editor.js vs. content.js). Letting people
// edit tends to sneak into sites so much that we might not bother
// with the distinction much in practice

apos.widgetPlayers.twitter = function($widget) {
  var data = apos.getWidgetData($widget);
  var account = data.account;
  var hashtag = data.hashtag;

  $.getJSON(
    // Note the trailing ? is significant. It tells jQuery to automatically
    // create a JSONP callback function and obtain the result via a cross-domain
    // script tag so we can talk to twitter in older browsers without a
    // security error
    '/apos-twitter/feed',
    {
      count: (data.limit || 5),
      username: account,
      hashtag: hashtag
    },
    function(tweets) {
      var $tweets = $widget.find('.apos-tweets, [data-apos-tweets]');

      if (!tweets.length) {
        $widget.trigger('aposTwitterNull');
        return;
      }
      $tweets.find('.apos-tweet:not(.apos-template), [data-apos-tweet-place-holer]').remove();
      _.each(tweets, function(tweet) {
        var text = tweet.text;
        var $li = $tweets.find('.apos-tweet.apos-template, [data-apos-tweet].apos-template').clone();

        var username = tweet.user.screen_name;
        var $username = $li.find('[data-apos-tweet-username]');
        $username.text("@"+username);

        var profileUrl = "http://twitter.com/"+ username;
        var $profileLink = $li.find('[data-apos-tweet-profile-link]');
        $profileLink.attr('href', profileUrl);

        var when = parseTwitterDate(tweet.created_at);
        // Months start at zero for use in arrays.
        var month = when.getMonth() + 1;
        if (month < 10) {
          month = '0' + month;
        }
        var day = when.getDate();
        if (day < 10) {
          day = '0' + day;
        }
        var url = "http://twitter.com/" + account + "/status/" + tweet.id_str;
        when = '' + month + '/' + day + '';
        $profileImage = $li.find('.apos-tweet-profile-image, [data-apos-tweet-profile-image]');
        $date = $li.find('.apos-tweet-date, [data-apos-tweet-date]');
        $date.append(when);

        var $link = $li.find('[data-apos-tweet-link]');
        $link.attr('href', url);
        var profileImage;
        if (document.location.href.substr(0, 5) === 'https') {
          profileImage = tweet.user.profile_image_url_https;
        } else {
          profileImage = tweet.user.profile_image_url;
        }
        $profileImage.css('background-image', 'url(' + profileImage + ')');

        // Grabbing any associated images
        var photos = (tweet.entities.media || []);
        if (photos.length) {
          photos.map(function(photo){
            var photoSrc;
            if (document.location.href.substr(0, 5) === 'https') {
              photoSrc = photo.media_url_https;
            } else {
              photoSrc = photo.media_url;
            }
            $li.find('[data-apos-tweet-images]').append('

');
          });
        };

        // Linkify URLs
        text = text.replace(/https?\:\/\/\S+/g, function(url) {
          var urlSansPeriod = url.replace(/\.$/, '');
          return '' + url + '';
        });
        // Tweets are pre-escaped for some reason in the JSON responses
        text = text.replace(/(^|[^@\w])@(\w{1,15})\b/g, '$1@$2');
        $li.find('.apos-tweet-text, [data-apos-tweet-text]').html(text);
        $li.removeClass('apos-template');
        $tweets.append($li);
      });
      $tweets.find('.apos-tweet.apos-template, [data-apos-tweet].apos-template').remove();
      $widget.trigger('aposTwitterReady');
    }
  );

  // Per http://stackoverflow.com/questions/3243546/problem-with-javascript-date-function-in-ie-7-returns-nan
  // Without this IE bombs
  function parseTwitterDate(str) {
    var v = str.split(' ');
    return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
  }
};
<|endoftext|>


<commit_before>"use strict";

const through2 = require('through2')
    , BatchStream = require('batch-stream')
    , duplexify = require('duplexify')

module.exports = function levelBatchStream(db, opts = {}) {
  const { silent, size = 100, type, ...batchOpts } = opts

  const ws = new BatchStream({ size })

  const rs = through2.obj(function(ops, _, next) {
    doBatch(ops, function(err) {
      if (err) {
        dup.emit('batch-error', err, ops)
        if (!silent) return dup.destroy(err)
      }

      next()
    })
  })

  function doBatch(ops, next) {
    if (type) {
      ops = ops.map(function(op){
        op.type = op.type || type
        return op
      })
    }

    db.batch(ops, batchOpts, next)
  }

  ws.pipe(rs)

  // TODO: use pumpify
  var dup = duplexify.obj(ws, rs)

  dup.clearBatch = function() {
    return ws.batch.splice(0, ws.batch.length)
  }

  dup.getBatch = function() {
    return ws.batch.slice()
  }

  // TODO: include ops buffered in rs?
  dup.flushBatch = function(cb) {
    const batch = dup.clearBatch()
    doBatch(batch, cb)
  }

  return dup
}
<commit_msg>batch stream with timeout<commit_after>"use strict";

const through2 = require('through2')

module.exports = function levelBatchStream(db, opts = {}) {
  const { silent, type, highWaterMark, ...batchOpts,  } = opts
  const batch = []

  let timeout;

  const stream = through2.obj({ highWaterMark }, function (op, _, next) {
    if (type && !op.type) op.type = type
    batch.push(op)

    if (timeout == null) {
      timeout = setTimeout(function(){
        timeout = null
        flushBatch()
      }, 500)
    }

    next()
  }, function flush(cb) {
    clearTimeout(timeout)
    timeout = null
    flushBatch(cb)
  })

  function flushBatch(cb) {
    if (batch.length) {
      const ops = batch.splice(0, batch.length)

      db.batch(ops, batchOpts, function(err) {
        if (err) {
          stream.emit('batch-error', err, ops)
          if (!silent) return stream.destroy(err)
        }

        cb && cb()
      })
    } else {
      cb && cb()
    }
  }

  return stream
}
<|endoftext|>