<commit_before>module.exports = {
	_instantiate: _instantiate,
	create: create
}

var fin = require('../client'),
	customModels = require('./'),
	propertyModels = require('./propertyModels'),
	util = require('../fin/util')

function _instantiate(idOrValues) {
	var values
	if (typeof idOrValues == 'number') { this._id = idOrValues }
	else { values = idOrValues }
	values = values || {}

	for (var propertyName in this._constructor.description) {
		var value = values[propertyName],
			description = this._constructor.description[propertyName],
			delayedProperty = util.bind(this, _instantiateProperty, propertyName, value, description)
		util.defineGetter(this, propertyName, delayedProperty)
	}
}

var _instantiateProperty = function(propertyName, value, propertyDescription) {
	var type = propertyDescription.type
	if (customModels[type]) {
		if (typeof value != 'object') {
			var Model = customModels[type]
			value = new Model(value)
		}
	} else {
		var Model = propertyModels[type]
		value = new Model(value, propertyDescription.of)
	}
	delete this[propertyName]
	this[propertyName] = value
	this[propertyName]._propertyID = propertyDescription.id
	this[propertyName]._parent = this
	return this[propertyName]
}

function create(callback) {
	if (this._id) { return this } // already created
	_waitForID(this, callback)
	_waitForPropertyIDs(this, function() {
		_createInDatabase(this, function(newID) {
			this._id = newID
			util.each(this._waitingForID, function(fn) { fn(newID) })
			delete this._waitingForID
		})
	})
	return this
}

/* Util
 ******/
var _createInDatabase = function(model, callback) {
	fin.create(_currentValues(model), function(newID) {
		callback.call(model, newID)
	})
}

var _currentValues = function(model) {
	var keyValuePairs = {}
	util.each(model._constructor.description, function(propertyDescription, propertyName) {
		var property = model[propertyName],
			value = (customModels[propertyDescription.type] ? property._id : property._value)
		keyValuePairs[propertyDescription.id] = value
	})
	return keyValuePairs
}

var _waitForPropertyIDs = function(model, callback) {
	var waitingFor = 1
	function tryNow() {
		if (--waitingFor) { return }
		callback.call(model)
	}
	util.each(model._constructor.description, function(propertyDescription, propertyName) {
		if (propertyModels[propertyDescription.type]) { return }
		waitingFor++
		customModels._waitForID(model[propertyName], tryNow)
	})
	tryNow()
}

var _waitForID = function(model, callback) {
	if (model._id !== undefined) { callback(model._id) }
	else if (model._waitingForID) { model._waitingForID.push(callback) }
	else { model._waitingForID = [callback] }
}
<commit_msg>There may not be a callback - if there isn't, don't register it as an ID dependant callback<commit_after>module.exports = {
	_instantiate: _instantiate,
	create: create
}

var fin = require('../client'),
	customModels = require('./'),
	propertyModels = require('./propertyModels'),
	util = require('../fin/util')

function _instantiate(idOrValues) {
	var values
	if (typeof idOrValues == 'number') { this._id = idOrValues }
	else { values = idOrValues }
	values = values || {}

	for (var propertyName in this._constructor.description) {
		var value = values[propertyName],
			description = this._constructor.description[propertyName],
			delayedProperty = util.bind(this, _instantiateProperty, propertyName, value, description)
		util.defineGetter(this, propertyName, delayedProperty)
	}
}

var _instantiateProperty = function(propertyName, value, propertyDescription) {
	var type = propertyDescription.type
	if (customModels[type]) {
		if (typeof value != 'object') {
			var Model = customModels[type]
			value = new Model(value)
		}
	} else {
		var Model = propertyModels[type]
		value = new Model(value, propertyDescription.of)
	}
	delete this[propertyName]
	this[propertyName] = value
	this[propertyName]._propertyID = propertyDescription.id
	this[propertyName]._parent = this
	return this[propertyName]
}

function create(callback) {
	if (this._id) { return this } // already created
	if (callback) { _waitForID(this, callback) }
	_waitForPropertyIDs(this, function() {
		_createInDatabase(this, function(newID) {
			this._id = newID
			util.each(this._waitingForID, function(fn) { fn(newID) })
			delete this._waitingForID
		})
	})
	return this
}

/* Util
 ******/
var _createInDatabase = function(model, callback) {
	fin.create(_currentValues(model), function(newID) {
		callback.call(model, newID)
	})
}

var _currentValues = function(model) {
	var keyValuePairs = {}
	util.each(model._constructor.description, function(propertyDescription, propertyName) {
		var property = model[propertyName],
			value = (customModels[propertyDescription.type] ? property._id : property._value)
		keyValuePairs[propertyDescription.id] = value
	})
	return keyValuePairs
}

var _waitForPropertyIDs = function(model, callback) {
	var waitingFor = 1
	function tryNow() {
		if (--waitingFor) { return }
		callback.call(model)
	}
	util.each(model._constructor.description, function(propertyDescription, propertyName) {
		if (propertyModels[propertyDescription.type]) { return }
		waitingFor++
		customModels._waitForID(model[propertyName], tryNow)
	})
	tryNow()
}

var _waitForID = function(model, callback) {
	if (model._id !== undefined) { callback(model._id) }
	else if (model._waitingForID) { model._waitingForID.push(callback) }
	else { model._waitingForID = [callback] }
}
<|endoftext|>


<commit_before>/*global window*/
"use strict";

(function() {
  /**
   * Represents a single color
   *
   * @param {string} color - A representation of a color as RGB(A),HSL(A),Hexadecimal(with/without hash)
   *
   * @returns {void}
   */
  var ColorInternal = function(color) {
    this.red = null;
    this.green = null;
    this.blue = null;
    this.alpha = null;

    /**
     * Gets the RGB(A) representation of this color
     *
     * @param {boolean} withAlpha - Whether or not to include alpha in the outputted string
     *
     * @returns {string} the RGB(A) representation of this color
     */
    this.getRGB = function(withAlpha) {
    };

    /**
     * Gets the HSL representation of this color
     *
     * @param {boolean} withAlpha - Whether or not to include alpha in the outputted string
     *
     * @returns {string} the HSL(A) representation of this color
     */
    this.getHSL = function(withAlpha) {
    };

    /**
     * Gets the Hexadecimal representation of this color
     *
     * @param {boolean} withHash - Whether or not to include the hash mark at the front of the code
     *
     * @returns {string} the Hexadecimal representation of this color
     */
    this.getHex = function(withHash) {
    };

    /**
     * Retuns a new Colors.Color object that is the complement color of this one
     *
     * @returns {Colors.Color} the complement of this color
     */
    this.getComplement = function() {
    };

    /**
     * Retuns a new Colors.Color object that is the greyscale of this one
     *
     * @returns {Colors.Color} the greyscale color of this one
     */
    this.getGreyscal = function() {
    };

    /**
     * mix another color into this one
     *
     * @param {Colors.Color} mixin - The color you want to mix in
     * @param {double} amount - Between 0 and 1, how much you want to mix it in (defaults to 0.5)
     *
     * @returns {void}
     */
    this.mix = function(mixin, amount) {
    };

    /**
     * lighten this color
     *
     * @param {double} amount - Between 0 and 1, how much lighter do you want this? (defaults to 0.05 or 1/20th of a step)
     *
     * @returns {void}
     */
    this.lighten = function(amount) {
    };

    /**
     * darken this color
     *
     * @param {double} amount - Between 0 and 1, how much darker do you want this? (defaults to 0.05 or 1/20th of a step)
     *
     * @returns {void}
     */
    this.darken = function(amount) {
    };

    /**
     * is this a "dark" color?
     *
     * @returns {boolean} Whether or not this is a "dark" color
     */
    this.isDark = function() {
    };

    /**
     * is this a "light" color?
     *
     * @returns {boolean} Whether or not this is a "light" color
     */
    this.isLight = function() {
    };

    /**
     * is this a "warm" color?
     *
     * @returns {boolean} Whether or not this is a "warm" color
     */
    this.isWarm = function() {
    };

    /**
     * is this a "cold" color?
     *
     * @returns {boolean} Whether or not this is a "cold" color
     */
    this.isCold = function() {
    };

    /**
     * randomizes the color
     *
     * @returns {void}
     */
    this.randomize = function() {
    };
  };

  var ColorsInternal = function() {
    // Assign our internal color class
    this.Color = ColorInternal;

    return this;
  };

  var Colors = function() {
    return new ColorsInternal();
  };

  if ( !window.Colors ) {
    window.Colors = Colors;
  }
})();
<commit_msg>the new public interface looks even batter and this class layout is AWESOME!<commit_after>/*global window*/
"use strict";

(function() {
  /**
   * Represents a single color
   *
   * @param {string} color - A representation of a color as RGB(A),HSL(A),Hexadecimal(with/without hash)
   *
   * @returns {void}
   */
  var Color = function(color) {
     var red = null,
         green = null,
         blue = null,
         alpha = null;

    /**
     * Gets the RGB(A) representation of this color
     *
     * @param {boolean} withAlpha - Whether or not to include alpha in the outputted string
     *
     * @returns {string} the RGB(A) representation of this color
     */
    this.getRGB = function(withAlpha) {
    };

    /**
     * Gets the HSL representation of this color
     *
     * @param {boolean} withAlpha - Whether or not to include alpha in the outputted string
     *
     * @returns {string} the HSL(A) representation of this color
     */
    this.getHSL = function(withAlpha) {
    };

    /**
     * Gets the Hexadecimal representation of this color
     *
     * @param {boolean} withHash - Whether or not to include the hash mark at the front of the code
     *
     * @returns {string} the Hexadecimal representation of this color
     */
    this.getHex = function(withHash) {
    };

    /**
     * Retuns a new Colors.Color object that is the complement color of this one
     *
     * @returns {Colors.Color} the complement of this color
     */
    this.getComplement = function() {
    };

    /**
     * Retuns a new Colors.Color object that is the greyscale of this one
     *
     * @returns {Colors.Color} the greyscale color of this one
     */
    this.getGreyscal = function() {
    };

    /**
     * mix another color into this one
     *
     * @param {Colors.Color} mixin - The color you want to mix in
     * @param {double} amount - Between 0 and 1, how much you want to mix it in (defaults to 0.5)
     *
     * @returns {void}
     */
    this.mix = function(mixin, amount) {
    };

    /**
     * lighten this color
     *
     * @param {double} amount - Between 0 and 1, how much lighter do you want this? (defaults to 0.05 or 1/20th of a step)
     *
     * @returns {void}
     */
    this.lighten = function(amount) {
    };

    /**
     * darken this color
     *
     * @param {double} amount - Between 0 and 1, how much darker do you want this? (defaults to 0.05 or 1/20th of a step)
     *
     * @returns {void}
     */
    this.darken = function(amount) {
    };

    /**
     * is this a "dark" color?
     *
     * @returns {boolean} Whether or not this is a "dark" color
     */
    this.isDark = function() {
    };

    /**
     * is this a "light" color?
     *
     * @returns {boolean} Whether or not this is a "light" color
     */
    this.isLight = function() {
    };

    /**
     * is this a "warm" color?
     *
     * @returns {boolean} Whether or not this is a "warm" color
     */
    this.isWarm = function() {
    };

    /**
     * is this a "cold" color?
     *
     * @returns {boolean} Whether or not this is a "cold" color
     */
    this.isCold = function() {
    };

    /**
     * randomizes the color
     *
     * @returns {void}
     */
    this.randomize = function() {
    };
  };

  var Colors = function() {
    // Assign our internal color class
    this.Color = Color;

    return this;
  };

  if ( !window.Colors ) {
    window.Colors = new Colors();
  }
})();
<|endoftext|>


<commit_before>var monk = require('monk');
var ObjectID = require('mongodb').ObjectID;
var dbAPI = require('api/db.js');
var Item = require('api/models/Item.js');
var User = require('api/models/User.js');

var Reservation = function(id) {
    dbAPI.DatabaseItem.call(this, dbAPI.reservations, id);
};

Reservation.prototype = Object.create(dbAPI.DatabaseItem.prototype);
Reservation.prototype.constructor = Reservation;

Reservation.prototype.count = async function(v) {
    if(v !== undefined) {
        if(typeof v === 'string' && !isNaN(parseInt(v, 10))) {
            v = parseInt(v, 10);
        } else if(typeof v !== 'number') {
            throw new Error("Parameter to count() must be a number or a numerical string!");
        }

        return this.prop('count', v);
    } else {
        var t = await this.prop('count');
        if(typeof t === 'string' && !isNaN(parseInt(t, 10))) {
            return parseInt(t, 10);
        } else if(typeof t === 'number') {
            return t;
        }

        throw new Error("Got non-numerical value for count() from database!");
    }
};

Reservation.prototype.requester = function(v) {
    if(v === undefined) {
        return this.prop('requester').then(
            (userID) => {
                if(userID === null) return null;
                return new User(userID);
            }
        );
    } else {
        if(v instanceof User) {
            return this.prop('requester', v.id());
        } else if((v instanceof ObjectID) || (typeof v === 'string')) {
            return this.prop('requester', monk.id(v));
        } else {
            throw new Error("Invalid UserID passed to setter!");
        }
    }
};

Reservation.prototype.part = function(v) {
    if(v === undefined) {
        /* Get part object. */
        return this.prop('part').then(
            (partID) => {
                if(partID === null) {
                    return null;
                }

                return new Item(partID);
            }
        );
    } else {
        if(v instanceof Item) {
            return this.prop('part', v.id());
        } else if((v instanceof ObjectID) || (typeof v === 'string')) {
            return this.prop('part', monk.id(v));
        } else {
            throw new Error("Invalid PartID passed to setter!");
        }
    }
};

Reservation.prototype.summary = function () {
    return this.fetch().then(
        () => {
            return Promise.all([
                this.prop('part'),
                this.count(),
                this.requester().then( (user) => user.summary() ),
                this.created(),
                this.updated(),
            ]);
        }
    ).then(
        (retn) => {
            return {
                id: this.id(),
                part: retn[0],
                count: retn[1],
                requester: retn[2],
                created: retn[3],
                updated: retn[4],
            };
        }
    );
};

module.exports = Reservation;
<commit_msg>Reservation#count() now returns null if property not set<commit_after>var monk = require('monk');
var ObjectID = require('mongodb').ObjectID;
var dbAPI = require('api/db.js');
var Item = require('api/models/Item.js');
var User = require('api/models/User.js');

var Reservation = function(id) {
    dbAPI.DatabaseItem.call(this, dbAPI.reservations, id);
};

Reservation.prototype = Object.create(dbAPI.DatabaseItem.prototype);
Reservation.prototype.constructor = Reservation;

Reservation.prototype.count = async function(v) {
    if(v !== undefined) {
        if(typeof v === 'string' && !isNaN(parseInt(v, 10))) {
            v = parseInt(v, 10);
        } else if(typeof v !== 'number') {
            throw new Error("Parameter to count() must be a number or a numerical string!");
        }

        return this.prop('count', v);
    } else {
        var t = await this.prop('count');
        if(typeof t === 'string' && !isNaN(parseInt(t, 10))) {
            return parseInt(t, 10);
        } else if(typeof t === 'number' || t === null) {
            return t;
        }

        throw new Error("Got non-numerical, non-null value for count() from database!");
    }
};

Reservation.prototype.requester = function(v) {
    if(v === undefined) {
        return this.prop('requester').then(
            (userID) => {
                if(userID === null) return null;
                return new User(userID);
            }
        );
    } else {
        if(v instanceof User) {
            return this.prop('requester', v.id());
        } else if((v instanceof ObjectID) || (typeof v === 'string')) {
            return this.prop('requester', monk.id(v));
        } else {
            throw new Error("Invalid UserID passed to setter!");
        }
    }
};

Reservation.prototype.part = function(v) {
    if(v === undefined) {
        /* Get part object. */
        return this.prop('part').then(
            (partID) => {
                if(partID === null) {
                    return null;
                }

                return new Item(partID);
            }
        );
    } else {
        if(v instanceof Item) {
            return this.prop('part', v.id());
        } else if((v instanceof ObjectID) || (typeof v === 'string')) {
            return this.prop('part', monk.id(v));
        } else {
            throw new Error("Invalid PartID passed to setter!");
        }
    }
};

Reservation.prototype.summary = function () {
    return this.fetch().then(
        () => {
            return Promise.all([
                this.prop('part'),
                this.count(),
                this.requester().then( (user) => user.summary() ),
                this.created(),
                this.updated(),
            ]);
        }
    ).then(
        (retn) => {
            return {
                id: this.id(),
                part: retn[0],
                count: retn[1],
                requester: retn[2],
                created: retn[3],
                updated: retn[4],
            };
        }
    );
};

module.exports = Reservation;
<|endoftext|>


<commit_before>import { uniq, difference } from 'lodash/fp'
import moment from 'moment'

export default {
  isEvent () {
    return this.get('type') === Post.Type.EVENT
  },

  eventInvitees: function () {
    return this.belongsToMany(User).through(EventInvitation, 'event_id', 'user_id')
    .withPivot('response')
  },

  eventInvitations: function () {
    return this.isEvent() ? this.hasMany(EventInvitation, 'event_id') : false
  },

  userEventInvitation: function (userId) {
    return this.eventInvitations().query({ where: { user_id: userId } }).fetchOne()
  },

  removeEventInvitees: async function (userIds, opts) {
    return Promise.map(userIds, async userId => {
      const invitation = await EventInvitation.find({ userId, eventId: this.id })
      return invitation.destroy(opts)
    })
  },

  addEventInvitees: async function (userIds, inviterId, opts) {
    return Promise.map(uniq(userIds), async userId => {
      const invitation = await EventInvitation.find({ userId, eventId: this.id })
      if (invitation) return
      return EventInvitation.create({
        userId,
        inviterId,
        eventId: this.id
      }, opts)
    })
  },

  updateEventInvitees: async function (userIds, inviterId, opts) {
    const eventInviteeIds = (await this.eventInvitees().fetch()).pluck('id')
    const toRemove = difference(eventInviteeIds, userIds)
    const toAdd = difference(userIds, eventInviteeIds)

    await this.removeEventInvitees(toRemove, opts)
    return this.addEventInvitees(toAdd, inviterId, opts)
  },

  prettyEventDates: function (startTime, endTime) {
    if (!startTime && !endTime) return null
    const start = moment(startTime)
    const end = moment(endTime)

    const from = start.format('ddd, MMM D [at] h:mmA')

    let to = ''

    if (endTime) {
      if (end.month() !== start.month()) {
        to = end.format(' - ddd, MMM D [at] h:mmA')
      } else if (end.day() !== start.day()) {
        to = end.format(' - ddd D [at] h:mmA')
      } else {
        to = end.format(' - h:mmA')
      }
    }

    return from + to
  },

  createInviteNotifications: async function (userId, inviteeIds) {
    const invitees = inviteeIds.map(inviteeId => ({
      reader_id: inviteeId,
      post_id: this.id,
      actor_id: userId,
      reason: 'eventInvitation'
    }))
    return Activity.saveForReasons(invitees)
  }
}
<commit_msg>Add UTC to end of pretty ranges, for email purposes<commit_after>import { uniq, difference } from 'lodash/fp'
import moment from 'moment'

export default {
  isEvent () {
    return this.get('type') === Post.Type.EVENT
  },

  eventInvitees: function () {
    return this.belongsToMany(User).through(EventInvitation, 'event_id', 'user_id')
    .withPivot('response')
  },

  eventInvitations: function () {
    return this.isEvent() ? this.hasMany(EventInvitation, 'event_id') : false
  },

  userEventInvitation: function (userId) {
    return this.eventInvitations().query({ where: { user_id: userId } }).fetchOne()
  },

  removeEventInvitees: async function (userIds, opts) {
    return Promise.map(userIds, async userId => {
      const invitation = await EventInvitation.find({ userId, eventId: this.id })
      return invitation.destroy(opts)
    })
  },

  addEventInvitees: async function (userIds, inviterId, opts) {
    return Promise.map(uniq(userIds), async userId => {
      const invitation = await EventInvitation.find({ userId, eventId: this.id })
      if (invitation) return
      return EventInvitation.create({
        userId,
        inviterId,
        eventId: this.id
      }, opts)
    })
  },

  updateEventInvitees: async function (userIds, inviterId, opts) {
    const eventInviteeIds = (await this.eventInvitees().fetch()).pluck('id')
    const toRemove = difference(eventInviteeIds, userIds)
    const toAdd = difference(userIds, eventInviteeIds)

    await this.removeEventInvitees(toRemove, opts)
    return this.addEventInvitees(toAdd, inviterId, opts)
  },

  prettyEventDates: function (startTime, endTime) {
    if (!startTime && !endTime) return null
    const start = moment(startTime)
    const end = moment(endTime)

    const from = start.format('ddd, MMM D [at] h:mmA')

    let to = ''

    if (endTime) {
      if (end.month() !== start.month()) {
        to = end.format(' - ddd, MMM D [at] h:mmA')
      } else if (end.day() !== start.day()) {
        to = end.format(' - ddd D [at] h:mmA')
      } else {
        to = end.format(' - h:mmA')
      }
    }

    return from + to + " UTC timezone"
  },

  createInviteNotifications: async function (userId, inviteeIds) {
    const invitees = inviteeIds.map(inviteeId => ({
      reader_id: inviteeId,
      post_id: this.id,
      actor_id: userId,
      reason: 'eventInvitation'
    }))
    return Activity.saveForReasons(invitees)
  }
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile<commit_msg>Fixed a typo<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile <|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "W<commit_msg>GET A HAIRCUT!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "We<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP<commit_msg>Quick fix<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP"<|endoftext|>


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

var MULTICAST_ADDRESS = '224.0.0.234';
var MULTICAST_PORT = 60547;

module.exports = function(me, options, callback) {
	var server = dgram.createSocket('udp4');
	var env = process.env;
	var hosts = {};
	var found = 0;
	var loopTimer;

	var port = options.port || MULTICAST_PORT;
	var address = options.address || MULTICAST_ADDRESS;
	var multicast = !(options.multicast === false || (options.multicast === undefined && process.env.NODE_ENV === 'development'));

	var clear = function() {
		hosts = {};
	};
	var encode = function() {
		return 'ann;' + me + (Object.keys(hosts).length ? ';' + Object.keys(hosts).join(';') : '');
	};
	var send = function(msg) {
		msg = new Buffer(msg);
		server.send(msg, 0, msg.length, port, address);
	};
	var find = function() {
		var then = found;
		var timeout = 10;
		var loop = function() {
			if (then < found) return find();
			if (timeout > 15000) return clear();

			send(encode());
			loopTimer = setTimeout(loop, timeout *= 2);
		};

		loop();
	};

	me = Math.random().toString(16).substr(2) + '@' + me;

	process.env = {};
	server.bind(port);
	process.env = env;

	server.on('listening', function() {
		if (!multicast) server.setMulticastTTL(0);
		try {
			server.addMembership(address);
		} catch (e) {
			callback(e);
		}
	});

	server.on('message', function(message, rinfo) {
		var parts = message.toString().split(';');
		var type = parts[0];
		var from = parts[1];

		if (parts.indexOf(me, 2) > -1) return;
		if (from === me) return;
		if (!from) return;

		if (type === 'ann') {
			send('ack;' + me);
		}
		if (!hosts[from]) {
			found++;
			hosts[from] = 1;
			callback(null, from.split('@')[1]);
		}
	});

	find();

	var announcer = {};
	announcer.close = function() {
		if (server) {
			server.close();
			server = null;
		}
		clearTimeout(loopTimer);
	};

	return announcer;
};
<commit_msg>Address -> Host to stress that port is a separate option<commit_after>var dgram = require('dgram');

var MULTICAST_ADDRESS = '224.0.0.234';
var MULTICAST_PORT = 60547;

module.exports = function(me, options, callback) {
	var server = dgram.createSocket('udp4');
	var env = process.env;
	var hosts = {};
	var found = 0;
	var loopTimer;

	var port = options.port || MULTICAST_PORT;
	var host = options.host || MULTICAST_ADDRESS;
	var multicast = !(options.multicast === false || (options.multicast === undefined && process.env.NODE_ENV === 'development'));

	var clear = function() {
		hosts = {};
	};
	var encode = function() {
		return 'ann;' + me + (Object.keys(hosts).length ? ';' + Object.keys(hosts).join(';') : '');
	};
	var send = function(msg) {
		msg = new Buffer(msg);
		server.send(msg, 0, msg.length, port, host);
	};
	var find = function() {
		var then = found;
		var timeout = 10;
		var loop = function() {
			if (then < found) return find();
			if (timeout > 15000) return clear();

			send(encode());
			loopTimer = setTimeout(loop, timeout *= 2);
		};

		loop();
	};

	me = Math.random().toString(16).substr(2) + '@' + me;

	process.env = {};
	server.bind(port);
	process.env = env;

	server.on('listening', function() {
		if (!multicast) server.setMulticastTTL(0);
		try {
			server.addMembership(host);
		} catch (e) {
			callback(e);
		}
	});

	server.on('message', function(message, rinfo) {
		var parts = message.toString().split(';');
		var type = parts[0];
		var from = parts[1];

		if (parts.indexOf(me, 2) > -1) return;
		if (from === me) return;
		if (!from) return;

		if (type === 'ann') {
			send('ack;' + me);
		}
		if (!hosts[from]) {
			found++;
			hosts[from] = 1;
			callback(null, from.split('@')[1]);
		}
	});

	find();

	var announcer = {};
	announcer.close = function() {
		if (server) {
			server.close();
			server = null;
		}
		clearTimeout(loopTimer);
	};

	return announcer;
};
<|endoftext|>


<commit_before>import createService from 'feathers-objection'
import { disallow, iff, isProvider } from 'feathers-hooks-common'
import { hooks as localHooks } from '@feathersjs/authentication-local'
import { hooks as verifyHooks } from 'feathers-authentication-management'

import User from '../models/users'
import {
  setOrigin,
  assignUserRole,
  protectUserFields,
  validateUserPassword,
  protectUserFieldChanges,
} from '../hooks/user'
import {
  convertVerifyDatesFromISOStrings,
  convertVerifyDatesToISOStrings,
} from '../hooks/verify'
import { sendConfirmationEmail } from '../hooks/email'
import { setCreatedAt, setUpdatedAt } from '../hooks/audit'
import filterAllowedFields from '../hooks/filterAllowedFields'
import { withEager } from '../hooks/relations'

export default (app) => {
  const service = createService({
    model: User,
    whitelist: ['$eager'],
    allowedEager: 'roles',
  })

  app.use('/users', service)

  app
    .service('users')
    .hooks({
      before: {
        all: [],
        find: [disallow('external')],
        get: [
          withEager('roles'), // TODO: limit to current user
        ],
        create: [
          setOrigin,
          verifyHooks.addVerification(),
          localHooks.hashPassword({ passwordField: 'password' }),
          convertVerifyDatesToISOStrings,
          setCreatedAt,
        ],
        update: [disallow()],
        patch: [
          validateUserPassword,
          protectUserFieldChanges,
          convertVerifyDatesToISOStrings,
          setUpdatedAt,
        ],
        remove: [disallow('external')],
      },
      after: {
        all: [protectUserFields],
        find: [],
        get: [convertVerifyDatesFromISOStrings],
        create: [
          assignUserRole,
          sendConfirmationEmail,
          verifyHooks.removeVerification(),
          iff(
            isProvider('external'),
            localHooks.protect('password', 'origin', 'baseurl')
          ),
        ],
        patch: [],
        remove: [],
      },
      error: {
        all: [],
        find: [],
        get: [],
        create: [],
        patch: [],
        remove: [],
      },
    })
    .hooks({
      after: {
        all: [filterAllowedFields],
      },
    })
}
<commit_msg>Run protectUserFields hook after signup email hook to get access to protected fields when sending email.<commit_after>import createService from 'feathers-objection'
import { disallow, iff, isProvider } from 'feathers-hooks-common'
import { hooks as localHooks } from '@feathersjs/authentication-local'
import { hooks as verifyHooks } from 'feathers-authentication-management'

import User from '../models/users'
import {
  setOrigin,
  assignUserRole,
  protectUserFields,
  validateUserPassword,
  protectUserFieldChanges,
} from '../hooks/user'
import {
  convertVerifyDatesFromISOStrings,
  convertVerifyDatesToISOStrings,
} from '../hooks/verify'
import { sendConfirmationEmail } from '../hooks/email'
import { setCreatedAt, setUpdatedAt } from '../hooks/audit'
import filterAllowedFields from '../hooks/filterAllowedFields'
import { withEager } from '../hooks/relations'

export default (app) => {
  const service = createService({
    model: User,
    whitelist: ['$eager'],
    allowedEager: 'roles',
  })

  app.use('/users', service)

  app
    .service('users')
    .hooks({
      before: {
        all: [],
        find: [disallow('external')],
        get: [
          withEager('roles'), // TODO: limit to current user
        ],
        create: [
          setOrigin,
          verifyHooks.addVerification(),
          localHooks.hashPassword({ passwordField: 'password' }),
          convertVerifyDatesToISOStrings,
          setCreatedAt,
        ],
        update: [disallow()],
        patch: [
          validateUserPassword,
          protectUserFieldChanges,
          convertVerifyDatesToISOStrings,
          setUpdatedAt,
        ],
        remove: [disallow('external')],
      },
      after: {
        all: [],
        find: [protectUserFields],
        get: [protectUserFields, convertVerifyDatesFromISOStrings],
        create: [
          assignUserRole,
          sendConfirmationEmail,
          verifyHooks.removeVerification(),
          iff(
            isProvider('external'),
            localHooks.protect('password', 'origin', 'baseurl')
          ),
          protectUserFields,
        ],
        patch: [protectUserFields],
        remove: [protectUserFields],
      },
      error: {
        all: [],
        find: [],
        get: [],
        create: [],
        patch: [],
        remove: [],
      },
    })
    .hooks({
      after: {
        all: [filterAllowedFields],
      },
    })
}
<|endoftext|>


<commit_before>/* eslint react/no-multi-comp:0 */
import React, { Component } from 'react'
import { createSpy } from 'expect'
import { Provider } from 'react-redux'
import { combineReducers as plainCombineReducers, createStore } from 'redux'
import { combineReducers as immutableCombineReducers } from 'redux-immutablejs'
import TestUtils from 'react-addons-test-utils'
import createReduxForm from '../reduxForm'
import createReducer from '../reducer'
import createField from '../Field'
import Form from '../Form'
import plain from '../structure/plain'
import plainExpectations from '../structure/plain/expectations'
import immutable from '../structure/immutable'
import immutableExpectations from '../structure/immutable/expectations'
import addExpectations from './addExpectations'
import SubmissionError from '../SubmissionError'
import { submit } from '../actions'

const describeForm = (name, structure, combineReducers, expect) => {
  const reduxForm = createReduxForm(structure)
  const Field = createField(structure)
  const reducer = createReducer(structure)
  const { fromJS } = structure
  const makeStore = (initial) => createStore(
    combineReducers({ form: reducer }), fromJS({ form: initial }))

  describe(name, () => {
    it('should throw an error if not in ReduxForm', () => {
      expect(() => {
        TestUtils.renderIntoDocument(

            <Form onSubmit={() => {}}/>

        )
      }).toThrow(/must be inside a component decorated with reduxForm/)
    })

    it('should output a <form> element with all props mapped', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy()
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={onSubmit} action="/save" method="post" target="_blank">
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(onSubmit).toNotHaveBeenCalled()

      const tag = TestUtils.findRenderedDOMComponentWithTag(dom, 'form')

      // 🤢 This line is DISGUSTING!! Is there a better way to get the props on the <form> ??
      const props = tag[Object.keys(tag)[0]]._currentElement.props

      expect(props.onSubmit).toBe(onSubmit)
      expect(props.action).toBe('/save')
      expect(props.method).toBe('post')
      expect(props.target).toBe('_blank')
    })

    it('should call the onSubmit given to <Form> when instance API submit() is called', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy().andReturn(7)
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      const decoratedForm = TestUtils.findRenderedComponentWithType(dom, DecoratedTestForm)

      expect(onSubmit).toNotHaveBeenCalled()

      const result = decoratedForm.submit()
      expect(result).toBe(7)

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })
    })

    it('should call the onSubmit given to <Form> when SUBMIT action is dispatched', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy()
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(onSubmit).toNotHaveBeenCalled()

      store.dispatch(submit('testForm'))

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })
    })

    it('should properly handle submission errors', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy().andThrow(new SubmissionError({ _error: 'Invalid' }))
      const formRender = createSpy()
      class TestForm extends Component {
        render() {
          formRender(this.props)
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(formRender).toHaveBeenCalled()
      expect(formRender.calls.length).toBe(1)

      const decoratedForm = TestUtils.findRenderedComponentWithType(dom, DecoratedTestForm)

      expect(onSubmit).toNotHaveBeenCalled()

      decoratedForm.submit()

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })

      expect(formRender.calls.length).toBe(3)
      expect(formRender.calls[2].arguments[0].error).toBe('Invalid')
    })
  })
}

describeForm('Form.plain', plain, plainCombineReducers, addExpectations(plainExpectations))
describeForm('Form.immutable', immutable, immutableCombineReducers, addExpectations(immutableExpectations))
<commit_msg>Test to show that #2786 fixes #2785<commit_after>/* eslint react/no-multi-comp:0 */
import React, { Component } from 'react'
import { createSpy } from 'expect'
import { Provider } from 'react-redux'
import { combineReducers as plainCombineReducers, createStore } from 'redux'
import { combineReducers as immutableCombineReducers } from 'redux-immutablejs'
import TestUtils from 'react-addons-test-utils'
import createReduxForm from '../reduxForm'
import createReducer from '../reducer'
import createField from '../Field'
import Form from '../Form'
import plain from '../structure/plain'
import plainExpectations from '../structure/plain/expectations'
import immutable from '../structure/immutable'
import immutableExpectations from '../structure/immutable/expectations'
import addExpectations from './addExpectations'
import SubmissionError from '../SubmissionError'
import {
  change,
  clearSubmit,
  setSubmitFailed,
  setSubmitSucceeded,
  submit,
  touch,
  updateSyncErrors
} from '../actions'

const propsAtNthRender = (componentSpy, callNumber) => componentSpy.calls[callNumber].arguments[0]

const describeForm = (name, structure, combineReducers, expect) => {
  const reduxForm = createReduxForm(structure)
  const Field = createField(structure)
  const reducer = createReducer(structure)
  const { fromJS, getIn } = structure
  const makeStore = (initial = {}, logger) => {
    const reducers = { form: reducer }
    if (logger) {
      reducers.logger = logger
    }
    return createStore(combineReducers(reducers), fromJS({ form: initial }))
  }

  describe(name, () => {
    it('should throw an error if not in ReduxForm', () => {
      expect(() => {
        TestUtils.renderIntoDocument(

            <Form onSubmit={() => {}}/>

        )
      }).toThrow(/must be inside a component decorated with reduxForm/)
    })

    it('should output a <form> element with all props mapped', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy()
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={onSubmit} action="/save" method="post" target="_blank">
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(onSubmit).toNotHaveBeenCalled()

      const tag = TestUtils.findRenderedDOMComponentWithTag(dom, 'form')

      // 🤢 This line is DISGUSTING!! Is there a better way to get the props on the <form> ??
      const props = tag[Object.keys(tag)[0]]._currentElement.props

      expect(props.onSubmit).toBe(onSubmit)
      expect(props.action).toBe('/save')
      expect(props.method).toBe('post')
      expect(props.target).toBe('_blank')
    })

    it('should call the onSubmit given to <Form> when instance API submit() is called', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy().andReturn(7)
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      const decoratedForm = TestUtils.findRenderedComponentWithType(dom, DecoratedTestForm)

      expect(onSubmit).toNotHaveBeenCalled()

      const result = decoratedForm.submit()
      expect(result).toBe(7)

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })
    })

    it('should call the onSubmit given to <Form> when SUBMIT action is dispatched', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy()
      class TestForm extends Component {
        render() {
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(onSubmit).toNotHaveBeenCalled()

      store.dispatch(submit('testForm'))

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })
    })

    it('should properly handle submission errors', () => {
      const store = makeStore({
        testForm: {
          values: {
            foo: 42
          }
        }
      })
      const onSubmit = createSpy().andThrow(new SubmissionError({ _error: 'Invalid' }))
      const formRender = createSpy()
      class TestForm extends Component {
        render() {
          formRender(this.props)
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component="input"/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      expect(formRender).toHaveBeenCalled()
      expect(formRender.calls.length).toBe(1)

      const decoratedForm = TestUtils.findRenderedComponentWithType(dom, DecoratedTestForm)

      expect(onSubmit).toNotHaveBeenCalled()

      decoratedForm.submit()

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })

      expect(formRender.calls.length).toBe(3)
      expect(formRender.calls[2].arguments[0].error).toBe('Invalid')
    })

    it('should NOT submit a form with sync validation errors', () => {
      const logger = createSpy((state = {}) => state).andCallThrough()
      const store = makeStore({}, logger)
      const inputRender = createSpy(props => <input {...props.input}/>).andCallThrough()
      const onSubmit = createSpy()
      const formRender = createSpy()
      const validate = values => {
        const errors = {}
        if(!getIn(values, 'foo')) {
          errors.foo = 'Required'
        }
        return errors
      }
      class TestForm extends Component {
        render() {
          formRender(this.props)
          return (
            <Form onSubmit={this.props.handleSubmit(onSubmit)}>
              <Field name="foo" component={inputRender}/>
            </Form>
          )
        }
      }
      const DecoratedTestForm = reduxForm({
        form: 'testForm',
        validate
      })(TestForm)
      const dom = TestUtils.renderIntoDocument(
        <Provider store={store}>
          <DecoratedTestForm/>
        </Provider>
      )

      let callIndex = logger.calls.length

      // form renders before sync validation and then again with invalid flag
      expect(formRender.calls.length).toBe(2)
      expect(propsAtNthRender(formRender, 0).invalid).toBe(false)
      expect(propsAtNthRender(formRender, 1).invalid).toBe(true)
      expect(propsAtNthRender(formRender, 1).submitFailed).toBe(false)

      // try to submit invalid form via dispatching submit action
      store.dispatch(submit('testForm'))

      // check that submit action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(submit('testForm'))

      // check that clear submit action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(clearSubmit('testForm'))

      // check that touch action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(touch('testForm', 'foo'))

      // check that setSubmitFailed action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(setSubmitFailed('testForm', 'foo'))

      // form rerendered twice, once with submit trigger, and then after submit failure
      expect(formRender.calls.length).toBe(4)
      expect(propsAtNthRender(formRender, 3).invalid).toBe(true)
      expect(propsAtNthRender(formRender, 3).submitFailed).toBe(true)

      // update input
      inputRender.calls[0].arguments[0].input.onChange('hello')

      // check that change action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(change('testForm', 'foo', 'hello', false, false))

      // check that updateSyncErrors action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(updateSyncErrors('testForm', {}))

      // rerendered once to flip dirty flag, and again to flip invalid flag
      expect(formRender.calls.length).toBe(6)
      expect(propsAtNthRender(formRender, 3).dirty).toBe(false)
      expect(propsAtNthRender(formRender, 4).dirty).toBe(true)
      expect(propsAtNthRender(formRender, 4).invalid).toBe(true)
      expect(propsAtNthRender(formRender, 5).invalid).toBe(false)
      expect(propsAtNthRender(formRender, 5).submitFailed).toBe(true)

      // dispatch submit action on now valid form
      store.dispatch(submit('testForm'))

      // check that submit action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(submit('testForm'))

      // check that clear submit action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(clearSubmit('testForm'))

      // check that touch action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(touch('testForm', 'foo'))

      // check that submit succeeded action was dispatched
      expect(logger.calls[callIndex++].arguments[1])
        .toEqual(setSubmitSucceeded('testForm'))

      // check no additional actions dispatched
      expect(logger.calls.length).toBe(callIndex)

      expect(onSubmit).toHaveBeenCalled()
      expect(onSubmit.calls.length).toBe(1)
      expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 'hello' })
      expect(onSubmit.calls[0].arguments[1]).toBeA('function')
      expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 'hello' })
    })
  })
}

describeForm('Form.plain', plain, plainCombineReducers, addExpectations(plainExpectations))
describeForm('Form.immutable', immutable, immutableCombineReducers, addExpectations(immutableExpectations))
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2018 Eric Gach <eric.gach@gmail.com>
 *
 * 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.
 */

const Me = imports.misc.extensionUtils.getCurrentExtension();
const Utils = Me.imports.utils;
const Profile = Me.imports.daemon.profile;
const Timer = Me.imports.daemon.timer;
const Interface = Me.imports.daemon.interface;

const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;

let DaemonDBusInterfaceObject = Gio.DBusNodeInfo.new_for_xml(Interface.DBusInterface).interfaces[0];

let DaemonDBusServer = GObject.registerClass({
    Properties: {
        'running': GObject.ParamSpec.boolean('running', 'Running', 'Boolean value if the daemon is running',
            GObject.ParamFlags.CONSTRUCT | GObject.ParamFlags.READABLE, false)
    },
    Signals: {
        'toggled': { param_types: [GObject.TYPE_BOOLEAN] }
    },
}, class DeskChangerDaemonDBusServer extends GObject.Object {
    _init(params={}) {
        super._init(params);
        this._dbus = null;
        this._dbus_id = null;
        this._dbus_connection = null;
        this._running = false;

        try {
            this._dbus = Gio.bus_own_name(Gio.BusType.SESSION, Interface.DBusName, Gio.BusNameOwnerFlags.NONE, this._on_bus_acquired.bind(this), null, function () {
                Utils.debug(`unable to acquire bus name ${Interface.DBusName}`);
            });
        } catch (e) {
            Utils.error(e, `unable to own dbus name ${Interface.DBusName}`);
            this._dbus = false;
        }
    }

    destroy() {
        this.stop();

        if (this._dbus)
            Gio.bus_unown_name(this._dbus);
    }

    start() {
        if (!this._dbus) {
            Utils.debug('Unable to start daemon, dbus not connected');
        }

        this._running = true;
        Utils.debug('daemon started');
        this.emit('toggled', this._running);
    }

    stop() {
        this._running = false;
        Utils.debug('daemon stopped');
        this.emit('toggled', this._running);
    }

    get running() {
        return this._running;
    }

    _dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation) {
        switch (method_name.toLowerCase()) {
            case 'start':
                this.start();
                invocation.return_value(new GLib.Variant('(b)', [true,]));
                break;

            case 'stop':
                this.stop();
                invocation.return_value(new GLib.Variant('(b)', [true,]));
                break;

            default:
                invocation.return_dbus_error('org.freedesktop.DBus.Error.UnknownMethod',
                                             'Method ' + method_name + ' in ' + interface_name + ' does not exist');
                Utils.debug(`unknown dbus method ${method_name}`);
                break;
        }
    }

    _dbus_handle_get(connection, sender, object_path, interface_name, property_name) {
        Utils.debug(`dbus::getProperty(${property_name})`);
        switch (property_name) {
            case 'history':
                return new GLib.Variant('as', this.desktop_profile.history.all());

            case 'running':
                return new GLib.Variant('b', this._running);

            default:
                // should error here?
                Utils.error(`unknown dbus property ${property_name}`);
                return null;
        }
    }

    _dbus_handle_set() {
    }

    _on_bus_acquired(connection) {
        // cannot haz two
        if (this._dbus_id !== null) return;

        try {
            this._dbus_id = connection.register_object(
                Interface.DBusPath,
                DaemonDBusInterfaceObject,
                this._dbus_handle_call.bind(this),
                this._dbus_handle_get.bind(this),
                this._dbus_handle_set.bind(this),
            );
            this._dbus_connection = connection;
            Utils.debug(`acquired dbus connection for ${DaemonDBusPath}`);
        } catch (e) {
            error(e, `failed to register dbus object: ${e}`);
        } finally {
            if (this._dbus_id === null || this._dbus_id === 0) {
                Utils.debug('failed to register dbus object');
                this._dbus_id = null;
                this._dbus_connection = null;
            }
        }
    }
});

var Daemon = GObject.registerClass({
    Signals: {
        'changed': { param_types: [GObject.TYPE_STRING] },
    },
},
class DeskChangerDaemon extends DaemonDBusServer {
    _init(settings, params = {}) {
        super._init(params);
        this._settings = settings;
        this.desktop_profile = new Profile.DesktopProfile(settings);
        this.lockscreen_profile = new Profile.LockScreenProfile(settings);

        this._loaded_id = this.desktop_profile.connect('loaded', () => {
            let wallpaper = this.desktop_profile.next(false);
            if (settings.update_lockscreen && this.lockscreen_profile.inherit) {
                this.lockscreen_profile.next(false, wallpaper);
            }
        });
        this._lockscreen_loaded_id = this.lockscreen_profile.connect('loaded', () => {
            this.lockscreen_profile.next(false);
        });
    }

    destroy() {
        if (this._timer) {
            this._timer.destroy();
        }

        this.desktop_profile.disconnect(this._loaded_id);
        this.lockscreen_profile.disconnect(this._lockscreen_loaded_id);
        super.destroy();
    }

    next() {
        let wallpaper = this.desktop_profile.next();
        if (this._settings.update_lockscreen) {
            (this.lockscreen_profile.inherit) ? this.lockscreen_profile.next(true, wallpaper) : this.lockscreen_profile.next();
        }
        this.emit('changed', wallpaper);
        return wallpaper;
    }

    prev() {
        let wallpaper = this.desktop_profile.prev();
        if (this._settings.update_lockscreen) {
            (this.lockscreen_profile.inherit) ? this.lockscreen_profile.prev(true, wallpaper) : this.lockscreen_profile.prev();
        }
        this.emit('changed', wallpaper);
        return wallpaper;
    }

    start() {
        this.desktop_profile.load();
        this.lockscreen_profile.load();
        super.start();
        this._check_timer(this._settings);

        this._settings.connect('changed::rotation', (settings, key) => {
            this._check_timer(settings);
        });
    }

    stop() {
        if (this._timer) {
            this._timer.destroy();
        }

        this.desktop_profile.unload();
        this.lockscreen_profile.unload();
        super.stop();
    }

    _check_timer(settings) {
        if (this._timer) {
            // no matter the change, destroy the current timer
            this._timer.destroy();
            this._timer = null;
        }

        if (settings.rotation == 'interval') {
            this._timer = new Timer.Interval(settings.get_int('interval'), this.next.bind(this));
        } else if (settings.rotation == 'hourly') {
            this._timer = new Timer.Hourly(this.next.bind(this));
        }
    }

    _dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation) {
        switch (method_name.toLowerCase()) {
            case 'loadprofile':
                break;

            case 'next':
                let uri = this.next();
                invocation.return_value(new GLib.Variant('(s)', [uri, ]));
                return;

            case 'prev':
                break;
        }

        super._dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation);
    }
});

<commit_msg>Updating checks for successful wallpaper<commit_after>/**
 * Copyright (c) 2018 Eric Gach <eric.gach@gmail.com>
 *
 * 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.
 */

const Me = imports.misc.extensionUtils.getCurrentExtension();
const Utils = Me.imports.utils;
const Profile = Me.imports.daemon.profile;
const Timer = Me.imports.daemon.timer;
const Interface = Me.imports.daemon.interface;

const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;

let DaemonDBusInterfaceObject = Gio.DBusNodeInfo.new_for_xml(Interface.DBusInterface).interfaces[0];

let DaemonDBusServer = GObject.registerClass({
    Properties: {
        'running': GObject.ParamSpec.boolean('running', 'Running', 'Boolean value if the daemon is running',
            GObject.ParamFlags.CONSTRUCT | GObject.ParamFlags.READABLE, false)
    },
    Signals: {
        'toggled': { param_types: [GObject.TYPE_BOOLEAN] }
    },
}, class DeskChangerDaemonDBusServer extends GObject.Object {
    _init(params={}) {
        super._init(params);
        this._dbus = null;
        this._dbus_id = null;
        this._dbus_connection = null;
        this._running = false;

        try {
            this._dbus = Gio.bus_own_name(Gio.BusType.SESSION, Interface.DBusName, Gio.BusNameOwnerFlags.NONE, this._on_bus_acquired.bind(this), null, function () {
                Utils.debug(`unable to acquire bus name ${Interface.DBusName}`);
            });
        } catch (e) {
            Utils.error(e, `unable to own dbus name ${Interface.DBusName}`);
            this._dbus = false;
        }
    }

    destroy() {
        this.stop();

        if (this._dbus)
            Gio.bus_unown_name(this._dbus);
    }

    start() {
        if (!this._dbus) {
            Utils.debug('Unable to start daemon, dbus not connected');
        }

        this._running = true;
        Utils.debug('daemon started');
        this.emit('toggled', this._running);
    }

    stop() {
        this._running = false;
        Utils.debug('daemon stopped');
        this.emit('toggled', this._running);
    }

    get running() {
        return this._running;
    }

    _dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation) {
        switch (method_name.toLowerCase()) {
            case 'start':
                this.start();
                invocation.return_value(new GLib.Variant('(b)', [true,]));
                break;

            case 'stop':
                this.stop();
                invocation.return_value(new GLib.Variant('(b)', [true,]));
                break;

            default:
                invocation.return_dbus_error('org.freedesktop.DBus.Error.UnknownMethod',
                                             'Method ' + method_name + ' in ' + interface_name + ' does not exist');
                Utils.debug(`unknown dbus method ${method_name}`);
                break;
        }
    }

    _dbus_handle_get(connection, sender, object_path, interface_name, property_name) {
        Utils.debug(`dbus::getProperty(${property_name})`);
        switch (property_name) {
            case 'history':
                return new GLib.Variant('as', this.desktop_profile.history.all());

            case 'running':
                return new GLib.Variant('b', this._running);

            default:
                // should error here?
                Utils.error(`unknown dbus property ${property_name}`);
                return null;
        }
    }

    _dbus_handle_set() {
    }

    _on_bus_acquired(connection) {
        // cannot haz two
        if (this._dbus_id !== null) return;

        try {
            this._dbus_id = connection.register_object(
                Interface.DBusPath,
                DaemonDBusInterfaceObject,
                this._dbus_handle_call.bind(this),
                this._dbus_handle_get.bind(this),
                this._dbus_handle_set.bind(this),
            );
            this._dbus_connection = connection;
            Utils.debug(`acquired dbus connection for ${DaemonDBusPath}`);
        } catch (e) {
            error(e, `failed to register dbus object: ${e}`);
        } finally {
            if (this._dbus_id === null || this._dbus_id === 0) {
                Utils.debug('failed to register dbus object');
                this._dbus_id = null;
                this._dbus_connection = null;
            }
        }
    }
});

var Daemon = GObject.registerClass({
    Signals: {
        'changed': { param_types: [GObject.TYPE_STRING] },
    },
},
class DeskChangerDaemon extends DaemonDBusServer {
    _init(settings, params = {}) {
        super._init(params);
        this._settings = settings;
        this.desktop_profile = new Profile.DesktopProfile(settings);
        this.lockscreen_profile = new Profile.LockScreenProfile(settings);

        this._loaded_id = this.desktop_profile.connect('loaded', () => {
            let wallpaper = this.desktop_profile.next(false);
            if (settings.update_lockscreen && this.lockscreen_profile.inherit) {
                this.lockscreen_profile.next(false, wallpaper);
            }
        });
        this._lockscreen_loaded_id = this.lockscreen_profile.connect('loaded', () => {
            this.lockscreen_profile.next(false);
        });
    }

    destroy() {
        if (this._timer) {
            this._timer.destroy();
        }

        this.desktop_profile.disconnect(this._loaded_id);
        this.lockscreen_profile.disconnect(this._lockscreen_loaded_id);
        super.destroy();
    }

    next() {
        let wallpaper = this.desktop_profile.next();

        if (wallpaper) {
            if (this._settings.update_lockscreen) {
                (this.lockscreen_profile.inherit) ? this.lockscreen_profile.next(true, wallpaper) : this.lockscreen_profile.next();
            }
            this.emit('changed', wallpaper);
        }

        return wallpaper;
    }

    prev() {
        let wallpaper = this.desktop_profile.prev();

        if (wallpaper) {
            if (this._settings.update_lockscreen) {
                (this.lockscreen_profile.inherit) ? this.lockscreen_profile.prev(true, wallpaper) : this.lockscreen_profile.prev();
            }
            this.emit('changed', wallpaper);
        }

        return wallpaper;
    }

    start() {
        this.desktop_profile.load();
        this.lockscreen_profile.load();
        super.start();
        this._check_timer(this._settings);

        this._settings.connect('changed::rotation', (settings, key) => {
            this._check_timer(settings);
        });
    }

    stop() {
        if (this._timer) {
            this._timer.destroy();
        }

        this.desktop_profile.unload();
        this.lockscreen_profile.unload();
        super.stop();
    }

    _check_timer(settings) {
        if (this._timer) {
            // no matter the change, destroy the current timer
            this._timer.destroy();
            this._timer = null;
        }

        if (settings.rotation == 'interval') {
            this._timer = new Timer.Interval(settings.get_int('interval'), this.next.bind(this));
        } else if (settings.rotation == 'hourly') {
            this._timer = new Timer.Hourly(this.next.bind(this));
        }
    }

    _dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation) {
        switch (method_name.toLowerCase()) {
            case 'loadprofile':
                break;

            case 'next':
                let uri = this.next();
                invocation.return_value(new GLib.Variant('(s)', [uri, ]));
                return;

            case 'prev':
                break;
        }

        super._dbus_handle_call(connection, sender, object_path, interface_name, method_name, parameters, invocation);
    }
});

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function s<|endoftext|>


<commit_before>import { expect } from 'chai';

import slugizoid from '../index';

describe('slugizoid', () => {
  describe('.toString', () => {
    it('should be a function with arity 1', () => {
      // Arrange
      const slug = slugizoid('pUll_reQUeSt');

      // Assert
      expect(slug.toString)
        .to.be.a('function')
        .with.lengthOf(1);
    });

    it('should return a singular space deliminated pascal case by default', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.toString()).to.equal('Pull Request');
    });

    describe('options', () => {
      describe('.plural', () => {
        it('should allow pluralized readable verison of slug', () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ plural: true })).to.equal('Pull Requests');
        });
      });

      describe('.format', () => {
        it('should allow formating of camel 🐫', async () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ format: 'camel' })).to.equal('pullRequest');
        });

        it('should allow formating of camel 🐫  and plural', async () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ format: 'camel', plural: true })).to.equal(
            'pullRequests'
          );
        });
      });
    });
  });

  describe('slugify', () => {
    it('should be a function with artiy 0', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.slugify)
        .to.be.a('function')
        .with.lengthOf(0);
    });

    it('should always return the singular, _ deliminated verison of slug', () => {
      // Arrange
      const slug = slugizoid('pull-requests');

      // Act
      const result = slug.slugify();

      // Assert
      expect(result.includes('-')).to.be.false;
      expect(result.includes('requests')).to.be.false;
      expect(result).to.be.equal('pull_request');
    });
  });

  describe('.urlify', () => {
    it('should be a function with arity 0', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.urlify)
        .to.be.a('function')
        .with.lengthOf(0);
    });

    it('should output the corrent slug with long words', () => {
      // Assert
      expect(
        slugizoid('this is a really  long slug name').urlify()
      ).to.be.equal('this-is-a-really-long-slug-names');
    });

    it('should always return the pluralized, - deliminated verions of slug', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Act
      const result = slug.urlify();

      // Assert
      expect(result.includes('_')).to.be.false;
      expect(result).to.be.equal('pull-requests');
    });
  });

  describe('creation', () => {
    const expectedSlug = 'pull_request';

    it('should remove non-alphanumeric characters', () => {
      // Arrange
      const slug = slugizoid('pull)*&^% -_$#@!(=+}{][]}/\'"`;:.,request');

      // Assert
      expect(slug.slugify()).to.be.equal(expectedSlug);
    });

    describe('plural', () => {
      it('_ deliminated', () => {
        // Arrange
        const slug = slugizoid('pull_requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('- deliminated', () => {
        // Arrange
        const slug = slugizoid('pull-requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('<space> deliminated', () => {
        // Arrange
        const slug = slugizoid('pull requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });
    });

    describe('singular', () => {
      it('_ deliminated', () => {
        // Arrange
        const slug = slugizoid('pull_request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('- deliminated', () => {
        // Arrange
        const slug = slugizoid('pull-request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('<space> deliminated', () => {
        // Arrange
        const slug = slugizoid('pull request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });
    });
  });

  describe('comparison', () => {
    describe('.equals', () => {
      it('should be a function with arity of 1', () => {
        // Arrange
        const slug = slugizoid();

        // Assert
        expect(slug.equals)
          .to.be.a('function')
          .with.lengthOf(1);
      });

      it('should match singular underscore deliminated version of slug', () => {
        // Arrange
        const slug = slugizoid('pull-request');

        // Assert
        expect(slug.equals('pull-requests')).to.be.true;
        expect(slug.equals('pull_requests')).to.be.true;
        expect(slug.equals('pull_request')).to.be.true;
        expect(slug.equals('pull-request')).to.be.true;
        expect(slug.equals('pull')).to.be.false;
      });
    });
  });
});
<commit_msg>Update slug.spec.js<commit_after>import { expect } from 'chai';

import slugizoid from '../index';

describe('slugizoid', () => {
  describe('.toString', () => {
    it('should be a function with arity 1', () => {
      // Arrange
      const slug = slugizoid('pUll_reQUeSt');

      // Assert
      expect(slug.toString)
        .to.be.a('function')
        .with.lengthOf(1);
    });

    it('should return a singular space deliminated pascal case by default', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.toString()).to.equal('Pull Request');
    });

    describe('options', () => {
      describe('.plural', () => {
        it('should allow pluralized readable verison of slug', () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ plural: true })).to.equal('Pull Requests');
        });
      });

      describe('.format', () => {
        it('should allow formating of camel 🐫', async () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ format: 'camel' })).to.equal('pullRequest');
        });

        it('should allow formating of camel 🐫  and plural', async () => {
          // Arrange
          const slug = slugizoid('pull_request');

          // Assert
          expect(slug.toString({ format: 'camel', plural: true })).to.equal(
            'pullRequests'
          );
        });
      });
    });
  });

  describe('slugify', () => {
    it('should be a function with artiy 0', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.slugify)
        .to.be.a('function')
        .with.lengthOf(0);
    });

    it('should always return the singular, _ deliminated verison of slug', () => {
      // Arrange
      const slug = slugizoid('pull-requests');

      // Act
      const result = slug.slugify();

      // Assert
      expect(result.includes('-')).to.be.false;
      expect(result.includes('requests')).to.be.false;
      expect(result).to.be.equal('pull_request');
    });
  });

  describe('.urlify', () => {
    it('should be a function with arity 0', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Assert
      expect(slug.urlify)
        .to.be.a('function')
        .with.lengthOf(0);
    });

    it('should output the correct slug with long words', () => {
      // Assert
      expect(
        slugizoid('this is a really  long slug name').urlify()
      ).to.be.equal('this-is-a-really-long-slug-names');
    });

    it('should always return the pluralized, - deliminated verions of slug', () => {
      // Arrange
      const slug = slugizoid('pull_request');

      // Act
      const result = slug.urlify();

      // Assert
      expect(result.includes('_')).to.be.false;
      expect(result).to.be.equal('pull-requests');
    });
  });

  describe('creation', () => {
    const expectedSlug = 'pull_request';

    it('should remove non-alphanumeric characters', () => {
      // Arrange
      const slug = slugizoid('pull)*&^% -_$#@!(=+}{][]}/\'"`;:.,request');

      // Assert
      expect(slug.slugify()).to.be.equal(expectedSlug);
    });

    describe('plural', () => {
      it('_ deliminated', () => {
        // Arrange
        const slug = slugizoid('pull_requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('- deliminated', () => {
        // Arrange
        const slug = slugizoid('pull-requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('<space> deliminated', () => {
        // Arrange
        const slug = slugizoid('pull requests');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });
    });

    describe('singular', () => {
      it('_ deliminated', () => {
        // Arrange
        const slug = slugizoid('pull_request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('- deliminated', () => {
        // Arrange
        const slug = slugizoid('pull-request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });

      it('<space> deliminated', () => {
        // Arrange
        const slug = slugizoid('pull request');

        // Assert
        expect(slug.slugify()).to.be.equal(expectedSlug);
      });
    });
  });

  describe('comparison', () => {
    describe('.equals', () => {
      it('should be a function with arity of 1', () => {
        // Arrange
        const slug = slugizoid();

        // Assert
        expect(slug.equals)
          .to.be.a('function')
          .with.lengthOf(1);
      });

      it('should match singular underscore deliminated version of slug', () => {
        // Arrange
        const slug = slugizoid('pull-request');

        // Assert
        expect(slug.equals('pull-requests')).to.be.true;
        expect(slug.equals('pull_requests')).to.be.true;
        expect(slug.equals('pull_request')).to.be.true;
        expect(slug.equals('pull-request')).to.be.true;
        expect(slug.equals('pull')).to.be.false;
      });
    });
  });
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import {STROKE_WIDTH} from 'src/shared/constants';
/**
 * Accepts an array of raw influxdb responses and returns a format
 * that Dygraph understands.
 */

// activeQueryIndex is an optional argument that indicated which query's series we want highlighted.
export default function timeSeriesToDygraph(raw = [], activeQueryIndex, isInDataExplorer) {
  // collect results from each influx response
  const results = raw.reduce((acc, response, responseIndex) => {
    const responses = _.get(response, 'response.results', [])
    const indexedResponses = responses.map((response) => ({...response, responseIndex}))
    return [...acc, ...indexedResponses]
  }, [])

  // collect each series
  const serieses = results.reduce((acc, {series, responseIndex}, index) => {
    return [...acc, ...series.map((item) => ({...item, responseIndex, index}))];
  }, [])

  // convert series into cells with rows and columns
  const cells = serieses.reduce((acc, {name, columns, values, index, responseIndex}) => {
    const rows = values.map((values) => ({
      name,
      columns,
      values,
      index,
    }))

    rows.forEach(({values: vals, columns: cols, name: n, index: seriesIndex}) => {
      const [time, ...rowValues] = vals
      rowValues.forEach((value, i) => {
        const column = cols[i + 1]
        acc.push({
          label: `${n}.${column}`,
          value,
          time,
          seriesIndex,
          responseIndex,
        })
      })
    })

    return acc
  }, [])

  const labels = cells.reduce((acc, {label, seriesIndex, responseIndex}) => {
    const existingLabel = acc.find(({
      label: findLabel,
      seriesIndex: findSeriesIndex,
    }) => findLabel === label && findSeriesIndex === seriesIndex)

    if (!existingLabel) {
      acc.push({
        label,
        seriesIndex,
        responseIndex,
      })
    }

    return acc
  }, [])

  const sortedLabels = _.sortBy(labels, 'label')

  const timeSeries = cells.reduce((acc, cell) => {
    let existingRowIndex = acc.findIndex(({time}) => cell.time === time)

    if (existingRowIndex === -1) {
      acc.push({
        time: cell.time,
        values: Array(sortedLabels.length).fill(null),
      })

      existingRowIndex = acc.length - 1
    }

    const values = acc[existingRowIndex].values
    const labelIndex = sortedLabels.findIndex(({label, seriesIndex}) => label === cell.label && cell.seriesIndex === seriesIndex);
    values[labelIndex] = cell.value
    acc[existingRowIndex].values = values

    return acc
  }, [])

  const sortedTimeSeries = _.sortBy(timeSeries, 'time')

  const {light, heavy} = STROKE_WIDTH;

  const dygraphSeries = sortedLabels.reduce((acc, {label, responseIndex}) => {
    acc[label] = {
      strokeWidth: responseIndex === activeQueryIndex ? heavy : light,
    }

    if (!isInDataExplorer) {
      acc[label].axis = responseIndex === 0 ? 'y' : 'y2'
    }

    return acc
  }, {})

  const timeSeriesToDygraph = {
    timeSeries: sortedTimeSeries.map(({time, values}) => ([new Date(time), ...values])),
    labels: ["time", ...sortedLabels.map(({label}) => label)],
    dygraphSeries,
  }

  return timeSeriesToDygraph;
  // timeSeriesToDygraph , {labels: [], timeSeries: []}

  // raw.forEach(({response}, queryIndex) => {
  //   // If a response is an empty result set or a query returned an error
  //   // from InfluxDB, don't try and parse.
  //   if (response.results.length) {
  //     if (isEmpty(response) || hasError(response)) {
  //       return;
  //     }
  //   }
  //
  //   /**
  //    * response looks like:
  //    * {
  //    *   results: [
  //    *     { series: [...] },
  //    *     { series: [...] },
  //    *   ]
  //    * }
  //    */
  //   response.results.forEach(parseResult);
  //
  //   function parseResult(s) {
  //     /*
  //      * s looks like:
  //      * {
  //      *   series: [
  //      *     {
  //      *       name: "<measurement>",
  //      *       columns: ["time", "<field name 1>", "<field name 2>", ...],
  //      *       values: [<time>, <value of field 1>, <value of field 2>, ...],
  //      *     },
  //      * }
  //      */
  //     s.series.forEach(parseSeries);
  //   }
  //
  //   function parseSeries(series) {
  //     /*
  //      * series looks like:
  //      * {
  //      *   name: "<measurement>",
  //      *   columns: ["time", "<field name 1>", "<field name 2>", ...],
  //      *   values: [
  //      *    [<time1>, <value of field 1 @ time1>, <value of field 2 @ time1>, ...],
  //      *    [<time2>, <value of field 1 @ time2>, <value of field 2 @ time2>, ...],
  //      *   ]
  //      * }
  //      */
  //     const measurementName = series.name;
  //     const columns = series.columns;
  //     // Tags are only included in an influxdb response under certain circumstances, e.g.
  //     // when a query is using GROUP BY (<tag key>).
  //     const tags = Object.keys(series.tags || {}).map((key) => {
  //       return `[${key}=${series.tags[key]}]`;
  //     }).sort().join('');
  //
  //     const c = columns.slice(1).sort();
  //     let previousColumnLength = 0;
  //
  //     if (c.length != previousColumnLength) {
  //       previousColumnLength = c.length;
  //     }
  //
  //     c.forEach((fieldName) => {
  //       let effectiveFieldName = `${measurementName}.${fieldName}${tags}`;
  //
  //       // If there are duplicate effectiveFieldNames identify them by their queryIndex
  //       if (effectiveFieldName in dygraphSeries) {
  //         effectiveFieldName = `${effectiveFieldName}-${queryIndex}`;
  //       }
  //
  //       // Given a field name, identify which column in the timeSeries result should hold the field's value
  //       // ex given this timeSeries [Date, 10, 20, 30] field index at 2 would correspond to value 20
  //       fieldToIndex[effectiveFieldName] = c.indexOf(fieldName);
  //       labels.push(effectiveFieldName);
  //
  //       const {light, heavy} = STROKE_WIDTH;
  //
  //       const dygraphSeriesStyles = {
  //         strokeWidth: queryIndex === activeQueryIndex ? heavy : light,
  //       };
  //
  //       if (!isInDataExplorer) {
  //         dygraphSeriesStyles.axis = queryIndex === 0 ? 'y' : 'y2';
  //       }
  //
  //       dygraphSeries[effectiveFieldName] = dygraphSeriesStyles;
  //     });
  //
  //     (series.values || []).forEach(parseRow);
  //
  //
  //
  //     function parseRow(row) {
  //       /**
  //        * row looks like:
  //        *   [<time1>, <value of field 1 @ time1>, <value of field 2 @ time1>, ...]
  //        */
  //       const date = row[0];
  //       const dateString = date.toString();
  //       row.forEach((value, index) => {
  //         if (index === 0) {
  //           // index 0 in a row is always the timestamp
  //           if (!dateToFieldValue[dateString]) {
  //             dateToFieldValue[dateString] = {};
  //             dates[dateString] = date;
  //           }
  //           return;
  //         }
  //
  //         const fieldName = columns[index];
  //         let effectiveFieldName = `${measurementName}.${fieldName}${tags}`;
  //
  //         // If there are duplicate effectiveFieldNames identify them by their queryIndex
  //         if (effectiveFieldName in dateToFieldValue[dateString]) {
  //           effectiveFieldName = `${effectiveFieldName}-${queryIndex}`;
  //         }
  //
  //         dateToFieldValue[dateString][effectiveFieldName] = value;
  //       });
  //     }
  //   }
  // });
  //
  // function buildTimeSeries() {
  //   const allDates = Object.keys(dateToFieldValue);
  //   allDates.sort((a, b) => a - b);
  //   const rowLength = labels.length + 1;
  //   return allDates.map((date) => {
  //     const row = new Array(rowLength);
  //
  //     row.fill(null);
  //     row[0] = new Date(dates[date]);
  //
  //     const fieldsForRow = dateToFieldValue[date];
  //
  //     Object.keys(fieldsForRow).forEach((effectiveFieldName) => {
  //       row[fieldToIndex[effectiveFieldName]] = fieldsForRow[effectiveFieldName];
  //     });
  //
  //     return row;
  //   });
  // }

}

function isEmpty(resp) {
  return !resp.results[0].series;
}

function hasError(resp) {
  return !!resp.results[0].error;
}
<commit_msg>Cleanup. Passes linter.<commit_after>import _ from 'lodash';
import {STROKE_WIDTH} from 'src/shared/constants';
/**
 * Accepts an array of raw influxdb responses and returns a format
 * that Dygraph understands.
 */

// activeQueryIndex is an optional argument that indicated which query's series we want highlighted.
export default function timeSeriesToDygraph(raw = [], activeQueryIndex, isInDataExplorer) {
  // collect results from each influx response
  const results = raw.reduce((acc, rawResponse, responseIndex) => {
    const responses = _.get(rawResponse, 'response.results', []);
    const indexedResponses = responses.map((response) => ({...response, responseIndex}));
    return [...acc, ...indexedResponses];
  }, []);

  // collect each series
  const serieses = results.reduce((acc, {series, responseIndex}, index) => {
    return [...acc, ...series.map((item) => ({...item, responseIndex, index}))];
  }, []);

  // convert series into cells with rows and columns
  const cells = serieses.reduce((acc, {name, columns, values, index, responseIndex}) => {
    const rows = values.map((vals) => ({
      name,
      columns,
      vals,
      index,
    }));

    rows.forEach(({vals, columns: cols, name: n, index: seriesIndex}) => {
      const [time, ...rowValues] = vals;
      rowValues.forEach((value, i) => {
        const column = cols[i + 1];
        acc.push({
          label: `${n}.${column}`,
          value,
          time,
          seriesIndex,
          responseIndex,
        });
      });
    });

    return acc;
  }, []);

  const labels = cells.reduce((acc, {label, seriesIndex, responseIndex}) => {
    const existingLabel = acc.find(({
      label: findLabel,
      seriesIndex: findSeriesIndex,
    }) => findLabel === label && findSeriesIndex === seriesIndex);

    if (!existingLabel) {
      acc.push({
        label,
        seriesIndex,
        responseIndex,
      });
    }

    return acc;
  }, []);

  const sortedLabels = _.sortBy(labels, 'label');

  const timeSeries = cells.reduce((acc, cell) => {
    let existingRowIndex = acc.findIndex(({time}) => cell.time === time);

    if (existingRowIndex === -1) {
      acc.push({
        time: cell.time,
        values: Array(sortedLabels.length).fill(null),
      });

      existingRowIndex = acc.length - 1;
    }

    const values = acc[existingRowIndex].values;
    const labelIndex = sortedLabels.findIndex(({label, seriesIndex}) => label === cell.label && cell.seriesIndex === seriesIndex);
    values[labelIndex] = cell.value;
    acc[existingRowIndex].values = values;

    return acc;
  }, []);

  const sortedTimeSeries = _.sortBy(timeSeries, 'time');

  const {light, heavy} = STROKE_WIDTH;

  const dygraphSeries = sortedLabels.reduce((acc, {label, responseIndex}) => {
    acc[label] = {
      strokeWidth: responseIndex === activeQueryIndex ? heavy : light,
    };

    if (!isInDataExplorer) {
      acc[label].axis = responseIndex === 0 ? 'y' : 'y2';
    }

    return acc;
  }, {});

  return {
    timeSeries: sortedTimeSeries.map(({time, values}) => ([new Date(time), ...values])),
    labels: ["time", ...sortedLabels.map(({label}) => label)],
    dygraphSeries,
  };
}
<|endoftext|>