<commit_before>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneEvents = require('./events'),
    watchElement = require('../watch').element;

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zone = Object.create({}),
        apiNamespace = eventerface.create(),
        localNamespace = eventerface.create(),
        zoneEmitter = localNamespace.emitter(),
        zoneProperties = createZoneProperties(properties, apiNamespace, zoneEmitter);

    Object.defineProperties(zone, zoneProperties);

    // Watch and route events on changes to zone properties
    eventerface.find('zone_' + zone.id, function (zoneNamespace) {
        zoneEvents.watchProperties(zoneNamespace, localNamespace.emitter());
        zone.events.emit('ready');
    });

    return zone;
}

function createZoneProperties(properties, apiNamespace, zoneEmitter) {
    var apiEmitter = apiNamespace.emitter();

    var properties = {
        // ID of the zone
        id: {
            value: properties.id
        },
        // Name of the zone
        name: changeGetterSetter('name', 'name', properties.name, zoneEmitter),
        // Size of the zone
        size: {
            value: Object.create({}, {
                x: changeGetterSetter('size', 'x', properties.size.x, zoneEmitter),
                y: changeGetterSetter('size', 'y', properties.size.y, zoneEmitter),
                z: changeGetterSetter('size', 'z', properties.size.z, zoneEmitter)
            })
        },
        // Zone limits
        limits: marginGetterSetter('limits', properties.limits, zoneEmitter),
        // Zone center coordinates
        coordinates: {
            value: Object.create({}, {
                x: changeGetterSetter('coordinates', 'x', properties.coordinates.x, zoneEmitter),
                y: changeGetterSetter('coordinates', 'y', properties.coordinates.y, zoneEmitter),
                z: changeGetterSetter('coordinates', 'z', properties.coordinates.z, zoneEmitter)
            })
        },
        // Maximum range of visibility
        visibility: {
            value: Object.create({}, {
                horizontal: changeGetterSetter('visibility', 'horizontal', properties.visibility.horizontal, zoneEmitter),
                vertical: changeGetterSetter('visibility', 'vertical', properties.visibility.vertical, zoneEmitter)
            })
        },
        // Bookin and checkin margin size
        handover: changeGetterSetter('handover', 'handover', properties.handover, zoneEmitter),
        // Zone scope and handover limits
        margins: {
            value: Object.create({}, {
                scope: {
                    value: Object.create({}, {
                        inner: marginGetterSetter('innerScope', properties.margins.scope.inner, zoneEmitter),
                        outer: marginGetterSetter('outerScope', properties.margins.scope.outer, zoneEmitter)
                    })
                },
                handover: {
                    value: Object.create({}, {
                        bookin: marginGetterSetter('bookinMargin', properties.margins.handover.bookin, zoneEmitter),
                        checkin: marginGetterSetter('checkinMargin', properties.margins.handover.checkin, zoneEmitter)
                    })
                }
            })
        },
        elements: createElementsContainer(zoneEmitter),

        // API events
        events: {
            value: apiNamespace.emitter()
        },
        on: {
            value: function (event, callback) {
                apiEmitter.on(event, callback);
            }
        },
        emit: {
            writable: true,
            value: function (event, message) {
                apiEmitter.emit(event, message);
            }
        }
    };

    return properties;
}

/*----------------------------------------------------------------------------*/

function changeGetterSetter(typeofChange, propertyChanged, initialValue, eventEmitter) {
    var value = initialValue;
    return {
        get: function () {
            return value;
        },
        set: function (newValue) {
            value = newValue;
            eventEmitter.emit(typeofChange + 'Change', {
                property: propertyChanged,
                value: newValue
            });
        }
    }
}

function marginGetterSetter(typeofChange, margins, emitter) {
    function margin(propertyChanged, margin) {
        return {
            value: Object.create({}, {
                lower: (function (value) {
                    return {
                        get: function () {
                            return value;
                        },
                        set: function (newValue) {
                            // value = newValue;
                            emitter.emit(typeofChange + 'Change', {
                                property: propertyChanged,
                                side: 'lower',
                                value: newValue
                            });
                        }
                    };
                })(margin.lower),
                higher: (function (value) {
                    return {
                        get: function () {
                            return value;
                        },
                        set: function (newValue) {
                            // value = newValue;
                            emitter.emit(typeofChange + 'Change', {
                                property: propertyChanged,
                                side: 'higher',
                                value: newValue
                            });
                        }
                    };
                })(margin.higher)
            })
        };
    }
    return {
        value: Object.create({}, {
            x: new margin('x', margins.x),
            y: new margin('y', margins.y),
            z: new margin('z', margins.z)
        })
    }
}

/*----------------------------------------------------------------------------*/

function createElementsContainer(emitter) {
    var elements = {},
        getMethods = function (container) {
            return {
                add: { value: addElement.bind(container, emitter) },
                remove: { value: removeElement.bind(container, emitter) }
            }
        },
        elementMethods = getMethods(elements);

    Object.defineProperties(elements, elementMethods);

    return {
        get: function (key) {
            return (typeof key === 'string') ? elements[key] : elements;
        },
        set: function (arrayObject) {
            if (typeof arrayObject === 'object') {
                elements = arrayObject;
                Object.defineProperties(elements, getMethods(elements));
                return true;
            }
            return false;
        }
    };
}

function addElement(emitter, element, key) {
    var elements = this,
        addWith,
        id = element.id,
        name = element.name;

    if (typeof key === 'string' && !elements[key]) {
        addWith = key;
    } else if (typeof id === 'string' && !elements[id]) {
        addWith = id;
    } else if (typeof name === 'string' && !elements[name]) {
        addWith = name;
    }

    if (addWith) {
        Object.defineProperty(elements, addWith, {
            enumerable: true,
            writable: true,
            configurable: true,
            value: watchElement(element, emitter)
        });
        emitter.emit('addElement', elements[addWith]);
    }

    return addWith;
}

function removeElement(emitter, key) {
    var elements = this;
    if (typeof elements[key] !== 'object') {
        return false;
    } else {
        delete elements[key];
        emitter.emit('removeElement', key);
        return true;
    }
}<commit_msg>Enclosed all the functions inside the #create method in order to remove dependency injection of the emitter object<commit_after>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneEvents = require('./events'),
    watchElement = require('../watch').element;

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zone = Object.create({}),
        apiNamespace = eventerface.create(),
        localNamespace = eventerface.create(),
        zoneEmitter = localNamespace.emitter(),
        zoneProperties = createZoneProperties(properties, apiNamespace);

    Object.defineProperties(zone, zoneProperties);

    // Watch and route events on changes to zone properties
    eventerface.find('zone_' + zone.id, function (zoneNamespace) {
        zoneEvents.watchProperties(zoneNamespace, localNamespace.emitter());
        zone.events.emit('ready');
    });

    /*----------------------------------------------------------------------------*/

    function createZoneProperties(properties, apiNamespace) {
        var apiEmitter = apiNamespace.emitter();

        var properties = {
            // ID of the zone
            id: {
                value: properties.id
            },
            // Name of the zone
            name: changeGetterSetter('name', 'name', properties.name),
            // Size of the zone
            size: {
                value: Object.create({}, {
                    x: changeGetterSetter('size', 'x', properties.size.x),
                    y: changeGetterSetter('size', 'y', properties.size.y),
                    z: changeGetterSetter('size', 'z', properties.size.z)
                })
            },
            // Zone limits
            limits: marginGetterSetter('limits', properties.limits),
            // Zone center coordinates
            coordinates: {
                value: Object.create({}, {
                    x: changeGetterSetter('coordinates', 'x', properties.coordinates.x),
                    y: changeGetterSetter('coordinates', 'y', properties.coordinates.y),
                    z: changeGetterSetter('coordinates', 'z', properties.coordinates.z)
                })
            },
            // Maximum range of visibility
            visibility: {
                value: Object.create({}, {
                    horizontal: changeGetterSetter('visibility', 'horizontal', properties.visibility.horizontal),
                    vertical: changeGetterSetter('visibility', 'vertical', properties.visibility.vertical)
                })
            },
            // Bookin and checkin margin size
            handover: changeGetterSetter('handover', 'handover', properties.handover),
            // Zone scope and handover limits
            margins: {
                value: Object.create({}, {
                    scope: {
                        value: Object.create({}, {
                            inner: marginGetterSetter('innerScope', properties.margins.scope.inner),
                            outer: marginGetterSetter('outerScope', properties.margins.scope.outer)
                        })
                    },
                    handover: {
                        value: Object.create({}, {
                            bookin: marginGetterSetter('bookinMargin', properties.margins.handover.bookin),
                            checkin: marginGetterSetter('checkinMargin', properties.margins.handover.checkin)
                        })
                    }
                })
            },
            elements: createElementsContainer(),

            // API events
            events: {
                value: apiNamespace.emitter()
            },
            on: {
                value: function (event, callback) {
                    apiEmitter.on(event, callback);
                }
            },
            emit: {
                writable: true,
                value: function (event, message) {
                    apiEmitter.emit(event, message);
                }
            }
        };

        return properties;
    }

    /*----------------------------------------------------------------------------*/

    function changeGetterSetter(typeofChange, propertyChanged, initialValue) {
        var value = initialValue;
        return {
            get: function () {
                return value;
            },
            set: function (newValue) {
                value = newValue;
                zoneEmitter.emit(typeofChange + 'Change', {
                    property: propertyChanged,
                    value: newValue
                });
            }
        }
    }

    function marginGetterSetter(typeofChange, margins) {
        function margin(propertyChanged, margin) {
            return {
                value: Object.create({}, {
                    lower: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                zoneEmitter.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'lower',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.lower),
                    higher: (function (value) {
                        return {
                            get: function () {
                                return value;
                            },
                            set: function (newValue) {
                                // value = newValue;
                                zoneEmitter.emit(typeofChange + 'Change', {
                                    property: propertyChanged,
                                    side: 'higher',
                                    value: newValue
                                });
                            }
                        };
                    })(margin.higher)
                })
            };
        }
        return {
            value: Object.create({}, {
                x: new margin('x', margins.x),
                y: new margin('y', margins.y),
                z: new margin('z', margins.z)
            })
        }
    }

    /*----------------------------------------------------------------------------*/

    function createElementsContainer() {
        var elements = {},
            getMethods = function (container) {
                return {
                    add: { value: addElement.bind(container) },
                    remove: { value: removeElement.bind(container) }
                }
            },
            elementMethods = getMethods(elements);

        Object.defineProperties(elements, elementMethods);

        return {
            get: function (key) {
                return (typeof key === 'string') ? elements[key] : elements;
            },
            set: function (arrayObject) {
                if (typeof arrayObject === 'object') {
                    elements = arrayObject;
                    Object.defineProperties(elements, getMethods(elements));
                    return true;
                }
                return false;
            }
        };
    }

    function addElement(element, key) {
        var elements = this,
            addWith,
            id = element.id,
            name = element.name;

        if (typeof key === 'string' && !elements[key]) {
            addWith = key;
        } else if (typeof id === 'string' && !elements[id]) {
            addWith = id;
        } else if (typeof name === 'string' && !elements[name]) {
            addWith = name;
        }

        if (addWith) {
            Object.defineProperty(elements, addWith, {
                enumerable: true,
                writable: true,
                configurable: true,
                value: watchElement(element, zoneEmitter)
            });
            zoneEmitter.emit('addElement', elements[addWith]);
        }

        return addWith;
    }

    function removeElement(key) {
        var elements = this;
        if (typeof elements[key] !== 'object') {
            return false;
        } else {
            delete elements[key];
            zoneEmitter.emit('removeElement', key);
            return true;
        }
    }

/*----------------------------------------------------------------------------*/
// END OF #CREATE
    return zone;
}
/*----------------------------------------------------------------------------*/<|endoftext|>


<commit_before>'use strict';

const Term = function(en, fr) {
  this.en = en;
  this.fr = fr;
};

const Couple = function(id, firstTerm, secondTerm, wtf, polarized) {
  this.id = id;
  this.firstTerm = firstTerm;
  this.secondTerm = secondTerm;
  this.wtf = wtf;
  this.polarized = polarized;
};
Couple.prototype = {
  hasTerm: function(term, lang) {
    if (this.firstTerm[lang] === term) {
      return true;
    }
    if (this.secondTerm[lang] === term) {
      return true;
    }
    return false;
  }
};

const CoupleManager = function() {
  this.couples = [];
};
CoupleManager.prototype = {
  addCouple: function(couple) {
    this.couples.push(couple);
  },
  getRandom: function(ignoredCouple) {
    let couple = this.couples[Math.floor(Math.random() * this.couples.length)];
    if (ignoredCouple && couple == ignoredCouple) {
      couple = this.getRandom(ignoredCouple);
    }
    return couple;
  },
  termExists: function(term, lang) {
    for (var i = 0, c = this.couples.length; i < c; i++) {
      if (this.couples[i].hasTerm(term, lang)) {
        return true;
      }
    }
    return false;
  }
}
const couples = new CoupleManager();

let couple, firstTerm, secondTerm;

firstTerm = new Term('man', 'homme');
secondTerm = new Term('woman', 'femme');
couple = new Couple('man-woman', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('dog', 'chien');
secondTerm = new Term('cat', 'chat');
couple = new Couple('dog-cat', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('gay', 'gay');
secondTerm = new Term('straight', 'hétéro');
couple = new Couple('gay-straight', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('black', 'noir');
secondTerm = new Term('white', 'blanc');
couple = new Couple('black-white', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('smart', 'intelligent');
secondTerm = new Term('dumb', 'bête');
couple = new Couple('smart-dumb', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

// firstTerm = new Term('nice', 'gentil');
// secondTerm = new Term('mean', 'méchant');
// couple = new Couple('nice-mean', firstTerm, secondTerm, false, true);
// couples.addCouple(couple);
//
firstTerm = new Term('vote left', 'de gauche');
secondTerm = new Term('vote right', 'de droite');
couple = new Couple('leftist-rightist', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('vulgar', 'vulgaire');
// secondTerm = new Term('refined', 'raffiné');
// couple = new Couple('vulgar-refined', firstTerm, secondTerm, false, true);
// couples.addCouple(couple);
//
// firstTerm = new Term('vegeterian', 'végétarien');
// secondTerm = new Term('meat-eater', 'omnivore');
// couple = new Couple('vegetarian-meat-eater', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('smoker', 'fumeur');
// secondTerm = new Term('non-smoker', 'non-fumeur');
// couple = new Couple('smoker-non-smoker', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
firstTerm = new Term('young', 'jeune');
secondTerm = new Term('old', 'vieux');
couple = new Couple('young-old', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('manual', 'manuel');
// secondTerm = new Term('intellectual', 'intellectuel');
// couple = new Couple('manual-intellectual', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);

firstTerm = new Term('shaved', 'rasé');
secondTerm = new Term('hairy', 'poilu');
couple = new Couple('shaved-hairy', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('happy', 'heureux');
secondTerm = new Term('sad', 'malheureux');
couple = new Couple('happy-sad', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('tall', 'grand');
// secondTerm = new Term('small', 'petit');
// couple = new Couple('tall-small', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('fat', 'gros');
// secondTerm = new Term('skinny', 'maigre');
// couple = new Couple('fat-skinny', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('original', 'original');
// secondTerm = new Term('conformist', 'conformiste');
// couple = new Couple('original-conformist', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);

firstTerm = new Term('believer', 'croyant');
secondTerm = new Term('atheist', 'athée');
couple = new Couple('believer-atheist', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('fast', 'rapide');
secondTerm = new Term('slow', 'lent');
couple = new Couple('fast-slow', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('beautiful', 'beau');
secondTerm = new Term('ugly', 'moche');
couple = new Couple('beautiful-ugly', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('funny', 'drôle');
secondTerm = new Term('serious', 'sérieux');
couple = new Couple('funny-serious', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('lazy', 'paresseux');
secondTerm = new Term('hard-working', 'travailleur');
couple = new Couple('lazy-hard-worker', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('rich', 'riche');
secondTerm = new Term('poor', 'pauvre');
couple = new Couple('rich-poor', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

// firstTerm = new Term('sick', 'malade');
// secondTerm = new Term('healthy', 'bien portant');
// couple = new Couple('sick-healthy', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('relaxed', 'relax');
// secondTerm = new Term('anxious', 'anxieux');
// couple = new Couple('relaxed-anxious', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('few', 'peu');
// secondTerm = new Term('many', 'nombreux');
// couple = new Couple('few-many', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);

firstTerm = new Term('robot', 'robot');
secondTerm = new Term('human', 'humain');
couple = new Couple('robot-human', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('dangerous', 'dangereux');
secondTerm = new Term('harmless', 'inofensif');
couple = new Couple('dangerous-harmless', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

// firstTerm = new Term('fragile', 'fragile');
// secondTerm = new Term('solid', 'solide');
// couple = new Couple('fragile-solid', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
firstTerm = new Term('fruit', 'fruit');
secondTerm = new Term('vegetable', 'légume');
couple = new Couple('fruit-vegetable', firstTerm, secondTerm, true, false);
couples.addCouple(couple);
//
// firstTerm = new Term('scientific', 'scientifique');
// secondTerm = new Term('artist', 'artiste');
// couple = new Couple('scientific-artist', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('introverted', 'introverti');
// secondTerm = new Term('extraverted', 'extraverti');
// couple = new Couple('introverted-extraverted', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('hot', 'chaud');
// secondTerm = new Term('cold', 'froid');
// couple = new Couple('hot-cold', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('commited', 'impliqué');
// secondTerm = new Term('indifferent', 'indifférent');
// couple = new Couple('commited-indifferent', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);

firstTerm = new Term('brave', 'coward');
secondTerm = new Term('coward', 'lache');
couple = new Couple('brave-coward', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

// firstTerm = new Term('liar', 'menteur');
// secondTerm = new Term('honest', 'honnête');
// couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
// couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

firstTerm = new Term('batman', 'batman');
secondTerm = new Term('superman', 'superman');
couple = new Couple('batman-superman', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('jewish', 'juif');
secondTerm = new Term('muslim', 'musulman');
couple = new Couple('jewish-musulman', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

module.exports = couples;
<commit_msg>Update couples.js<commit_after>'use strict';

const Term = function(en, fr) {
  this.en = en;
  this.fr = fr;
};

const Couple = function(id, firstTerm, secondTerm, wtf, polarized) {
  this.id = id;
  this.firstTerm = firstTerm;
  this.secondTerm = secondTerm;
  this.wtf = wtf;
  this.polarized = polarized;
};
Couple.prototype = {
  hasTerm: function(term, lang) {
    if (this.firstTerm[lang] === term) {
      return true;
    }
    if (this.secondTerm[lang] === term) {
      return true;
    }
    return false;
  }
};

const CoupleManager = function() {
  this.couples = [];
};
CoupleManager.prototype = {
  addCouple: function(couple) {
    this.couples.push(couple);
  },
  getRandom: function(ignoredCouple) {
    let couple = this.couples[Math.floor(Math.random() * this.couples.length)];
    if (ignoredCouple && couple == ignoredCouple) {
      couple = this.getRandom(ignoredCouple);
    }
    return couple;
  },
  termExists: function(term, lang) {
    for (var i = 0, c = this.couples.length; i < c; i++) {
      if (this.couples[i].hasTerm(term, lang)) {
        return true;
      }
    }
    return false;
  }
}
const couples = new CoupleManager();

let couple, firstTerm, secondTerm;

firstTerm = new Term('man', 'homme');
secondTerm = new Term('woman', 'femme');
couple = new Couple('man-woman', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('dog', 'chien');
secondTerm = new Term('cat', 'chat');
couple = new Couple('dog-cat', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('gay', 'gay');
secondTerm = new Term('straight', 'hétéro');
couple = new Couple('gay-straight', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('black', 'noir');
secondTerm = new Term('white', 'blanc');
couple = new Couple('black-white', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('smart', 'intelligent');
secondTerm = new Term('dumb', 'bête');
couple = new Couple('smart-dumb', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('nice', 'gentil');
secondTerm = new Term('mean', 'méchant');
couple = new Couple('nice-mean', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('vote left', 'de gauche');
secondTerm = new Term('vote right', 'de droite');
couple = new Couple('leftist-rightist', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('vulgar', 'vulgaire');
// secondTerm = new Term('refined', 'raffiné');
// couple = new Couple('vulgar-refined', firstTerm, secondTerm, false, true);
// couples.addCouple(couple);
//
// firstTerm = new Term('vegeterian', 'végétarien');
// secondTerm = new Term('meat-eater', 'omnivore');
// couple = new Couple('vegetarian-meat-eater', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('smoker', 'fumeur');
// secondTerm = new Term('non-smoker', 'non-fumeur');
// couple = new Couple('smoker-non-smoker', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
firstTerm = new Term('young', 'jeune');
secondTerm = new Term('old', 'vieux');
couple = new Couple('young-old', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('manual', 'manuel');
// secondTerm = new Term('intellectual', 'intellectuel');
// couple = new Couple('manual-intellectual', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);

firstTerm = new Term('shaved', 'rasé');
secondTerm = new Term('hairy', 'poilu');
couple = new Couple('shaved-hairy', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('happy', 'heureux');
secondTerm = new Term('sad', 'malheureux');
couple = new Couple('happy-sad', firstTerm, secondTerm, false, false);
couples.addCouple(couple);
//
// firstTerm = new Term('tall', 'grand');
// secondTerm = new Term('small', 'petit');
// couple = new Couple('tall-small', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('fat', 'gros');
// secondTerm = new Term('skinny', 'maigre');
// couple = new Couple('fat-skinny', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('original', 'original');
// secondTerm = new Term('conformist', 'conformiste');
// couple = new Couple('original-conformist', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);

firstTerm = new Term('believer', 'croyant');
secondTerm = new Term('atheist', 'athée');
couple = new Couple('believer-atheist', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('fast', 'rapide');
secondTerm = new Term('slow', 'lent');
couple = new Couple('fast-slow', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('beautiful', 'beau');
secondTerm = new Term('ugly', 'moche');
couple = new Couple('beautiful-ugly', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('funny', 'drôle');
secondTerm = new Term('serious', 'sérieux');
couple = new Couple('funny-serious', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('lazy', 'paresseux');
secondTerm = new Term('hard-working', 'travailleur');
couple = new Couple('lazy-hard-worker', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('rich', 'riche');
secondTerm = new Term('poor', 'pauvre');
couple = new Couple('rich-poor', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

// firstTerm = new Term('sick', 'malade');
// secondTerm = new Term('healthy', 'bien portant');
// couple = new Couple('sick-healthy', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('relaxed', 'relax');
// secondTerm = new Term('anxious', 'anxieux');
// couple = new Couple('relaxed-anxious', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('few', 'peu');
// secondTerm = new Term('many', 'nombreux');
// couple = new Couple('few-many', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);

firstTerm = new Term('robot', 'robot');
secondTerm = new Term('human', 'humain');
couple = new Couple('robot-human', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('dangerous', 'dangereux');
secondTerm = new Term('harmless', 'inofensif');
couple = new Couple('dangerous-harmless', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

// firstTerm = new Term('fragile', 'fragile');
// secondTerm = new Term('solid', 'solide');
// couple = new Couple('fragile-solid', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
firstTerm = new Term('fruit', 'fruit');
secondTerm = new Term('vegetable', 'légume');
couple = new Couple('fruit-vegetable', firstTerm, secondTerm, true, false);
couples.addCouple(couple);
//
// firstTerm = new Term('scientific', 'scientifique');
// secondTerm = new Term('artist', 'artiste');
// couple = new Couple('scientific-artist', firstTerm, secondTerm, false, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('introverted', 'introverti');
// secondTerm = new Term('extraverted', 'extraverti');
// couple = new Couple('introverted-extraverted', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('hot', 'chaud');
// secondTerm = new Term('cold', 'froid');
// couple = new Couple('hot-cold', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);
//
// firstTerm = new Term('commited', 'impliqué');
// secondTerm = new Term('indifferent', 'indifférent');
// couple = new Couple('commited-indifferent', firstTerm, secondTerm, true, false);
// couples.addCouple(couple);

firstTerm = new Term('brave', 'coward');
secondTerm = new Term('coward', 'lache');
couple = new Couple('brave-coward', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

// firstTerm = new Term('liar', 'menteur');
// secondTerm = new Term('honest', 'honnête');
// couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
// couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

//firstTerm = new Term('liar', 'menteur');
//secondTerm = new Term('honest', 'honnête');
//couple = new Couple('liar-honest', firstTerm, secondTerm, false, true);
//couples.addCouple(couple);

firstTerm = new Term('batman', 'batman');
secondTerm = new Term('superman', 'superman');
couple = new Couple('batman-superman', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('jewish', 'juif');
secondTerm = new Term('muslim', 'musulman');
couple = new Couple('jewish-musulman', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

firstTerm = new Term('mac', 'mac');
secondTerm = new Term('PC', 'PC');
couple = new Couple('mac-pc', firstTerm, secondTerm, true, false);
couples.addCouple(couple);

firstTerm = new Term('generous', 'généreux');
secondTerm = new Term('avaricious', 'avare');
couple = new Couple('generous-avaricious', firstTerm, secondTerm, false, true);
couples.addCouple(couple);

firstTerm = new Term('handicaped', 'handicapé');
secondTerm = new Term('able-bodied', 'valide');
couple = new Couple('handicaped-able-bodied', firstTerm, secondTerm, false, false);
couples.addCouple(couple);

module.exports = couples;
<|endoftext|>


<commit_before>enyo.kind({
	name: "ares.Node",
	kind: "Node",
	events: {
		onFileClick: "",
		onFolderClick: "",
		onFileDblClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null
	},

	debug: true,

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		if (this.debug) this.log(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				if (this.debug) this.log("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
    updateNodeContent: function(files) {
		var i = 0 , nfiles, rfiles, res, modified = 0, newControl ;

		if (this.debug) this.log("updateNodeContent on",this) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			if (this.debug) this.log("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes(files) ; // with prefix in name
		nfiles = this.getNodeFiles() ;

		while ( i < nfiles.length || i < rfiles.length) {
			if (this.debug) this.log("considering node " + (nfiles[i] ? nfiles[i].name : '<none>') + ' and file ' + (rfiles[i] ? rfiles[i].name : '<none>') );

			res = i >= nfiles.length ? 1
			    : i >= rfiles.length ? -1
			    :                      this.fileNameSort(nfiles[i], rfiles[i]) ;

			// remember that these file lists are sorted
			switch(res) {
				case -1: // remote file removed
					if (this.debug) this.log(nfiles[i].name + " was removed") ;
					nfiles[i].destroy() ;
				    modified = 1;
					nfiles = this.getNodeFiles() ;
					// node file list reduced by one, must not increment i
					break ;

				case 0: // no change
					i++ ;
					break ;

				case 1: // file added
				    if (this.debug) this.log(rfiles[i].name + " was added") ;
					newControl = this.createComponent( rfiles[i], {kind: "ares.Node"} ) ;
					if (this.debug) this.log("updateNodeContent created ", newControl) ;
					newControl.setService(this.service);
					nfiles = this.getNodeFiles() ;
					// FIXME: ENYO-1337
					//if (nfiles[i]) {
					//	var justAdded = inNode.controls.pop() ;
					//	inNode.controls.splice(i+4, 0, justAdded);
					//}
				    modified = 1;
					if (nfiles[i].name === '$project.json') {
						// project.json file is internal to Ares
						nfiles[i].hide();
					}
					i++ ;
					break ;
			}

		}

		if (modified) {
			this.$.client.render();
		}
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},
	filesToNodes: function(inFiles) {
		var nodes = [];
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0, f; f=inFiles[i]; i++) {
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		if (this.debug) this.log(inSender, "=>", inEvent);

		if (this.debug) this.log("nodeExpand called while node Expanded is " + this.expanded) ;
		// update icon for expanded state
		if (this.file.isDir) {
			this.setIcon("$services/assets/images/" + (this.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (this.expanded) {
			this.updateNodes().
				response(this, function() {
					this.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		if (this.debug) this.log(this) ;
		var target = this ;

		if (this.debug) this.log('running refreshTree with ' +
					 this.controls.length + ' controls with content ' + this.content +
					 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					if (this.debug) this.log('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						if (this.debug) this.log('force select of ' + c.file.id);
						c.doAresNodeTap();
						this.doAdjustScroll() ;
						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + JSON.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.showErrorPopup(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.debug && this.log("refreshTree done") ;
	}

});

<commit_msg>ENYO-1996: call node expand on a subnode and not on self<commit_after>enyo.kind({
	name: "ares.Node",
	kind: "Node",
	events: {
		onFileClick: "",
		onFolderClick: "",
		onFileDblClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null
	},

	debug: true,

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		if (this.debug) this.log(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				if (this.debug) this.log("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
    updateNodeContent: function(files) {
		var i = 0 , nfiles, rfiles, res, modified = 0, newControl ;

		if (this.debug) this.log("updateNodeContent on",this) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			if (this.debug) this.log("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes(files) ; // with prefix in name
		nfiles = this.getNodeFiles() ;

		while ( i < nfiles.length || i < rfiles.length) {
			if (this.debug) this.log("considering node " + (nfiles[i] ? nfiles[i].name : '<none>') + ' and file ' + (rfiles[i] ? rfiles[i].name : '<none>') );

			res = i >= nfiles.length ? 1
			    : i >= rfiles.length ? -1
			    :                      this.fileNameSort(nfiles[i], rfiles[i]) ;

			// remember that these file lists are sorted
			switch(res) {
				case -1: // remote file removed
					if (this.debug) this.log(nfiles[i].name + " was removed") ;
					nfiles[i].destroy() ;
				    modified = 1;
					nfiles = this.getNodeFiles() ;
					// node file list reduced by one, must not increment i
					break ;

				case 0: // no change
					i++ ;
					break ;

				case 1: // file added
				    if (this.debug) this.log(rfiles[i].name + " was added") ;
					newControl = this.createComponent( rfiles[i], {kind: "ares.Node"} ) ;
					if (this.debug) this.log("updateNodeContent created ", newControl) ;
					newControl.setService(this.service);
					nfiles = this.getNodeFiles() ;
					// FIXME: ENYO-1337
					//if (nfiles[i]) {
					//	var justAdded = inNode.controls.pop() ;
					//	inNode.controls.splice(i+4, 0, justAdded);
					//}
				    modified = 1;
					if (nfiles[i].name === '$project.json') {
						// project.json file is internal to Ares
						nfiles[i].hide();
					}
					i++ ;
					break ;
			}

		}

		if (modified) {
			this.$.client.render();
		}
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},
	filesToNodes: function(inFiles) {
		var nodes = [];
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0, f; f=inFiles[i]; i++) {
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		if (this.debug) this.log(inSender, "=>", inEvent);

		var subnode = inEvent.originator;
		if (this.debug) this.log("nodeExpand called while node Expanded is " + subnode.expanded) ;
		// update icon for expanded state
		if (subnode.file.isDir) {
			subnode.setIcon("$services/assets/images/" + (subnode.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (subnode.expanded) {
			subnode.updateNodes().
				response(this, function() {
					subnode.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		if (this.debug) this.log(this) ;
		var target = this ;

		if (this.debug) this.log('running refreshTree with ' +
					 this.controls.length + ' controls with content ' + this.content +
					 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					if (this.debug) this.log('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						if (this.debug) this.log('force select of ' + c.file.id);
						c.doAresNodeTap();
						this.doAdjustScroll() ;
						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + JSON.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.showErrorPopup(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.debug && this.log("refreshTree done") ;
	}

});

<|endoftext|>


<commit_before>var longToShortMap = new Map();
var shortToLongMap = new Map();

var genCharArray = function (charA, charZ) {
    var arr = [];
    var i = charA.charCodeAt(0);
    var j = charZ.charCodeAt(0);

    for (var k = i; k <= j; k++) {
        arr.push(String.fromCharCode(k));
    }

    return arr;
};

var encode = function () {
    var encodeArr = [];
    encodeArr = encodeArr.concat(genCharArray('0', '9'));
    encodeArr = encodeArr.concat(genCharArray('A', 'Z'));
    encodeArr = encodeArr.concat(genCharArray('a', 'z'));
    return encodeArr;
}();

function recursiveFunc (x, result) {
    var v = Math.floor(x/62);
    var m = x % 62;
    var tempResult = encode[m] + result;
    if (v == 0) {
        return tempResult;
    } else if (v > 0 && v < 62){
        return encode[v] + tempResult;
    } else if (v >= 62) {
        return recursiveFunc(v, tempResult);
    }
}

function ConvertTo62(size) {
    return recursiveFunc(size, "");
}

function ConvertToInt(shortUrl) {
    var length = shortUrl.length;
    var shortUrlInNumber = 0;
    for (var i = 0; i < length; i++) {
        var encodingLength = encode.length;
        var c = shortUrl.charAt(i);
        var index = encode.indexOf(c);
        shortUrlInNumber += index * Math.pow(encodingLength, length-i-1);
    }
    return shortUrlInNumber;
}

function enrichLongUrl(longUrl) {
    if (longUrl.indexOf('http') === -1) {
        longUrl = "http://" + longUrl;
    }
    return longUrl;
}

function getShortUrl(reqLongUrl) {
    var longUrl = enrichLongUrl(reqLongUrl);
    if (longToShortMap.has(longUrl)) {
        var shortUrlInNumber = longToShortMap.get(longUrl);
        shortUrl = ConvertTo62(shortUrlInNumber);
    } else {
        var size = longToShortMap.size;
        shortUrl = ConvertTo62(size);
        longToShortMap.set(longUrl, size);
        shortToLongMap.set(size, longUrl);
    }
    return shortUrl;
}

function getLongUrl(shortUrl) {
    var shortUrlInNumber = ConvertToInt(shortUrl);
    if (shortToLongMap.has(shortUrlInNumber)) {
        return shortToLongMap.get(shortUrlInNumber);
    } else {
        return null;
    }
}

module.exports = {
    getShortUrl: getShortUrl,
    getLongUrl: getLongUrl
};<commit_msg>Improved ConvertTo62 implementation<commit_after>var longToShortMap = new Map();
var shortToLongMap = new Map();

var genCharArray = function (charA, charZ) {
    var arr = [];
    var i = charA.charCodeAt(0);
    var j = charZ.charCodeAt(0);

    for (var k = i; k <= j; k++) {
        arr.push(String.fromCharCode(k));
    }

    return arr;
};

var encode = function () {
    var encodeArr = [];
    encodeArr = encodeArr.concat(genCharArray('0', '9'));
    encodeArr = encodeArr.concat(genCharArray('A', 'Z'));
    encodeArr = encodeArr.concat(genCharArray('a', 'z'));
    return encodeArr;
}();

function ConvertTo62(num) {
    var result = '';
    do {
        result = encode[num % 62] + result;
        num = Math.floor(num / 62);
    } while (num > 0);

    return result;
}

function ConvertToInt(shortUrl) {
    var length = shortUrl.length;
    var shortUrlInNumber = 0;
    for (var i = 0; i < length; i++) {
        var encodingLength = encode.length;
        var c = shortUrl.charAt(i);
        var index = encode.indexOf(c);
        shortUrlInNumber += index * Math.pow(encodingLength, length-i-1);
    }
    return shortUrlInNumber;
}

function enrichLongUrl(longUrl) {
    if (longUrl.indexOf('http') === -1) {
        longUrl = "http://" + longUrl;
    }
    return longUrl;
}

function getShortUrl(reqLongUrl) {
    var longUrl = enrichLongUrl(reqLongUrl);
    var shortUrl = "";
    if (longToShortMap.has(longUrl)) {
        var shortUrlInNumber = longToShortMap.get(longUrl);
        shortUrl = ConvertTo62(shortUrlInNumber);
    } else {
        var size = longToShortMap.size;
        shortUrl = ConvertTo62(size);
        longToShortMap.set(longUrl, size);
        shortToLongMap.set(size, longUrl);
    }
    return shortUrl;
}

function getLongUrl(shortUrl) {
    var shortUrlInNumber = ConvertToInt(shortUrl);
    if (shortToLongMap.has(shortUrlInNumber)) {
        return shortToLongMap.get(shortUrlInNumber);
    } else {
        return null;
    }
}

module.exports = {
    getShortUrl: getShortUrl,
    getLongUrl: getLongUrl
};<|endoftext|>


<commit_before>"use strict";
let fs = require('fs');
let options = require('commander');
let Compiler = require('angular-gettext-tools').Compiler;

function main(inputs) {
  let compiler = new Compiler({format: 'json'});

  let contents = [];
  inputs.forEach(function(input) {
    // ignore un existing files
    fs.exists(input, function(exists) {
      if (exists) {
        fs.readFile(input, {encoding: 'utf-8'}, function(err, content) {
          if (!err) {
            contents.push(content);
            if (contents.length === inputs.length) {
              process.stdout.write(compiler.convertPo(contents.filter(function (content) {
                return content.length !== 0;
              })));
            }
          }
        });
      }
      else {
        contents.push("")
      }
    });
  });
}

// If running this module directly then call the main function.
if (require.main === module) {
  options.parse(process.argv);
  main(options.args);
}

module.exports = main;
<commit_msg>Compile the the po files in order<commit_after>"use strict";
const fs = require('fs');
const options = require('commander');
const Compiler = require('angular-gettext-tools').Compiler;

function main(inputs) {
  const compiler = new Compiler({format: 'json'});

  const promises = [];
  inputs.forEach((input) => {
    promises.push(new Promise((resolve) => {
      fs.readFile(input, 'utf-8', (error, content) => {
        resolve(error ? undefined : content);
      });
    }));
  });

  Promise.all(promises).then((contents) => {
    contents = contents.filter(content => content !== undefined);
    process.stdout.write(compiler.convertPo(contents));
  });
}

// If running this module directly then call the main function.
if (require.main === module) {
  options.parse(process.argv);
  main(options.args);
}

module.exports = main;
<|endoftext|>


<commit_before>/**
 * @preserve EventEmitter v3.0.0
 *
 * Copyright 2011, Oliver Caldwell (olivercaldwell.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/EventEmitter
 */

function EventEmitter() {

}<commit_msg>Added the Event class<commit_after>/**
 * @preserve EventEmitter v3.0.0
 *
 * Copyright 2011, Oliver Caldwell (olivercaldwell.co.uk)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * https://github.com/Wolfy87/EventEmitter
 */

function EventEmitter() {
	// Initialise variables
	var listeners = {},
		instance = this;

	/**
	 * Event class
	 * Contains Event methods and property storage
	 */
	instance.Event = function(type, listener, scope) {
		// Initialise variables
		var instance = this;

		// Store arguments
		instance.type = type;
		instance.listener = listener;

		/**
		 * Executes the listener
		 */
		instance.fire = function(args) {
			this.listener.apply(scope || this, args);
		};
	};
}<|endoftext|>


<commit_before>class UserService {
    mapAsUser(user) {
        return {
            login: user.login,
            avatar_url: user.avatar_url,
            html_url: user.html_url,
            name: user.name,
            bio: user.bio,
            followers: user.followers,
            following: user.following,
            created_at: user.created_at,
            updated_at: user.updated_at,
            repositories: []
        };
    }
}<commit_msg>refactor(UserService): add type field in user mapping<commit_after>class UserService {
    mapAsUser(user) {
        return {
            login: user.login,
            avatar_url: user.avatar_url,
            html_url: user.html_url,
            name: user.name,
            bio: user.bio,
            type: user.type,
            followers: user.followers,
            following: user.following,
            created_at: user.created_at,
            updated_at: user.updated_at,
            repositories: []
        };
    }
}<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var request = require('request');
var config = require("../../config");
var wolfram = require('node-wolfram');

wolfram = new wolfram(config.WOLFRAM_KEY);

var shouldFilterOutTitle = function(title) {
  return title === 'Response' ||
         title === 'Result';
}

var formatResult = function(result) {
	if (!result.queryresult.pod) return '';
  for (var a = 0; a < result.queryresult.pod.length; a++) {
    var pod = result.queryresult.pod[a];
    if (pod &&
        pod.$.title != "Input" &&
        pod.$.title != "Input interpretation" &&
        pod.$.title != "Plot" &&
        pod.subpod.length &&
        pod.subpod[0] &&
        pod.subpod[0].plaintext.length) {
      var title   = pod.$.title;
      var answer  = pod.subpod[0].plaintext[0];

      // Some title don't make sense to add. Filter them out there.
      var resultString = shouldFilterOutTitle(title) ? answer : title + ':\n' + answer;
      resultString.replace("Wolfram|Alpha", "Kanye");
    }
  }
  return '';
};

var getWolframResult = function(userQuery, callback) {
  wolfram.query(userQuery, function(err, result) {
    if (err) {
      return '';
    }

    if (result.queryresult &&
        !result.queryresult.didyoumeans) {
      var outgoingMessage = formatResult(result);
      callback(outgoingMessage);
    } else {
      var newQuery = result.queryresult.didyoumeans[0].didyoumean[0]._;
      getWolframResult(newQuery, callback);
    }
  });
}

// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
  var userQuery = req.query.message;

  getWolframResult(userQuery, function(result) {
    if (result === '') {
      res.status(200).json({ message: 'Sorry, I don\'t have an answer for that.' });
    } else {
      res.status(200).json({ message: result });
    }
  });
});

app.listen(4000);
<commit_msg>Fix bug<commit_after>var express = require('express');
var app = express();
var request = require('request');
var config = require("../../config");
var wolfram = require('node-wolfram');

wolfram = new wolfram(config.WOLFRAM_KEY);

var shouldFilterOutTitle = function(title) {
  return title === 'Response' ||
         title === 'Result';
}

var formatResult = function(result) {
	if (!result.queryresult.pod) return '';
  for (var a = 0; a < result.queryresult.pod.length; a++) {
    var pod = result.queryresult.pod[a];
    if (pod &&
        pod.$.title != "Input" &&
        pod.$.title != "Input interpretation" &&
        pod.$.title != "Plot" &&
        pod.subpod.length &&
        pod.subpod[0] &&
        pod.subpod[0].plaintext.length) {
      var title   = pod.$.title;
      var answer  = pod.subpod[0].plaintext[0];

      // Some title don't make sense to add. Filter them out there.
      var resultString = shouldFilterOutTitle(title) ? answer : title + ':\n' + answer;
      resultString.replace("Wolfram|Alpha", "Kanye");
      return resultString;
    }
  }
  return '';
};

var getWolframResult = function(userQuery, callback) {
  wolfram.query(userQuery, function(err, result) {
    if (err) {
      return '';
    }

    if (result.queryresult &&
        !result.queryresult.didyoumeans) {
      var outgoingMessage = formatResult(result);
      callback(outgoingMessage);
    } else {
      var newQuery = result.queryresult.didyoumeans[0].didyoumean[0]._;
      getWolframResult(newQuery, callback);
    }
  });
}

// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
  var userQuery = req.query.message;

  getWolframResult(userQuery, function(result) {
    if (result === '') {
      res.status(200).json({ message: 'Sorry, I don\'t have an answer for that.' });
    } else {
      res.status(200).json({ message: result });
    }
  });
});

app.listen(4000);
<|endoftext|>


<commit_before>import util from 'util'
import dns from 'dns'
import uuid from 'uuid'
import zmq from 'zmq'
import { isString, isInteger, isArray, every } from 'lodash'
import EventEmitter from 'eventemitter3'

import { EXTERNAL_NODE } from './NodeTypes'

import { nodeIdToName, prefixString, debugLog, zeropad } from './utils'

const HEARTBEAT_INTERVAL_CHECK = 400
const HEARTBEAT_TIMEOUT = 1500
const ctorMessage = prefixString('[ExternalNode constructor]: ')
const invariantMessage = prefixString('[ExternalNode Invariant]: ')

let defaultSettings = {
  debug: false,
  externalUpdatesPort: 50081
}

function ExternalNode (host, _settings) {
  let instance = this instanceof ExternalNode
  if (!instance) return new ExternalNode(host, _settings)

  let node = this

  // Settings
  let settings = Object.assign({}, defaultSettings, _settings)
  let {
    debug,
    externalUpdatesPort
  } = settings

  // Settings validation
  if (!host || !isString(host)) throw new TypeError(ctorMessage('host is mandatory and should be a string.'))
  if (!isInteger(externalUpdatesPort) || externalUpdatesPort <= 0) throw new TypeError(ctorMessage('settings.externalUpdatesPort should be a positive integer.'))

  // Emitter inheritance
  EventEmitter.call(this)

  // Private API
  let _id = uuid.v4()
  let _name = nodeIdToName(_id)
  let _connected = false
  let _seeking = false
  let _connectedMaster = {}
  let _checkHearbeatInterval
  let _lastHeartbeatReceivedTime = 0
  let _subscribedChannels = []
  let _intPub
  let _intSub
  let _checkHeartbeat = () => {
    let passedTime = Date.now() - _lastHeartbeatReceivedTime
    if (passedTime > HEARTBEAT_TIMEOUT) {
      node.debug('Missing master...')
      _seekForMaster()
    }
  }
  let _seekForMaster = () => {
    if (_seeking) return
    _seeking = true
    dns.resolve4(host, (err, addresses) => {
      if (err) return
      let _updating = zmq.socket('sub')
      _updating.subscribe('heartbeats')
      _updating.on('message', (channelBuffer, ...argsBuffers) => {
        _seeking = false
        let args = argsBuffers.map(buffer => buffer.toString())
        let master = JSON.parse(args[0])
        _connectedMaster = master
        _connectToMaster()
        _updating.close()
      })

      addresses.forEach(address => {
        _updating.connect(`tcp://${address}:${settings.externalUpdatesPort}`)
      })
    })
  }
  let _connectToMaster = () => {
    let _newIntPub = zmq.socket('pub')
    let _newIntSub = zmq.socket('sub')

    let connections = 0
    function attemptTransitionToConnected () {
      if (!_connected && connections === 2) {
        _connected = true
        node.emit('connect')
      }
    }

    node.debug('Connecting to new master: ', nodeIdToName(_connectedMaster.id))
    _lastHeartbeatReceivedTime = Date.now()

    _newIntPub.monitor()
    _newIntPub.on('connect', () => {
      _newIntPub.unmonitor()
      if (_intPub) _intPub.close()
      _intPub = _newIntPub
      connections++
      attemptTransitionToConnected()
    })
    _newIntPub.connect(_connectedMaster.endpoints.sub)

    _newIntSub.monitor()
    _newIntSub.on('connect', () => {
      _newIntSub.unmonitor()
      if (_intSub) _intSub.close()
      _intSub = _newIntSub
      connections++
      attemptTransitionToConnected()
    })
    _newIntSub.subscribe('heartbeats')
    _subscribedChannels.forEach(channel => _newIntSub.subscribe(channel))
    _newIntSub.connect(_connectedMaster.endpoints.pub)
    _newIntSub.on('message', (channelBuffer, ...argsBuffers) => {
      let channel = channelBuffer.toString()
      let args = argsBuffers.map(buffer => buffer.toString())

      if (channel === 'heartbeats') {
        let master = JSON.parse(args[0])
        if (_connectedMaster.id === master.id) {
          _lastHeartbeatReceivedTime = Date.now()
        } else {
          _connectedMaster = master
          _connectToMaster()
        }
        return
      }
      node.emit(channel, ...args)
    })
  }

  // Public API
  function connect () {
    node.debug('Connecting...')
    _checkHearbeatInterval = setInterval(_checkHeartbeat, HEARTBEAT_INTERVAL_CHECK)
  }
  function disconnect () {
    node.debug('Disconnecting...')
    clearInterval(_checkHearbeatInterval)
    if (_intPub) _intPub.close()
    if (_intSub) _intSub.close()

    _intPub = null
    _intSub = null
    node.emit('disconnect')
  }
  function publish (channel, ...args) {
    if (channel === 'heartbeats') return
    if (_intPub) {
      _intPub.send([channel, ...args])
    }
  }
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(invariantMessage('subscribe channels must be represented by strings'))

    channels.forEach(channel => {
      if (_intSub) _intSub.subscribe(channel)
      if (!~_subscribedChannels.indexOf(channel)) {
        _subscribedChannels.push(channel)
      }
    })
  }
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(invariantMessage('subscribe channels must be represented by strings'))

    channels.forEach(channel => {
      if (_intSub) _intSub.unsubscribe(channel)
      let index = _subscribedChannels.indexOf(channel)
      if (index >= 0) {
        _subscribedChannels.splice(index, 1)
      }
    })
  }

  //  Debug
  node.debug = debugLog(`[External Node ${_name}]: `, debug)

  // Instance decoration
  Object.defineProperty(node, 'id', {
    get: () => _id,
    set: () => console.warn(invariantMessage('You cannot change the .id of a dnsNode instance'))
  })
  Object.defineProperty(node, 'name', {
    get: () => _name,
    set: () => console.warn(invariantMessage('You cannot change the .name of a dnsNode instance'))
  })
  Object.defineProperty(node, 'type', {
    get: () => EXTERNAL_NODE,
    set: () => console.warn(invariantMessage('You cannot change the .type of a dnsNode instance'))
  })
  Object.defineProperty(node, 'connected', {
    get: () => _connected,
    set: () => console.warn(invariantMessage('You cannot manually change the .connected status of a dnsNode instance'))
  })
  Object.defineProperty(node, 'master', {
    get: () => _connectedMaster,
    set: () => console.warn(invariantMessage('You cannot manually change the .master reference of a dnsNode instance'))
  })
  Object.assign(node, {
    connect,
    disconnect,
    publish,
    subscribe,
    unsubscribe
  })
}

util.inherits(ExternalNode, EventEmitter)

export default ExternalNode
<commit_msg>ExternalNode id starts with `EX-`<commit_after>import util from 'util'
import dns from 'dns'
import uuid from 'uuid'
import zmq from 'zmq'
import { isString, isInteger, isArray, every } from 'lodash'
import EventEmitter from 'eventemitter3'

import { EXTERNAL_NODE } from './NodeTypes'

import { nodeIdToName, prefixString, debugLog, zeropad } from './utils'

const HEARTBEAT_INTERVAL_CHECK = 400
const HEARTBEAT_TIMEOUT = 1500
const ctorMessage = prefixString('[ExternalNode constructor]: ')
const invariantMessage = prefixString('[ExternalNode Invariant]: ')

let defaultSettings = {
  debug: false,
  externalUpdatesPort: 50081
}

function ExternalNode (host, _settings) {
  let instance = this instanceof ExternalNode
  if (!instance) return new ExternalNode(host, _settings)

  let node = this

  // Settings
  let settings = Object.assign({}, defaultSettings, _settings)
  let {
    debug,
    externalUpdatesPort
  } = settings

  // Settings validation
  if (!host || !isString(host)) throw new TypeError(ctorMessage('host is mandatory and should be a string.'))
  if (!isInteger(externalUpdatesPort) || externalUpdatesPort <= 0) throw new TypeError(ctorMessage('settings.externalUpdatesPort should be a positive integer.'))

  // Emitter inheritance
  EventEmitter.call(this)

  // Private API
  let _id = `EX-${uuid.v4()}`
  let _name = nodeIdToName(_id)
  let _connected = false
  let _seeking = false
  let _connectedMaster = {}
  let _checkHearbeatInterval
  let _lastHeartbeatReceivedTime = 0
  let _subscribedChannels = []
  let _intPub
  let _intSub
  let _checkHeartbeat = () => {
    let passedTime = Date.now() - _lastHeartbeatReceivedTime
    if (passedTime > HEARTBEAT_TIMEOUT) {
      node.debug('Missing master...')
      _seekForMaster()
    }
  }
  let _seekForMaster = () => {
    if (_seeking) return
    _seeking = true
    dns.resolve4(host, (err, addresses) => {
      if (err) return
      let _updating = zmq.socket('sub')
      _updating.subscribe('heartbeats')
      _updating.on('message', (channelBuffer, ...argsBuffers) => {
        _seeking = false
        let args = argsBuffers.map(buffer => buffer.toString())
        let master = JSON.parse(args[0])
        _connectedMaster = master
        _connectToMaster()
        _updating.close()
      })

      addresses.forEach(address => {
        _updating.connect(`tcp://${address}:${settings.externalUpdatesPort}`)
      })
    })
  }
  let _connectToMaster = () => {
    let _newIntPub = zmq.socket('pub')
    let _newIntSub = zmq.socket('sub')

    let connections = 0
    function attemptTransitionToConnected () {
      if (!_connected && connections === 2) {
        _connected = true
        node.emit('connect')
      }
    }

    node.debug('Connecting to new master: ', nodeIdToName(_connectedMaster.id))
    _lastHeartbeatReceivedTime = Date.now()

    _newIntPub.monitor()
    _newIntPub.on('connect', () => {
      _newIntPub.unmonitor()
      if (_intPub) _intPub.close()
      _intPub = _newIntPub
      connections++
      attemptTransitionToConnected()
    })
    _newIntPub.connect(_connectedMaster.endpoints.sub)

    _newIntSub.monitor()
    _newIntSub.on('connect', () => {
      _newIntSub.unmonitor()
      if (_intSub) _intSub.close()
      _intSub = _newIntSub
      connections++
      attemptTransitionToConnected()
    })
    _newIntSub.subscribe('heartbeats')
    _subscribedChannels.forEach(channel => _newIntSub.subscribe(channel))
    _newIntSub.connect(_connectedMaster.endpoints.pub)
    _newIntSub.on('message', (channelBuffer, ...argsBuffers) => {
      let channel = channelBuffer.toString()
      let args = argsBuffers.map(buffer => buffer.toString())

      if (channel === 'heartbeats') {
        let master = JSON.parse(args[0])
        if (_connectedMaster.id === master.id) {
          _lastHeartbeatReceivedTime = Date.now()
        } else {
          _connectedMaster = master
          _connectToMaster()
        }
        return
      }
      node.emit(channel, ...args)
    })
  }

  // Public API
  function connect () {
    node.debug('Connecting...')
    _checkHearbeatInterval = setInterval(_checkHeartbeat, HEARTBEAT_INTERVAL_CHECK)
  }
  function disconnect () {
    node.debug('Disconnecting...')
    clearInterval(_checkHearbeatInterval)
    if (_intPub) _intPub.close()
    if (_intSub) _intSub.close()

    _intPub = null
    _intSub = null
    node.emit('disconnect')
  }
  function publish (channel, ...args) {
    if (channel === 'heartbeats') return
    if (_intPub) {
      _intPub.send([channel, ...args])
    }
  }
  function subscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(invariantMessage('subscribe channels must be represented by strings'))

    channels.forEach(channel => {
      if (_intSub) _intSub.subscribe(channel)
      if (!~_subscribedChannels.indexOf(channel)) {
        _subscribedChannels.push(channel)
      }
    })
  }
  function unsubscribe (channels) {
    if (!isArray(channels)) channels = [channels]
    if (!every(channels, isString)) throw new TypeError(invariantMessage('subscribe channels must be represented by strings'))

    channels.forEach(channel => {
      if (_intSub) _intSub.unsubscribe(channel)
      let index = _subscribedChannels.indexOf(channel)
      if (index >= 0) {
        _subscribedChannels.splice(index, 1)
      }
    })
  }

  //  Debug
  node.debug = debugLog(`[External Node ${_name}]: `, debug)

  // Instance decoration
  Object.defineProperty(node, 'id', {
    get: () => _id,
    set: () => console.warn(invariantMessage('You cannot change the .id of a dnsNode instance'))
  })
  Object.defineProperty(node, 'name', {
    get: () => _name,
    set: () => console.warn(invariantMessage('You cannot change the .name of a dnsNode instance'))
  })
  Object.defineProperty(node, 'type', {
    get: () => EXTERNAL_NODE,
    set: () => console.warn(invariantMessage('You cannot change the .type of a dnsNode instance'))
  })
  Object.defineProperty(node, 'connected', {
    get: () => _connected,
    set: () => console.warn(invariantMessage('You cannot manually change the .connected status of a dnsNode instance'))
  })
  Object.defineProperty(node, 'master', {
    get: () => _connectedMaster,
    set: () => console.warn(invariantMessage('You cannot manually change the .master reference of a dnsNode instance'))
  })
  Object.assign(node, {
    connect,
    disconnect,
    publish,
    subscribe,
    unsubscribe
  })
}

util.inherits(ExternalNode, EventEmitter)

export default ExternalNode
<|endoftext|>


<commit_before>let path = require('path');
let webpack = require('webpack');
let Mix = require('laravel-mix').config;
let plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

let vueExtractTextPlugin = false;

if (Mix.options.extractVueStyles) {
    vueExtractTextPlugin = Mix.vueExtractTextPlugin();

    module.exports.plugins = (module.exports.plugins || []).concat(vueExtractTextPlugin);
}

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: Mix.options.extractVueStyles ? {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: vueExtractTextPlugin.extract({
                        use: 'css-loader!sass-loader',
                        fallback: 'vue-style-loader'
                    }),
                    sass: vueExtractTextPlugin.extract({
                        use: 'css-loader!sass-loader?indentedSyntax',
                        fallback: 'vue-style-loader'
                    }),
                    stylus: vueExtractTextPlugin.extract({
                        use: 'css-loader!stylus-loader?paths[]=node_modules',
                        fallback: 'vue-style-loader'
                    }),
                    css: vueExtractTextPlugin.extract({
                        use: 'css-loader',
                        fallback: 'vue-style-loader'
                    })
                }: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
                    stylus: 'vue-style-loader!css-loader!stylus-loader?paths[]=node_modules'
                },

                postcss: Mix.options.postCss
            }
        },

        {
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.css$/,
            loaders: ['style-loader', 'css-loader']
        },

        {
            test: /\.s[ac]ss$/,
            include: /node_modules/,
            loaders: ['style-loader', 'css-loader', 'sass-loader']
        },

        {
            test: /\.html$/,
            loaders: ['html-loader']
        },

        {
            test: /\.(png|jpe?g|gif)$/,
            loader: 'file-loader',
            options: {
                name: path => {
                    if (!/node_modules|bower_components/.test(path)) {
                        return 'images/[name].[ext]?[hash]';
                    }

                    return 'images/vendor/' + path.replace(/\\/g, '/').replace(/((.*(node_modules|bower_components))|images|image|img|assets)\//g, '') + '?[hash]';
                },
                publicPath: Mix.resourceRoot
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: path => {
                    if (!/node_modules|bower_components/.test(path)) {
                        return 'fonts/[name].[ext]?[hash]';
                    }

                    return 'fonts/vendor/' + path.replace(/\\/g, '/').replace(/((.*(node_modules|bower_components))|fonts|font|assets)\//g, '') + '?[hash]';
                },
                publicPath: Mix.resourceRoot
            }
        },

        {
            test: /\.(cur|ani)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]',
                publicPath: Mix.resourceRoot
            }
        }
    ]
};

if (Mix.preprocessors) {
    Mix.preprocessors.forEach(preprocessor => {
        module.exports.module.rules.push(preprocessor.rules());

        module.exports.plugins = (module.exports.plugins || []).concat(preprocessor.extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

process.noDeprecation = true;

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    historyApiFallback: true,
    noInfo: true,
    compress: true,
    quiet: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: 'mix-manifest.json',
        transform: Mix.manifest.transform.bind(Mix.manifest),
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: Mix.options.postCss,
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.browserSync) {
    module.exports.plugins.push(
        new plugins.BrowserSyncPlugin(
            Object.assign({
                host: 'localhost',
                port: 3000,
                proxy: 'app.dev',
                files: [
                    'app/**/*.php',
                    'resources/views/**/*.php',
                    'public/js/**/*.js',
                    'public/css/**/*.css'
                ]
            }, Mix.browserSync),
            {
                reload: false
            }
        )
    );
}

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.extract) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: Mix.entryBuilder.extractions.concat([
                path.join(Mix.js.base, 'manifest').replace(/\\/g, '/')
            ]),
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins.push(
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin(Mix.options.uglify)
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<commit_msg>Add the auto setting of webpack dev server contentBase to example webpack.config.js<commit_after>let path = require('path');
let webpack = require('webpack');
let Mix = require('laravel-mix').config;
let plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

let vueExtractTextPlugin = false;

if (Mix.options.extractVueStyles) {
    vueExtractTextPlugin = Mix.vueExtractTextPlugin();

    module.exports.plugins = (module.exports.plugins || []).concat(vueExtractTextPlugin);
}

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: Mix.options.extractVueStyles ? {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: vueExtractTextPlugin.extract({
                        use: 'css-loader!sass-loader',
                        fallback: 'vue-style-loader'
                    }),
                    sass: vueExtractTextPlugin.extract({
                        use: 'css-loader!sass-loader?indentedSyntax',
                        fallback: 'vue-style-loader'
                    }),
                    stylus: vueExtractTextPlugin.extract({
                        use: 'css-loader!stylus-loader?paths[]=node_modules',
                        fallback: 'vue-style-loader'
                    }),
                    css: vueExtractTextPlugin.extract({
                        use: 'css-loader',
                        fallback: 'vue-style-loader'
                    })
                }: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
                    stylus: 'vue-style-loader!css-loader!stylus-loader?paths[]=node_modules'
                },

                postcss: Mix.options.postCss
            }
        },

        {
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.css$/,
            loaders: ['style-loader', 'css-loader']
        },

        {
            test: /\.s[ac]ss$/,
            include: /node_modules/,
            loaders: ['style-loader', 'css-loader', 'sass-loader']
        },

        {
            test: /\.html$/,
            loaders: ['html-loader']
        },

        {
            test: /\.(png|jpe?g|gif)$/,
            loader: 'file-loader',
            options: {
                name: path => {
                    if (!/node_modules|bower_components/.test(path)) {
                        return 'images/[name].[ext]?[hash]';
                    }

                    return 'images/vendor/' + path.replace(/\\/g, '/').replace(/((.*(node_modules|bower_components))|images|image|img|assets)\//g, '') + '?[hash]';
                },
                publicPath: Mix.resourceRoot
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: path => {
                    if (!/node_modules|bower_components/.test(path)) {
                        return 'fonts/[name].[ext]?[hash]';
                    }

                    return 'fonts/vendor/' + path.replace(/\\/g, '/').replace(/((.*(node_modules|bower_components))|fonts|font|assets)\//g, '') + '?[hash]';
                },
                publicPath: Mix.resourceRoot
            }
        },

        {
            test: /\.(cur|ani)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[ext]?[hash]',
                publicPath: Mix.resourceRoot
            }
        }
    ]
};

if (Mix.preprocessors) {
    Mix.preprocessors.forEach(preprocessor => {
        module.exports.module.rules.push(preprocessor.rules());

        module.exports.plugins = (module.exports.plugins || []).concat(preprocessor.extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

process.noDeprecation = true;

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    contentBase: (Mix.publicPath + '/').replace(/\/{2,}/g, '/'),
    historyApiFallback: true,
    noInfo: true,
    compress: true,
    quiet: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: 'mix-manifest.json',
        transform: Mix.manifest.transform.bind(Mix.manifest),
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: Mix.options.postCss,
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.browserSync) {
    module.exports.plugins.push(
        new plugins.BrowserSyncPlugin(
            Object.assign({
                host: 'localhost',
                port: 3000,
                proxy: 'app.dev',
                files: [
                    'app/**/*.php',
                    'resources/views/**/*.php',
                    'public/js/**/*.js',
                    'public/css/**/*.css'
                ]
            }, Mix.browserSync),
            {
                reload: false
            }
        )
    );
}

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.extract) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: Mix.entryBuilder.extractions.concat([
                path.join(Mix.js.base, 'manifest').replace(/\\/g, '/')
            ]),
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins.push(
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin(Mix.options.uglify)
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<|endoftext|>