<commit_before>
/** Note: This file doesn't contain any unit tests. It has utility functions and
 * logic for performing common things required in unit tests. An example is
 * creating a level and adding a list of actors automatically there.
 */

const RG = require('../client/src/battles');
const expect = require('chai').expect;
const Screen = require('../client/gui/screen');

const RGTest = {};

RGTest.rng = new RG.Random();

/* Creates a mock-level for unit tests. */
RGTest.createMockLevel = function(cols, rows) {
    const level = {cols: cols, rows: rows,
        map: {
            getCell: function(x, y) {
                return { x: x, y: y };
            },
            hasXY: function() {
                return true;
            },
            isPassable: function(x, y) {
                return x > -1 && y > -1;
            }
        },
        getMap: function() {return this.map;},

        addActor: function(actor, x, y) {
            actor.setXY(x, y);
            actor.setLevel(this);
        }
    };
    return level;
};

RGTest.createLevel = function(type, cols, rows) {
    return RG.FACT.createLevel('arena', cols, rows);
};

RGTest.equipItem = function(actor, item) {
    const invEq = actor.getInvEq();
    invEq.addItem(item);
    expect(invEq.equipItem(item)).to.equal(true);
};

/* Wraps an object into a cell for later use. Some functions require a map cell
* instead of taking the object directly, so this is useful. */
RGTest.wrapObjWithCell = function(obj) {
    const cell = RG.FACT.createFloorCell();
    cell.setExplored(true); // Otherwise returns darkness
    const propType = obj.getPropType();
    cell.setProp(propType, obj);
    return cell;
};

RGTest.getMeAWizard = function(conf = {}) {
    const wizard = new RG.Actor.Rogue('wizard');
    wizard.setType(conf.type || 'human');
    const brain = new RG.Brain.SpellCaster(wizard);
    wizard.setBrain(brain);

    wizard._spellbook = new RG.Spell.SpellBook(wizard);
    const spell = RG.FACT.createSpell('FrostBolt');
    spell.setPower(conf.power || 11);
    spell.setRange(conf.range || 7);
    spell.setDice([RG.FACT.createDie([1, 2, 3])]);
    wizard._spellbook.addSpell(spell);

    // Adjust evaluators and casting probability
    RGTest.ensureSpellCast(wizard);

    const spellPower = new RG.Component.SpellPower();
    spellPower.setPP(30);
    spellPower.setMaxPP(40);
    wizard.add('SpellPower', spellPower);
    return wizard;

};

RGTest.ensureSpellCast = function(actor) {
    const goal = actor.getBrain().getGoal();
    goal.setBias({CastSpell: 2.0, AttackActor: 0.3});
    goal.getEvaluator('CastSpell').setCastingProbability(1.0);
};

RGTest.checkActorXY = function(actor, x, y) {
    expect(actor.getX(), `X must be ${x}`).to.equal(x);
    expect(actor.getY(), `Y must be ${y}`).to.equal(y);
};

RGTest.checkChar = function(obj, expChar) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getCellChar(cell)).to.equal(expChar);
};

RGTest.checkCSSClassName = function(obj, expClass) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getStyleClassForCell(cell)).to.equal(expClass);

};

RGTest.expectEqualHealth = function(o1, o2) {
    expect(o1.get('Health').getHP()).to.equal(o2.get('Health').getHP());
};

RGTest.verifyStairsConnectivity = function(stairs, numExp = -1) {
    let connVerified = 0;
    stairs.forEach(s => {
        expect(s.getTargetStairs()).not.to.be.empty;
        expect(s.getTargetLevel()).not.to.be.empty;
        expect(s.getSrcLevel()).not.to.be.empty;
        ++connVerified;
    });
    if (numExp >= 0) {
        expect(connVerified, `Exp ${numExp} conns`).to.equal(numExp);
    }
    else {
        expect(connVerified, 'At least one conn verified').to.be.above(0);
    }
};

/* Verifies that all given stairs in the array are connected. On failure, prints
 * the optional error msg. */
RGTest.verifyConnectivity = function(stairs, msg = '') {
    let connVerified = 0;
    stairs.forEach(s => {
        let str = `${msg} x, y: ${s.getX()}, ${s.getY()} `;
        str += JSON.stringify(s);
        expect(s.getTargetStairs(), str + ' targetStairs').to.exist;
        expect(s.getTargetLevel(), str + ' targetLevel').to.exist;
        expect(s.getSrcLevel(), str + ' srcLevel').to.exist;
        ++connVerified;
    });
    expect(connVerified, 'At least one connection exists').to.be.above(0);
};

// Expect that subzones b1 and b2 are connected by number of connections
// given by nConns.
RGTest.expectConnected = function(b1, b2, nConns) {
    let connFound = 0;
    const b1Stairs = b1.getStairsOther();
    const b2Stairs = b2.getStairsOther();
    expect(b1Stairs, 'B1 must have stairs').to.have.length.above(0);
    expect(b2Stairs, 'B2 must have stairs').to.have.length.above(0);

    b1Stairs.forEach(stair1 => {
        const s1TargetID = stair1.getTargetLevel().getID();
        expect(stair1.getTargetStairs()).not.to.be.empty;
        b2Stairs.forEach(stair2 => {
            const s2SourceID = stair2.getSrcLevel().getID();
            if (s1TargetID === s2SourceID) {
                // stair1 should be the target of stair2
                if (stair2.getTargetStairs() === stair1) {
                    ++connFound;
                }
                expect(stair2.getTargetStairs()).not.to.be.empty;
            }
        });
    });
    expect(connFound, `Connections between branches must be ${nConns}`)
        .to.equal(nConns);
};

/* Adds each entity into the level into a random location. */
RGTest.wrapIntoLevel = function(arr) {
    const level = RG.FACT.createLevel('empty', 20, 20);
    arr.forEach(ent => {
        const x = RGTest.rng.getUniformInt(0, 19);
        const y = RGTest.rng.getUniformInt(0, 19);
        if (ent.getPropType() === RG.TYPE_ACTOR) {
            level.addActor(ent, x, y);
        }
        if (ent.getPropType() === RG.TYPE_ITEM) {
            level.addItem(ent, x, y);
        }
    });
    return level;
};

/* Moves entity from its current position to x,y. */
RGTest.moveEntityTo = function(ent, x, y) {
    const map = ent.getLevel().getMap();
    const xOld = ent.getX();
    const yOld = ent.getY();
    const propType = ent.getPropType();
    if (map.removeProp(xOld, yOld, propType, ent)) {
        map.setProp(x, y, propType, ent);
        ent.setXY(x, y);
        return true;
    }
    throw new Error(`Cannot move entity to ${x}, ${y}`);
};

/* Equips all given items for the given actor, and checks that everything
 * succeeds. */
RGTest.equipItems = function(ent, items) {
    const inv = ent.getInvEq();
    items.forEach(item => {
        inv.addItem(item);
        if (!inv.equipItem(item)) {
            throw new Error(`Cannot equip item ${item}`);
        }
    });
};

/* Can be used to catch the emitted game messages. */
RGTest.MsgCatcher = function() {
    this.filters = [];

    this.hasNotify = true;
    this.enabled = true;
    this.notify = (evtName, msgObj) => {
        if (!this.enabled) {return;}

        const {msg, cell} = msgObj;
        let hasMatch = false;

        if (this.filters.length > 0) {
            this.filters.forEach(filter => {
                if (filter.test(msg)) {
                    hasMatch = true;
                }
            });
        }
        else {
            hasMatch = true;
        }

        if (hasMatch) {
            console.log('\tMsg: |' + msg + '|');
        }
        if (cell) {
            console.log('\tFrom cell: |' + JSON.stringify(cell) + '|');
        }
    };

    RG.POOL.listenEvent(RG.EVT_MSG, this);

    /* Adds a message filter to select which messages to print. */
    this.addFilter = filter => {
        if (typeof filter === 'string') {
            this.filters.push(new RegExp(filter));
        }
        else {
            this.filters.push(filter);
        }

    };

    this.disable = () => {this.enabled = false;};
};

RGTest.createBoundGem = function() {
    const gem = new RG.Item.SpiritGem('Great gem');
    const spirit = new RG.Actor.Spirit('Legend spirit');
    spirit.get('Stats').setStrength(100);
    spirit.get('Stats').setAgility(100);
    gem.setSpirit(spirit);
    return gem;
};

RGTest.printScreen = function(actor) {
    const screen = new Screen(30, 14);
    const visible = actor.getBrain().getSeenCells();
    const map = actor.getLevel().getMap();
    actor.getLevel().exploreCells(actor);
    const [pX, pY] = actor.getXY();
    screen.render(pX, pY, map, visible);
    screen.printRenderedChars();
};

/* A function to run game simulation using a list of actors and a list of
 * systems. */
RGTest.updateGame = (actors, systems, nTurns = 1, cb) => {
    let simActors = actors;
    if (!Array.isArray(actors)) {
        simActors = [actors];
    }
    for (let i = 0; i < nTurns; i++) {
        simActors.forEach(actor => {
            const action = actor.nextAction();
            action.doAction();
            systems.forEach(sys => {sys.update();});
        });
        if (typeof cb === 'function') {
            cb();
        }
    }
};

/* Prints the given level as ASCII. */
RGTest.printLevel = level => {
    const [cols, rows] = [level.getMap().cols, level.getMap().rows];
    const screen = new Screen(cols / 2, rows / 2);
    level.getMap()._optimizeForRowAccess();
    screen.renderFullMap(level.getMap());
    screen.printRenderedChars();
};

RGTest.updateSystems = systems => {
    for (let i = 0; i < systems.length; i++) {
        systems[i].update();
    }
};

RGTest.enablePrint = true;

RGTest.printMemUsage = msg => {
    const used = process.memoryUsage().heapUsed / 1024 / 1024;
    const usedMb = Math.round(used * 100) / 100;
    if (RGTest.enablePrint) {
        console.log(`${msg} The script uses approximately ${usedMb} MB`);
    }
};

/* Can be used to destroy items during testing. */
RGTest.ItemDestroyer = function(pool) {

    this.numCalls = 0;
    this.numDestroyed = 0;

    this.hasNotify = true;
    this.notify = (evtName, obj) => {
        if (evtName === RG.EVT_DESTROY_ITEM) {
            const item = obj.item;
            const owner = item.getOwner().getOwner();
            ++this.numCalls;
            if (owner.getInvEq().removeItem(item)) {
                ++this.numDestroyed;
            }
        }
    };
    pool.listenEvent(RG.EVT_DESTROY_ITEM, this);
};

RGTest.ObjToString = function() {
    const stack = [];
    let msg = '';

    this.toString = (obj, maxStack = 10) => {
        for (const prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                stack.push(prop);
                if (stack.length < maxStack) {
                    if (typeof obj[prop] === 'object') {
                        this.toString(obj[prop], maxStack - 1);
                    }
                    else if (typeof obj[prop] === 'function') {
                        // msg += `Func in ${JSON.stringify(stack)}`;
                        msg += `\n\tFunction: ${prop}`;
                        // msg += `\n\tValue: ${obj[prop].toString()}`;
                    }
                    else if (obj[prop].toString) {
                        msg += obj[prop].toString();
                    }
                    else {
                        msg += obj[prop];
                    }
                }
                stack.pop();
            }
        }
    };

    this.getMsg = () => msg;
};

RGTest.elemString = function(elem, depth = 5) {
    const objToStr = new RGTest.ObjToString();
    objToStr.toString(elem, depth);
    return objToStr.getMsg();
};

RGTest.addOnTop = function(toAdd, locObj) {
    const [x, y] = [locObj.getX(), locObj.getY()];
    if (toAdd.getLevel().getID() === locObj.getLevel().getID()) {
        RGTest.moveEntityTo(toAdd, x, y);
    }
    else {
        RG.err('RGTest', 'addOnTop',
            'Does not work on objects on different levels yet');
    }
};

module.exports = RGTest;
<commit_msg>Added moveActorTo().<commit_after>
/** Note: This file doesn't contain any unit tests. It has utility functions and
 * logic for performing common things required in unit tests. An example is
 * creating a level and adding a list of actors automatically there.
 */

const RG = require('../client/src/battles');
const expect = require('chai').expect;
const Screen = require('../client/gui/screen');

const RGTest = {};

RGTest.rng = new RG.Random();

/* Creates a mock-level for unit tests. */
RGTest.createMockLevel = function(cols, rows) {
    const level = {cols: cols, rows: rows,
        map: {
            getCell: function(x, y) {
                return { x: x, y: y };
            },
            hasXY: function() {
                return true;
            },
            isPassable: function(x, y) {
                return x > -1 && y > -1;
            }
        },
        getMap: function() {return this.map;},

        addActor: function(actor, x, y) {
            actor.setXY(x, y);
            actor.setLevel(this);
        }
    };
    return level;
};

RGTest.createLevel = function(type, cols, rows) {
    return RG.FACT.createLevel('arena', cols, rows);
};

RGTest.equipItem = function(actor, item) {
    const invEq = actor.getInvEq();
    invEq.addItem(item);
    expect(invEq.equipItem(item)).to.equal(true);
};

/* Wraps an object into a cell for later use. Some functions require a map cell
* instead of taking the object directly, so this is useful. */
RGTest.wrapObjWithCell = function(obj) {
    const cell = RG.FACT.createFloorCell();
    cell.setExplored(true); // Otherwise returns darkness
    const propType = obj.getPropType();
    cell.setProp(propType, obj);
    return cell;
};

RGTest.getMeAWizard = function(conf = {}) {
    const wizard = new RG.Actor.Rogue('wizard');
    wizard.setType(conf.type || 'human');
    const brain = new RG.Brain.SpellCaster(wizard);
    wizard.setBrain(brain);

    wizard._spellbook = new RG.Spell.SpellBook(wizard);
    const spell = RG.FACT.createSpell('FrostBolt');
    spell.setPower(conf.power || 11);
    spell.setRange(conf.range || 7);
    spell.setDice([RG.FACT.createDie([1, 2, 3])]);
    wizard._spellbook.addSpell(spell);

    // Adjust evaluators and casting probability
    RGTest.ensureSpellCast(wizard);

    const spellPower = new RG.Component.SpellPower();
    spellPower.setPP(30);
    spellPower.setMaxPP(40);
    wizard.add('SpellPower', spellPower);
    return wizard;

};

RGTest.ensureSpellCast = function(actor) {
    const goal = actor.getBrain().getGoal();
    goal.setBias({CastSpell: 2.0, AttackActor: 0.3});
    goal.getEvaluator('CastSpell').setCastingProbability(1.0);
};

RGTest.checkActorXY = function(actor, x, y) {
    expect(actor.getX(), `X must be ${x}`).to.equal(x);
    expect(actor.getY(), `Y must be ${y}`).to.equal(y);
};

RGTest.checkChar = function(obj, expChar) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getCellChar(cell)).to.equal(expChar);
};

RGTest.checkCSSClassName = function(obj, expClass) {
    const cell = RGTest.wrapObjWithCell(obj);
    expect(RG.getStyleClassForCell(cell)).to.equal(expClass);

};

RGTest.expectEqualHealth = function(o1, o2) {
    expect(o1.get('Health').getHP()).to.equal(o2.get('Health').getHP());
};

RGTest.verifyStairsConnectivity = function(stairs, numExp = -1) {
    let connVerified = 0;
    stairs.forEach(s => {
        expect(s.getTargetStairs()).not.to.be.empty;
        expect(s.getTargetLevel()).not.to.be.empty;
        expect(s.getSrcLevel()).not.to.be.empty;
        ++connVerified;
    });
    if (numExp >= 0) {
        expect(connVerified, `Exp ${numExp} conns`).to.equal(numExp);
    }
    else {
        expect(connVerified, 'At least one conn verified').to.be.above(0);
    }
};

/* Verifies that all given stairs in the array are connected. On failure, prints
 * the optional error msg. */
RGTest.verifyConnectivity = function(stairs, msg = '') {
    let connVerified = 0;
    stairs.forEach(s => {
        let str = `${msg} x, y: ${s.getX()}, ${s.getY()} `;
        str += JSON.stringify(s);
        expect(s.getTargetStairs(), str + ' targetStairs').to.exist;
        expect(s.getTargetLevel(), str + ' targetLevel').to.exist;
        expect(s.getSrcLevel(), str + ' srcLevel').to.exist;
        ++connVerified;
    });
    expect(connVerified, 'At least one connection exists').to.be.above(0);
};

// Expect that subzones b1 and b2 are connected by number of connections
// given by nConns.
RGTest.expectConnected = function(b1, b2, nConns) {
    let connFound = 0;
    const b1Stairs = b1.getStairsOther();
    const b2Stairs = b2.getStairsOther();
    expect(b1Stairs, 'B1 must have stairs').to.have.length.above(0);
    expect(b2Stairs, 'B2 must have stairs').to.have.length.above(0);

    b1Stairs.forEach(stair1 => {
        const s1TargetID = stair1.getTargetLevel().getID();
        expect(stair1.getTargetStairs()).not.to.be.empty;
        b2Stairs.forEach(stair2 => {
            const s2SourceID = stair2.getSrcLevel().getID();
            if (s1TargetID === s2SourceID) {
                // stair1 should be the target of stair2
                if (stair2.getTargetStairs() === stair1) {
                    ++connFound;
                }
                expect(stair2.getTargetStairs()).not.to.be.empty;
            }
        });
    });
    expect(connFound, `Connections between branches must be ${nConns}`)
        .to.equal(nConns);
};

/* Adds each entity into the level into a random location. */
RGTest.wrapIntoLevel = function(arr) {
    const level = RG.FACT.createLevel('empty', 20, 20);
    arr.forEach(ent => {
        const x = RGTest.rng.getUniformInt(0, 19);
        const y = RGTest.rng.getUniformInt(0, 19);
        if (ent.getPropType() === RG.TYPE_ACTOR) {
            level.addActor(ent, x, y);
        }
        if (ent.getPropType() === RG.TYPE_ITEM) {
            level.addItem(ent, x, y);
        }
    });
    return level;
};

/* Moves entity from its current position to x,y. */
RGTest.moveEntityTo = function(ent, x, y) {
    const level = ent.getLevel();
    if (level.moveActorTo(ent, x, y)) {
        return true;
    }
    throw new Error(`Cannot move entity to ${x}, ${y}`);
};

/* Equips all given items for the given actor, and checks that everything
 * succeeds. */
RGTest.equipItems = function(ent, items) {
    const inv = ent.getInvEq();
    items.forEach(item => {
        inv.addItem(item);
        if (!inv.equipItem(item)) {
            throw new Error(`Cannot equip item ${item}`);
        }
    });
};

/* Can be used to catch the emitted game messages. */
RGTest.MsgCatcher = function() {
    this.filters = [];

    this.hasNotify = true;
    this.enabled = true;
    this.notify = (evtName, msgObj) => {
        if (!this.enabled) {return;}

        const {msg, cell} = msgObj;
        let hasMatch = false;

        if (this.filters.length > 0) {
            this.filters.forEach(filter => {
                if (filter.test(msg)) {
                    hasMatch = true;
                }
            });
        }
        else {
            hasMatch = true;
        }

        if (hasMatch) {
            console.log('\tMsg: |' + msg + '|');
        }
        if (cell) {
            console.log('\tFrom cell: |' + JSON.stringify(cell) + '|');
        }
    };

    RG.POOL.listenEvent(RG.EVT_MSG, this);

    /* Adds a message filter to select which messages to print. */
    this.addFilter = filter => {
        if (typeof filter === 'string') {
            this.filters.push(new RegExp(filter));
        }
        else {
            this.filters.push(filter);
        }

    };

    this.disable = () => {this.enabled = false;};
};

RGTest.createBoundGem = function() {
    const gem = new RG.Item.SpiritGem('Great gem');
    const spirit = new RG.Actor.Spirit('Legend spirit');
    spirit.get('Stats').setStrength(100);
    spirit.get('Stats').setAgility(100);
    gem.setSpirit(spirit);
    return gem;
};

RGTest.printScreen = function(actor) {
    const screen = new Screen(30, 14);
    const visible = actor.getBrain().getSeenCells();
    const map = actor.getLevel().getMap();
    actor.getLevel().exploreCells(actor);
    const [pX, pY] = actor.getXY();
    screen.render(pX, pY, map, visible);
    screen.printRenderedChars();
};

/* A function to run game simulation using a list of actors and a list of
 * systems. */
RGTest.updateGame = (actors, systems, nTurns = 1, cb) => {
    let simActors = actors;
    if (!Array.isArray(actors)) {
        simActors = [actors];
    }
    for (let i = 0; i < nTurns; i++) {
        simActors.forEach(actor => {
            const action = actor.nextAction();
            action.doAction();
            systems.forEach(sys => {sys.update();});
        });
        if (typeof cb === 'function') {
            cb();
        }
    }
};

/* Prints the given level as ASCII. */
RGTest.printLevel = level => {
    const [cols, rows] = [level.getMap().cols, level.getMap().rows];
    const screen = new Screen(cols / 2, rows / 2);
    level.getMap()._optimizeForRowAccess();
    screen.renderFullMap(level.getMap());
    screen.printRenderedChars();
};

RGTest.updateSystems = systems => {
    for (let i = 0; i < systems.length; i++) {
        systems[i].update();
    }
};

RGTest.enablePrint = true;

RGTest.printMemUsage = msg => {
    const used = process.memoryUsage().heapUsed / 1024 / 1024;
    const usedMb = Math.round(used * 100) / 100;
    if (RGTest.enablePrint) {
        console.log(`${msg} The script uses approximately ${usedMb} MB`);
    }
};

/* Can be used to destroy items during testing. */
RGTest.ItemDestroyer = function(pool) {

    this.numCalls = 0;
    this.numDestroyed = 0;

    this.hasNotify = true;
    this.notify = (evtName, obj) => {
        if (evtName === RG.EVT_DESTROY_ITEM) {
            const item = obj.item;
            const owner = item.getOwner().getOwner();
            ++this.numCalls;
            if (owner.getInvEq().removeItem(item)) {
                ++this.numDestroyed;
            }
        }
    };
    pool.listenEvent(RG.EVT_DESTROY_ITEM, this);
};

RGTest.ObjToString = function() {
    const stack = [];
    let msg = '';

    this.toString = (obj, maxStack = 10) => {
        for (const prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                stack.push(prop);
                if (stack.length < maxStack) {
                    if (typeof obj[prop] === 'object') {
                        this.toString(obj[prop], maxStack - 1);
                    }
                    else if (typeof obj[prop] === 'function') {
                        // msg += `Func in ${JSON.stringify(stack)}`;
                        msg += `\n\tFunction: ${prop}`;
                        // msg += `\n\tValue: ${obj[prop].toString()}`;
                    }
                    else if (obj[prop].toString) {
                        msg += obj[prop].toString();
                    }
                    else {
                        msg += obj[prop];
                    }
                }
                stack.pop();
            }
        }
    };

    this.getMsg = () => msg;
};

RGTest.elemString = function(elem, depth = 5) {
    const objToStr = new RGTest.ObjToString();
    objToStr.toString(elem, depth);
    return objToStr.getMsg();
};

RGTest.addOnTop = function(toAdd, locObj) {
    const [x, y] = [locObj.getX(), locObj.getY()];
    if (toAdd.getLevel().getID() === locObj.getLevel().getID()) {
        RGTest.moveEntityTo(toAdd, x, y);
    }
    else {
        RG.err('RGTest', 'addOnTop',
            'Does not work on objects on different levels yet');
    }
};

module.exports = RGTest;
<|endoftext|>


<commit_before>try {
  var args = process.argv, reporter_type = 'default';
  var reporters = require('nodeunit').reporters;

  if (args.length == 3) {
    reporter_type = args[2];

    if (!(reporter_type in reporters)) {
      console.error('Invalid reporter_type specified', reporter_type);
      process.exit();
    }
  }

  var reporter = reporters[reporter_type];
  var options  = require('./nodeunit.json');
}
catch(e) {
  console.log(e);
  console.log("Cannot find nodeunit module.");
  process.exit();
}

process.chdir(__dirname);

try {
  var server = require('mockserver').init();
  server.on('listening', function() {
    reporter.run(['src', 'src/index', 'src/runner', 'src/assertions', 'src/commands'], options, function() {
      server.close();
    });
  });
} catch (err) {
  console.log(e);
  process.exit();
}
<commit_msg>style(jshint): satisfy 'W109: Strings must use singlequote.'<commit_after>try {
  var args = process.argv, reporter_type = 'default';
  var reporters = require('nodeunit').reporters;

  if (args.length == 3) {
    reporter_type = args[2];

    if (!(reporter_type in reporters)) {
      console.error('Invalid reporter_type specified', reporter_type);
      process.exit();
    }
  }

  var reporter = reporters[reporter_type];
  var options  = require('./nodeunit.json');
}
catch(e) {
  console.log(e);
  console.log('Cannot find nodeunit module.');
  process.exit();
}

process.chdir(__dirname);

try {
  var server = require('mockserver').init();
  server.on('listening', function() {
    reporter.run(['src', 'src/index', 'src/runner', 'src/assertions', 'src/commands'], options, function() {
      server.close();
    });
  });
} catch (err) {
  console.log(e);
  process.exit();
}
<|endoftext|>


<commit_before><commit_msg>Fix issue in watcher utility<commit_after><|endoftext|>


<commit_before>/**
 * @properties={typeid:35,uuid:"D055F5E5-A18B-459B-9D17-86A082C98715",variableType:-4}
 */
var WEB_block_page_mode = false;

/**
 * @properties={typeid:35,uuid:"669F48AD-6BF9-4038-A808-1A8530337316",variableType:-4}
 */
var WEB_block_on_select = true;

/**
 * Populate meta data for selected block.
 *
 * @param	{String}	formName The block_type form.
 * @param	{String}	type The type of meta information we're interested in.
 *
 * @returns	{JSObject}	Pretty names and methods for requested meta information.
 *
 * @properties={typeid:24,uuid:"81DC790B-61A4-4895-BD4A-65F2BB1ABC21"}
 */
function WEB_block_methods(formName, type) {
	var methods = forms[formName].allmethods

	var clientActionsBlock = {}
	var clientActionsPage = {}
	var webActions = {}
	var views = {}

	for (var i in methods) {
		if ( methods[i].substr(0,5) == "BLOCK" ) {
			clientActionsBlock[methods[i].substr(6,100)] = methods[i]
		}
		if ( methods[i].substr(0,4) == "PAGE" ) {
			clientActionsPage[methods[i].substr(5,100)] = methods[i]
		}
		else if ( methods[i].substr(0,3) == "WEB" ) {
			webActions[methods[i].substr(4,100)] = methods[i]
		}
		else if ( methods[i].substr(0,4) == "VIEW" ) {
			views[methods[i].substr(5,100)] = methods[i]
		}
		else if ( methods[i].substr(0,10) == "CONTROLLER" ) {
			views[methods[i].substr(11,100)] = methods[i]
		}
	}

	switch (type) {
		case "BLOCK":
			return clientActionsBlock
			break
		case "PAGE":
			return clientActionsPage
		case "WEB":
			return webActions
			break
		case "VIEW":
			return views
			break
		default:
			return {}
	}
}

/**
 * @properties={typeid:24,uuid:"2936E71A-50BF-4F06-A427-09EE918F273C"}
 */
function WEB_block_form_refresh() {
//	//update display
//	if (globals.WEB_page_mode == 2) {
//		forms.WEB_0F_page__design_1F_version_2L_scope.ACTION_gui_mode_refresh()
//	}
//	else
	if (globals.WEB_page_mode == 3) {
		forms.WEB_0F_page__browser_1F_block__editor.FORM_on_show()
	}
}

/**
 * (Dis)Allows the REC_on_select method to fire for a block.
 *
 * @param {JSEvent} event Event that triggered onSelect of the block_type form.
 *
 * @returns {Boolean} Run the method.
 *
 * @properties={typeid:24,uuid:"E81AB531-F187-476A-9EE0-455D12DE6B5D"}
 */
function WEB_block_enable(event) {

	var blockEnable =
	//we're not in headless client
		application.getApplicationType() != APPLICATION_TYPES.HEADLESS_CLIENT &&
	//event is valid and called from a form
		event && event.getFormName && event.getFormName() &&
	//the foundset has records (don't fire when no block records)
		utils.hasRecords(forms[event.getFormName()].foundset) &&
	//selected block has a valid block type
		utils.hasRecords(forms[event.getFormName()].web_block_to_block_type) &&
	//either the edit form or the display form for said block type is calling the method (only run block_type code on correct block_type)
		(event.getFormName() == forms[event.getFormName()].web_block_to_block_type.form_name ||
		event.getFormName() == (forms[event.getFormName()].web_block_to_block_type.form_name_display || forms[event.getFormName()].web_block_to_block_type.form_name) ) &&
	//on_select not manually disabled
		globals.WEB_block_on_select

	return blockEnable
}

/**
 * Returns the correct web_block_data foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 *
 * @returns	{JSFoundset}	web_block_data foundset.
 *
 * @properties={typeid:24,uuid:"C8DFEF81-D9D8-4742-96C3-3BA32FFCF62C"}
 */
function WEB_block_getData(event, formName) {
	//get form from event
	if (!formName && event && event.getFormName) {
		formName = event.getFormName()
	}

	//we know where this is being called from
	if (formName) {
		//get the block record they were on
		/** @type {JSRecord<db:/sutra_cms/web_block>}*/
		var blockRec = forms[formName].foundset

		//on the page and not viewing page scrapbooks, just use active version
		if (globals.WEB_block_page_mode) {
			return (utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data : {}
		}
		//on a scrapbook, go through all relation (selected index determines which version)
		else {
			return (utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data')) ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data : {}
		}
	}
	//return something empty so won't fail as hard
	else {
		return new Object()
	}
}

/**
 * Returns the correct web_block_data_configure foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 *
 * @returns	{JSFoundset}	web_block_data_configure foundset.
 *
 * @properties={typeid:24,uuid:"C8DFEF81-D9D7-4742-96C3-3BA32FFCF62C"}
 */
function WEB_block_getConfig(event) {
	//we know where this is being called from
	if (event && event.getFormName) {
		//get the block record they were on
		/** @type {JSRecord<db:/sutra_cms/web_block>}*/
		var blockRec = forms[event.getFormName()].foundset

		//on the page and not viewing page scrapbooks, just use active version
		if (globals.WEB_block_page_mode) {
			return utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data_configure') ? blockRec.web_block_to_block_version.web_block_version_to_block_data_configure : {}
		}
		//on a scrapbook, go through all relation (selected index determines which version)
		else {
			return utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data_configure') ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data_configure : {}
		}
	}
}

/**
 * Returns the correct web_block_data_response foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 *
 * @returns	{JSFoundset}	web_block_data_response foundset.
 *
 * @properties={typeid:24,uuid:"B0D3D289-08E8-4820-9998-70F18D96C9B0"}
 */
function WEB_block_getResponse(event) {
	//we know where this is being called from
	if (event && event.getFormName) {
		//get the block record they were on
		/** @type {JSRecord<db:/sutra_cms/web_block>}*/
		var blockRec = forms[event.getFormName()].foundset

		//on the page and not viewing page scrapbooks, just use active version
		if (globals.WEB_block_page_mode) {
			return utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data_response') ? blockRec.web_block_to_block_version.web_block_version_to_block_data_response : {}
		}
		//on a scrapbook, go through all relation (selected index determines which version)
		else {
			return utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data_response') ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data_response : {}
		}
	}
}

/**
 * @properties={typeid:24,uuid:"B82E9E1D-9201-47C8-8FF7-D606643DCD6A"}
 */
function WEB_block_save() {
	//don't run when in real mode
	if (globals.WEB_page_mode != 3) {
		var formName = 'WEB_A__scrapbook'
		//on page gui detail
		if (globals.WEB_block_scope == 1 && globals.WEB_page_mode == 2 && forms.WEB_0F_page__design.elements.tab_main.tabIndex == 1) {
			formName = 'WEB_A__page'
		}

		//toggle upstream _editMode, but don't retrigger a save
		forms[formName].ACTION_save(null,true)
	}
}

/**
 * @properties={typeid:24,uuid:"44816F74-9845-4672-BE53-3D9C070DB6BC"}
 */
function WEB_block_cancel() {
	//don't run when in real mode
	if (globals.WEB_page_mode != 3) {
		var formName = 'WEB_A__scrapbook'
		//on page gui detail
		if (globals.WEB_block_scope == 1 && globals.WEB_page_mode == 2 && forms.WEB_0F_page__design.elements.tab_main.tabIndex == 1) {
			formName = 'WEB_A__page'
		}

		//toggle upstream _editMode, but don't retrigger a save
		forms[formName].ACTION_cancel(null,true)
	}
}

/**
 * Can selected block be edited.
 *
 * @returns {Boolean}	Edit-mode status.
 *
 * @properties={typeid:24,uuid:"BDE6D35A-5AF8-43F4-9575-04EFC6594475"}
 */
function WEB_block_edit_get() {
	//page scope
	if (globals.WEB_block_page_mode) {
		return forms.WEB_0F_page.ACTION_edit_get()
	}
	//scrapbook scope
	else {
		return forms.WEB_0F_block__scrapbook.ACTION_edit_get()
	}
}

/**
 * Gives a token that will represent a Sutra CMS object appropriately, given the context from which called.
 *
 * @param 	{JSRecord|String|UUID}	input The thing to be tokenized.
 * @param 	{String}				[tokenType] Type of CMS object. When passed a JSRecord, tokenType will be automatically determined.
 *
 * @returns	{String}	Token to reference a Sutra CMS object.
 *
 * @properties={typeid:24,uuid:"7F487623-AD66-4B6A-BEF0-90A4B1DEE499"}
 */
function WEB_block_link(input,tokenType) {
	return globals.WEB_MRKUP_link_token(input,tokenType)
}
<commit_msg>update getData[config/response] to work off headless client's object<commit_after>/**
 * @properties={typeid:35,uuid:"D055F5E5-A18B-459B-9D17-86A082C98715",variableType:-4}
 */
var WEB_block_page_mode = false;

/**
 * @properties={typeid:35,uuid:"669F48AD-6BF9-4038-A808-1A8530337316",variableType:-4}
 */
var WEB_block_on_select = true;

/**
 * Populate meta data for selected block.
 *
 * @param	{String}	formName The block_type form.
 * @param	{String}	type The type of meta information we're interested in.
 *
 * @returns	{JSObject}	Pretty names and methods for requested meta information.
 *
 * @properties={typeid:24,uuid:"81DC790B-61A4-4895-BD4A-65F2BB1ABC21"}
 */
function WEB_block_methods(formName, type) {
	var methods = forms[formName].allmethods

	var clientActionsBlock = {}
	var clientActionsPage = {}
	var webActions = {}
	var views = {}

	for (var i in methods) {
		if ( methods[i].substr(0,5) == "BLOCK" ) {
			clientActionsBlock[methods[i].substr(6,100)] = methods[i]
		}
		if ( methods[i].substr(0,4) == "PAGE" ) {
			clientActionsPage[methods[i].substr(5,100)] = methods[i]
		}
		else if ( methods[i].substr(0,3) == "WEB" ) {
			webActions[methods[i].substr(4,100)] = methods[i]
		}
		else if ( methods[i].substr(0,4) == "VIEW" ) {
			views[methods[i].substr(5,100)] = methods[i]
		}
		else if ( methods[i].substr(0,10) == "CONTROLLER" ) {
			views[methods[i].substr(11,100)] = methods[i]
		}
	}

	switch (type) {
		case "BLOCK":
			return clientActionsBlock
			break
		case "PAGE":
			return clientActionsPage
		case "WEB":
			return webActions
			break
		case "VIEW":
			return views
			break
		default:
			return {}
	}
}

/**
 * @properties={typeid:24,uuid:"2936E71A-50BF-4F06-A427-09EE918F273C"}
 */
function WEB_block_form_refresh() {
//	//update display
//	if (globals.WEB_page_mode == 2) {
//		forms.WEB_0F_page__design_1F_version_2L_scope.ACTION_gui_mode_refresh()
//	}
//	else
	if (globals.WEB_page_mode == 3) {
		forms.WEB_0F_page__browser_1F_block__editor.FORM_on_show()
	}
}

/**
 * (Dis)Allows the REC_on_select method to fire for a block.
 *
 * @param {JSEvent} event Event that triggered onSelect of the block_type form.
 *
 * @returns {Boolean} Run the method.
 *
 * @properties={typeid:24,uuid:"E81AB531-F187-476A-9EE0-455D12DE6B5D"}
 */
function WEB_block_enable(event) {

	var blockEnable =
	//we're not in headless client
		application.getApplicationType() != APPLICATION_TYPES.HEADLESS_CLIENT &&
	//event is valid and called from a form
		event && event.getFormName && event.getFormName() &&
	//the foundset has records (don't fire when no block records)
		utils.hasRecords(forms[event.getFormName()].foundset) &&
	//selected block has a valid block type
		utils.hasRecords(forms[event.getFormName()].web_block_to_block_type) &&
	//either the edit form or the display form for said block type is calling the method (only run block_type code on correct block_type)
		(event.getFormName() == forms[event.getFormName()].web_block_to_block_type.form_name ||
		event.getFormName() == (forms[event.getFormName()].web_block_to_block_type.form_name_display || forms[event.getFormName()].web_block_to_block_type.form_name) ) &&
	//on_select not manually disabled
		globals.WEB_block_on_select

	return blockEnable
}

/**
 * Returns the correct web_block_data foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 * @param	{Object}	[obj] Object used to drive headless client.
 *
 * @returns	{JSFoundset}	web_block_data foundset.
 *
 * @properties={typeid:24,uuid:"C8DFEF81-D9D8-4742-96C3-3BA32FFCF62C"}
 */
function WEB_block_getData(event, formName, obj) {
	//dummy foundset that will return 0 for size
	var fsBad = { getSize: function() {return 0}}

	//get from object (headless client)
	if (obj && obj.block && obj.block.record instanceof JSRecord) {
		/** @type {JSRecord<db:/sutra_cms/web_block_data>}*/
		return (utils.hasRecords(obj.block.record,'web_block_to_block_version.web_block_version_to_block_data')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data : fsBad
	}
	//get from context (smart client)
	else {
		//get form from event
		if (!formName && event && event.getFormName) {
			formName = event.getFormName()
		}

		//we know where this is being called from
		if (formName) {
			//get the block record they were on
			/** @type {JSRecord<db:/sutra_cms/web_block>}*/
			var blockRec = forms[formName].foundset

			//on the page and not viewing page scrapbooks, just use active version
			if (globals.WEB_block_page_mode) {
				/** @type {JSRecord<db:/sutra_cms/web_block_data>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data : fsBad
			}
			//on a scrapbook, go through all relation (selected index determines which version)
			else {
				/** @type {JSRecord<db:/sutra_cms/web_block_data>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data')) ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data : fsBad
			}
		}
		//return something empty so won't fail as hard
		else {
			return fsBad
		}
	}
}

/**
 * Returns the correct web_block_data_configure foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 * @param	{Object}	[obj] Object used to drive headless client.
 *
 * @returns	{JSFoundset}	web_block_data_configure foundset.
 *
 * @properties={typeid:24,uuid:"C8DFEF81-D9D7-4742-96C3-3BA32FFCF62C"}
 */
function WEB_block_getConfig(event, formName, obj) {
	//dummy foundset that will return 0 for size
	var fsBad = { getSize: function() {return 0}}

	//get from object (headless client)
	if (obj && obj.block && obj.block.record instanceof JSRecord) {
		/** @type {JSRecord<db:/sutra_cms/web_block_data_configure>}*/
		return (utils.hasRecords(obj.block.record,'web_block_to_block_version.web_block_version_to_block_data_configure')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data_configure : fsBad
	}
	//get from context (smart client)
	else {
		//get form from event
		if (!formName && event && event.getFormName) {
			formName = event.getFormName()
		}

		//we know where this is being called from
		if (formName) {
			//get the block record they were on
			/** @type {JSRecord<db:/sutra_cms/web_block>}*/
			var blockRec = forms[formName].foundset

			//on the page and not viewing page scrapbooks, just use active version
			if (globals.WEB_block_page_mode) {
				/** @type {JSRecord<db:/sutra_cms/web_block_data_configure>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data_configure')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data_configure : fsBad
			}
			//on a scrapbook, go through all relation (selected index determines which version)
			else {
				/** @type {JSRecord<db:/sutra_cms/web_block_data_configure>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data_configure')) ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data_configure : fsBad
			}
		}
		//return something empty so won't fail as hard
		else {
			return fsBad
		}
	}
}

/**
 * Returns the correct web_block_data_response foundset to work with.
 *
 * @param	{JSEvent}	event Event that triggered onSelect of the block_type form.
 * @param	{JSForm}	[formName] Scope where called from.
 * @param	{Object}	[obj] Object used to drive headless client.
 *
 * @returns	{JSFoundset}	web_block_data_response foundset.
 *
 * @properties={typeid:24,uuid:"B0D3D289-08E8-4820-9998-70F18D96C9B0"}
 */
function WEB_block_getResponse(event, formName, obj) {
	//dummy foundset that will return 0 for size
	var fsBad = { getSize: function() {return 0}}

	//get from object (headless client)
	if (obj && obj.block && obj.block.record instanceof JSRecord) {
		/** @type {JSRecord<db:/sutra_cms/web_block_data_response>}*/
		return (utils.hasRecords(obj.block.record,'web_block_to_block_version.web_block_version_to_block_data_response')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data_response : fsBad
	}
	//get from context (smart client)
	else {
		//get form from event
		if (!formName && event && event.getFormName) {
			formName = event.getFormName()
		}

		//we know where this is being called from
		if (formName) {
			//get the block record they were on
			/** @type {JSRecord<db:/sutra_cms/web_block>}*/
			var blockRec = forms[formName].foundset

			//on the page and not viewing page scrapbooks, just use active version
			if (globals.WEB_block_page_mode) {
				/** @type {JSRecord<db:/sutra_cms/web_block_data_response>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version.web_block_version_to_block_data_response')) ? blockRec.web_block_to_block_version.web_block_version_to_block_data_response : fsBad
			}
			//on a scrapbook, go through all relation (selected index determines which version)
			else {
				/** @type {JSRecord<db:/sutra_cms/web_block_data_response>}*/
				return (utils.hasRecords(blockRec,'web_block_to_block_version__all.web_block_version_to_block_data_response')) ? blockRec.web_block_to_block_version__all.web_block_version_to_block_data_response : fsBad
			}
		}
		//return something empty so won't fail as hard
		else {
			return fsBad
		}
	}
}

/**
 * @properties={typeid:24,uuid:"B82E9E1D-9201-47C8-8FF7-D606643DCD6A"}
 */
function WEB_block_save() {
	//don't run when in real mode
	if (globals.WEB_page_mode != 3) {
		var formName = 'WEB_A__scrapbook'
		//on page gui detail
		if (globals.WEB_block_scope == 1 && globals.WEB_page_mode == 2 && forms.WEB_0F_page__design.elements.tab_main.tabIndex == 1) {
			formName = 'WEB_A__page'
		}

		//toggle upstream _editMode, but don't retrigger a save
		forms[formName].ACTION_save(null,true)
	}
}

/**
 * @properties={typeid:24,uuid:"44816F74-9845-4672-BE53-3D9C070DB6BC"}
 */
function WEB_block_cancel() {
	//don't run when in real mode
	if (globals.WEB_page_mode != 3) {
		var formName = 'WEB_A__scrapbook'
		//on page gui detail
		if (globals.WEB_block_scope == 1 && globals.WEB_page_mode == 2 && forms.WEB_0F_page__design.elements.tab_main.tabIndex == 1) {
			formName = 'WEB_A__page'
		}

		//toggle upstream _editMode, but don't retrigger a save
		forms[formName].ACTION_cancel(null,true)
	}
}

/**
 * Can selected block be edited.
 *
 * @returns {Boolean}	Edit-mode status.
 *
 * @properties={typeid:24,uuid:"BDE6D35A-5AF8-43F4-9575-04EFC6594475"}
 */
function WEB_block_edit_get() {
	//page scope
	if (globals.WEB_block_page_mode) {
		return forms.WEB_0F_page.ACTION_edit_get()
	}
	//scrapbook scope
	else {
		return forms.WEB_0F_block__scrapbook.ACTION_edit_get()
	}
}

/**
 * Gives a token that will represent a Sutra CMS object appropriately, given the context from which called.
 *
 * @param 	{JSRecord|String|UUID}	input The thing to be tokenized.
 * @param 	{String}				[tokenType] Type of CMS object. When passed a JSRecord, tokenType will be automatically determined.
 *
 * @returns	{String}	Token to reference a Sutra CMS object.
 *
 * @properties={typeid:24,uuid:"7F487623-AD66-4B6A-BEF0-90A4B1DEE499"}
 */
function WEB_block_link(input,tokenType) {
	return globals.WEB_MRKUP_link_token(input,tokenType)
}
<|endoftext|>


<commit_before>StudentDashboardController.$inject = ['$rootScope', '$scope', '$state',
    'TbUtils', 'tableContent', 'sections', 'filterFilter', 'hours', 'students'];

function StudentDashboardController ($rootScope, $scope, $state, TbUtils, tableContent,
                                      sections, filterFilter, hours, students) {
  if($rootScope.Role !== 'Student' ) $state.go('main.'+$rootScope.Role.toLowerCase()+'-dashboard');

	const vm = this;
  vm.accountId;
  vm.totalHours;
  vm.name;
  vm.projects = [];
  vm.sections = [];
  vm.toTitleCase = TbUtils.toTitleCase;
  students.getAccountId(getAccountIdSuccess, getAccountIdFail);
  sections.getCurrentPeriodSections(getCurrentPeriodSectionsSuccess, getCurrentPeriodSectionsFail);

  function getAccountIdSuccess(response){
      vm.accountId = response.data.AccountId;
      vm.name = response.data.Name;
      hours.getStudentHourReport(vm.accountId, getStudentHourReportSuccess, getStudentHourReportFail);
      console.log(response);
  }
  function getAccountIdFail(response){
      console.log(response);
  }

  function limitProjects(projects){
      prjs = [];
      if(projects.length >= 4){
        for(i = 0; i < 4; i++){
          prjs[i] = projects[i];
        }
        return prjs;
      }else{
        return projects;
      }
  }
  function getStudentHourReportSuccess(response){
    vm.totalHours = response.data.TotalHours;
    vm.projects = limitProjects(response.data.Projects);
    console.log(response);
  }

  function getStudentHourReportFail(response){
    console.log(response);
  }

  function getCurrentPeriodSectionsSuccess(response){
    vm.sections = response.data;
    console.log("Sections data");
    console.log(vm.sections);
  }

  function getCurrentPeriodSectionsFail(response){
    console.log(response);
  }

  // // sections.getSections(getSectionsSuccess, getSectionsFail);
  //
  // function goSection(index) {
  //     console.log("Entro");
  // }
  //
  // sections.getSections(getTotalSectionsSuccess, getTotalSectionsFail);
  //
  // function getTotalSectionsSuccess(response) {
  //     console.log(response);
  //     TbUtils.fillListWithResponseData(response.data, vm.totalSections);
  // }
  //
  // $scope.$watch('search.data', function(term) {
  //     let obj = {
  //         Class: {
  //             Name: term
  //         }
  //     };
  //
  //     if(term && term.length >= vm.limitInLettersToSearch) {
  //         let filterSections = {data: filterFilter(vm.totalSections, obj)};
  //         let filterTable = [];
  //         constructTableBody(filterSections, filterTable);
  //         vm.sectionsTable.body = filterTable;
  //     }
  //
  //     else {
  //         console.log('vacio');
  //         vm.sectionsTable.body = vm.paginationSections;
  //     }
  // });
  //
  // function getTotalSectionsFail(response) {
  //     console.log(response);
  // }
  //
  // function getSectionsSuccess(response) {
  //     console.log(response.data.length);
  //     if (response.data.length <= 0) {
  //         vm.sectionsLoading = false;
  //         return;
  //     }
  //
  //     constructTableBody(response, vm.paginationSections);
  //
  //     vm.sectionsTable.body = vm.paginationSections;
  //     vm.sectionsLoading = false;
  // };
  //
  // function constructTableBody(response, tableSections) {
  //     for (let i = 0; i < response.data.length; i++) {
  //         console.log('Entro');
  //         let section = response.data[i];
  //         let name = 'N/A';
  //
  //         if (section.User !== null)
  //             name = section.User.Name;
  //
  //         let newTableElement = {
  //             content: [
  //                 tableContent.createALableElement(section.Code),
  //                 tableContent.createALableElement(section.Class.Name),
  //                 tableContent.createALableElement(section.Period.Number),
  //                 tableContent.createALableElement(section.Period.Year),
  //                 tableContent.createALableElement(name)
  //             ],
  //             data: section
  //         };
  //
  //         //vm.sectionsTable.body.push(newTableElement);
  //         tableSections.push(newTableElement);
  //     }
  // }
  //
  // sections.getSectionCount(getSectionCountSuccess, getSectionCountFail);
  //
  // function getSectionCountSuccess(response) {
  //     vm.options.count = response.data[0].Id;
  //     vm.sectionsLoading = true;
  //     sections.getSectionsWithPagination(vm.options.startingPage,
  //         vm.options.pageSize, getSectionsSuccess, getSectionsFail);
  // }
  //
  // function getSectionCountFail() {
  //     getSectionsFail();
  // }
  //
  // function getSectionsFail() {
  //     vm.sectionsLoading = false;
  //     TbUtils.displayNotification('error', 'Error',
  //         'No se pudieron cargar las secciones correctamente.');
  // }
  //
  // function onPageChange(skip, page) {
  //     if($scope.search) $scope.search.data = '';
  //     vm.sectionsTable.body = [];
  //     vm.paginationSections = [];
  //     vm.sectionsLoading = true;
  //     sections.getSectionsWithPagination(page, skip,
  //         getSectionsSuccess, getSectionsFail);
  // }
}

module.exports = { name: 'StudentDashboardController', ctrl: StudentDashboardController };
<commit_msg>Adding return in rootscope role validation<commit_after>StudentDashboardController.$inject = ['$rootScope', '$scope', '$state',
    'TbUtils', 'tableContent', 'sections', 'filterFilter', 'hours', 'students'];

function StudentDashboardController ($rootScope, $scope, $state, TbUtils, tableContent,
                                      sections, filterFilter, hours, students) {
  if($rootScope.Role !== 'Student' ){
    $state.go('main.'+$rootScope.Role.toLowerCase()+'-dashboard');
    return;
  }

	const vm = this;
  vm.accountId;
  vm.totalHours;
  vm.name;
  vm.projects = [];
  vm.sections = [];
  vm.goToSection = goToSection;
  vm.toTitleCase = TbUtils.toTitleCase;
  students.getAccountId(getAccountIdSuccess, getAccountIdFail);
  sections.getCurrentPeriodSections(getCurrentPeriodSectionsSuccess, getCurrentPeriodSectionsFail);

  function getAccountIdSuccess(response){
      vm.accountId = response.data.AccountId;
      vm.name = response.data.Name;
      hours.getStudentHourReport(vm.accountId, getStudentHourReportSuccess, getStudentHourReportFail);
      console.log(response);
  }
  function getAccountIdFail(response){
      console.log(response);
  }

  function goToSection(id){
    $state.go('main.section',{
      sectionId: id
    });
  }

  function limitProjects(projects){
      prjs = [];
      if(projects.length >= 4){
        for(i = 0; i < 4; i++){
          prjs[i] = projects[i];
        }
        return prjs;
      }else{
        return projects;
      }
  }
  function getStudentHourReportSuccess(response){
    vm.totalHours = response.data.TotalHours;
    vm.projects = limitProjects(response.data.Projects);
    console.log(response);
  }

  function getStudentHourReportFail(response){
    console.log(response);
  }

  function getCurrentPeriodSectionsSuccess(response){
    vm.sections = response.data;
    console.log("Sections data");
    console.log(vm.sections);
  }

  function getCurrentPeriodSectionsFail(response){
    console.log(response);
  }

  // // sections.getSections(getSectionsSuccess, getSectionsFail);
  //
  // function goSection(index) {
  //     console.log("Entro");
  // }
  //
  // sections.getSections(getTotalSectionsSuccess, getTotalSectionsFail);
  //
  // function getTotalSectionsSuccess(response) {
  //     console.log(response);
  //     TbUtils.fillListWithResponseData(response.data, vm.totalSections);
  // }
  //
  // $scope.$watch('search.data', function(term) {
  //     let obj = {
  //         Class: {
  //             Name: term
  //         }
  //     };
  //
  //     if(term && term.length >= vm.limitInLettersToSearch) {
  //         let filterSections = {data: filterFilter(vm.totalSections, obj)};
  //         let filterTable = [];
  //         constructTableBody(filterSections, filterTable);
  //         vm.sectionsTable.body = filterTable;
  //     }
  //
  //     else {
  //         console.log('vacio');
  //         vm.sectionsTable.body = vm.paginationSections;
  //     }
  // });
  //
  // function getTotalSectionsFail(response) {
  //     console.log(response);
  // }
  //
  // function getSectionsSuccess(response) {
  //     console.log(response.data.length);
  //     if (response.data.length <= 0) {
  //         vm.sectionsLoading = false;
  //         return;
  //     }
  //
  //     constructTableBody(response, vm.paginationSections);
  //
  //     vm.sectionsTable.body = vm.paginationSections;
  //     vm.sectionsLoading = false;
  // };
  //
  // function constructTableBody(response, tableSections) {
  //     for (let i = 0; i < response.data.length; i++) {
  //         console.log('Entro');
  //         let section = response.data[i];
  //         let name = 'N/A';
  //
  //         if (section.User !== null)
  //             name = section.User.Name;
  //
  //         let newTableElement = {
  //             content: [
  //                 tableContent.createALableElement(section.Code),
  //                 tableContent.createALableElement(section.Class.Name),
  //                 tableContent.createALableElement(section.Period.Number),
  //                 tableContent.createALableElement(section.Period.Year),
  //                 tableContent.createALableElement(name)
  //             ],
  //             data: section
  //         };
  //
  //         //vm.sectionsTable.body.push(newTableElement);
  //         tableSections.push(newTableElement);
  //     }
  // }
  //
  // sections.getSectionCount(getSectionCountSuccess, getSectionCountFail);
  //
  // function getSectionCountSuccess(response) {
  //     vm.options.count = response.data[0].Id;
  //     vm.sectionsLoading = true;
  //     sections.getSectionsWithPagination(vm.options.startingPage,
  //         vm.options.pageSize, getSectionsSuccess, getSectionsFail);
  // }
  //
  // function getSectionCountFail() {
  //     getSectionsFail();
  // }
  //
  // function getSectionsFail() {
  //     vm.sectionsLoading = false;
  //     TbUtils.displayNotification('error', 'Error',
  //         'No se pudieron cargar las secciones correctamente.');
  // }
  //
  // function onPageChange(skip, page) {
  //     if($scope.search) $scope.search.data = '';
  //     vm.sectionsTable.body = [];
  //     vm.paginationSections = [];
  //     vm.sectionsLoading = true;
  //     sections.getSectionsWithPagination(page, skip,
  //         getSectionsSuccess, getSectionsFail);
  // }
}

module.exports = { name: 'StudentDashboardController', ctrl: StudentDashboardController };
<|endoftext|>


<commit_before>/*global cordova */

var Fingerprint = function() {
}

// Plugin Errors
Fingerprint.prototype.BIOMETRIC_UNKNOWN_ERROR = -100;
Fingerprint.prototype.BIOMETRIC_UNAVAILABLE = -101;
Fingerprint.prototype.BIOMETRIC_AUTHENTICATION_FAILED = -102;
Fingerprint.prototype.BIOMETRIC_SDK_NOT_SUPPORTED = -103;
Fingerprint.prototype.BIOMETRIC_HARDWARE_NOT_SUPPORTED = -104;
Fingerprint.prototype.BIOMETRIC_PERMISSION_NOT_GRANTED = -105;
Fingerprint.prototype.BIOMETRIC_FINGERPRINT_NOT_ENROLLED = -106;
Fingerprint.prototype.BIOMETRIC_INTERNAL_PLUGIN_ERROR = -107;
Fingerprint.prototype.BIOMETRIC_FINGERPRINT_DISMISSED = -108;
Fingerprint.prototype.BIOMETRIC_PIN_OR_PATTERN_DISMISSED = -109;
Fingerprint.prototype.BIOMETRIC_SCREEN_GUARD_UNSECURED = -110;
Fingerprint.prototype.BIOMETRIC_LOCKED_OUT = -111;
Fingerprint.prototype.BIOMETRIC_LOCKED_OUT_PERMANENT = -112;

Fingerprint.prototype.show = function (params, successCallback, errorCallback) {
  cordova.exec(
    successCallback,
    errorCallback,
    "Fingerprint",
    "authenticate",
    [params]
  );
};

Fingerprint.prototype.isAvailable = function (successCallback, errorCallback) {
  cordova.exec(
    successCallback,
    errorCallback,
    "Fingerprint",
    "isAvailable",
    [{}]
  );
};

module.exports = new Fingerprint();
<commit_msg>Fix linting error<commit_after>/*global cordova */

var Fingerprint = function() {
};

// Plugin Errors
Fingerprint.prototype.BIOMETRIC_UNKNOWN_ERROR = -100;
Fingerprint.prototype.BIOMETRIC_UNAVAILABLE = -101;
Fingerprint.prototype.BIOMETRIC_AUTHENTICATION_FAILED = -102;
Fingerprint.prototype.BIOMETRIC_SDK_NOT_SUPPORTED = -103;
Fingerprint.prototype.BIOMETRIC_HARDWARE_NOT_SUPPORTED = -104;
Fingerprint.prototype.BIOMETRIC_PERMISSION_NOT_GRANTED = -105;
Fingerprint.prototype.BIOMETRIC_FINGERPRINT_NOT_ENROLLED = -106;
Fingerprint.prototype.BIOMETRIC_INTERNAL_PLUGIN_ERROR = -107;
Fingerprint.prototype.BIOMETRIC_FINGERPRINT_DISMISSED = -108;
Fingerprint.prototype.BIOMETRIC_PIN_OR_PATTERN_DISMISSED = -109;
Fingerprint.prototype.BIOMETRIC_SCREEN_GUARD_UNSECURED = -110;
Fingerprint.prototype.BIOMETRIC_LOCKED_OUT = -111;
Fingerprint.prototype.BIOMETRIC_LOCKED_OUT_PERMANENT = -112;

Fingerprint.prototype.show = function (params, successCallback, errorCallback) {
  cordova.exec(
    successCallback,
    errorCallback,
    "Fingerprint",
    "authenticate",
    [params]
  );
};

Fingerprint.prototype.isAvailable = function (successCallback, errorCallback) {
  cordova.exec(
    successCallback,
    errorCallback,
    "Fingerprint",
    "isAvailable",
    [{}]
  );
};

module.exports = new Fingerprint();
<|endoftext|>


<commit_before>cordova.define("cordova-plugin-permissions.Permissions", function(require, exports, module) {

    "use strict";

    function Permissions() {
    }

    Permissions.prototype.getLocationPermissions = function (callback) {
        cordova.exec(callback, null, "Permissions", "getLocationPermissions", []);
    };

    Permissions.prototype.getNotificationPermissions = function (callback) {
        cordova.exec(callback, null, "Permissions", "getNotificationPermissions", []);
    };

    Permissions.prototype.getCalendarPermissions = function (callback) {
        cordova.exec(callback, null, "Permissions", "getCalendarPermissions", []);
    };

    Permissions.prototype.getHealthKitPermissions = function (callback) {
        cordova.exec(callback, null, "Permissions", "getHealthKitPermissions", []);
    };

    Permissions.prototype.openSettings = function (callback) {
      cordova.exec(callback, null, "Permissions", "openSettings", []);
    };

    Permissions.install = function () {
      if (!window.plugins) {
        window.plugins = {};
      }

      window.plugins.permissions = new Permissions();
      return window.plugins.permissions;
    };

    cordova.addConstructor(Permissions.install);

});
<commit_msg>remove outer cordova wrapper<commit_after>
function Permissions() {
}

Permissions.prototype.getLocationPermissions = function (callback) {
    cordova.exec(callback, null, "Permissions", "getLocationPermissions", []);
};

Permissions.prototype.getNotificationPermissions = function (callback) {
    cordova.exec(callback, null, "Permissions", "getNotificationPermissions", []);
};

Permissions.prototype.getCalendarPermissions = function (callback) {
    cordova.exec(callback, null, "Permissions", "getCalendarPermissions", []);
};

Permissions.prototype.getHealthKitPermissions = function (callback) {
    cordova.exec(callback, null, "Permissions", "getHealthKitPermissions", []);
};

Permissions.prototype.openSettings = function (callback) {
  cordova.exec(callback, null, "Permissions", "openSettings", []);
};

Permissions.install = function () {
  if (!window.plugins) {
    window.plugins = {};
  }

  window.plugins.permissions = new Permissions();
  return window.plugins.permissions;
};

cordova.addConstructor(Permissions.install);
<|endoftext|>


<commit_before>define([
    '/bower_components/jquery/dist/jquery.min.js',
    '/common/hyperjson.js', // serializing classes as an attribute
    '/common/hyperscript.js', // using setAttribute
    '/common/TextPatcher.js'
], function (jQuery, Hyperjson, Hyperscript, TextPatcher) {
    var $ = window.jQuery;
    window.Hyperjson = Hyperjson;
    window.Hyperscript = Hyperscript;
    window.TextPatcher = TextPatcher;

    var assertions = 0;
    var failed = false;
    var failedOn;
    var failMessages = [];

    var ASSERTS = [];
    var runASSERTS = function () {
        ASSERTS.forEach(function (f, index) {
            f(index);
        });
    };

    var assert = function (test, msg) {
        ASSERTS.push(function (i) {
            if (test()) {
                assertions++;
            } else {
                failed = true;
                failedOn = assertions;
                failMessages.push({
                    test: i,
                    message: msg
                });
            }
        });
    };

    var $body = $('body');

    var roundTrip = function (target) {
        assert(function () {
            var hjson = Hyperjson.fromDOM(target);
            var cloned = Hyperjson.callOn(hjson, Hyperscript);

            var success = cloned.outerHTML === target.outerHTML;

            if (!success) {
                var op = TextPatcher.diff(target.outerHTML, cloned.outerHTML);
                window.DEBUG = {
                    error: "Expected equality between A and B",
                    A: target.outerHTML,
                    B: cloned.outerHTML,
                    diff: op
                };
                console.log(JSON.stringify(window.DEBUG, null, 2));
                TextPatcher.log(op);
            }

            return success;
        }, "Round trip serialization introduced artifacts.");
    };

    [   '#target',
        '#widget',
        '#quot',
    ].forEach(function (sel) {
        roundTrip($(sel)[0]);
    });

    var strungJSON = function (orig) {
        var result;
        assert(function () {
            result = JSON.stringify(JSON.parse(orig));
            return result === orig;
        }, "expected result (" + result + ") to equal original (" + orig + ")");
    };

    [   '{"border":"1","style":{"width":"500px"}}',
        '{"style":{"width":"500px"},"border":"1"}',
    ].forEach(function (orig) {
        strungJSON(orig);
    });

    //assert(function () { }, "this is expected to fail");

    /*  TODO Test how browsers handle weird elements
        like "_moz-resizing":"true"

        and anything else you can think of.

        Start with Hyperjson, turn it into a DOM and come back
    */

    var swap = function (str, dict) {
        return str.replace(/\{\{(.*?)\}\}/g, function (all, key) {
            return typeof dict[key] !== 'undefined'? dict[key] : all;
        });
    };

    var multiline = function (f) {
        var str;
        f.toString().replace(/\/\*([\s\S]*)\*\//g, function (all, out) {
            str = out;
        });
        return str || '';
    };

    var formatFailures = function () {
        var template = multiline(function () { /*

Failed on test number {{test}} with error:
> "{{message}}"

*/});
        return failMessages.map(function (obj) {
            console.log(obj);
            return swap(template, obj);
        }).join("\n");
    };

    runASSERTS();

    $("body").html(function (i, val) {
        var dict = {
            previous: val,
            totalAssertions: ASSERTS.length,
            passedAssertions: assertions,
            plural: (assertions === 1? '' : 's'),
            failMessages: formatFailures()
        };

        var SUCCESS = swap(multiline(function(){/*

{{passedAssertions}} / {{totalAssertions}} test{{plural}} passed.

{{failMessages}}

{{previous}}
        */}), dict);

        var report = SUCCESS;

        return report;
    });

    var $report = $('.report');
    $report.addClass(failed?'failure':'success');

});
<commit_msg>add a FIXME to the assert page<commit_after>require.config({ paths: { 'json.sortify': '/bower_components/json.sortify/dist/JSON.sortify' } });
define([
    '/bower_components/jquery/dist/jquery.min.js',
    '/common/hyperjson.js', // serializing classes as an attribute
    '/common/hyperscript.js', // using setAttribute
    '/common/TextPatcher.js',
    'json.sortify',
], function (jQuery, Hyperjson, Hyperscript, TextPatcher, JSONSortify) {
    var $ = window.jQuery;
    window.Hyperjson = Hyperjson;
    window.Hyperscript = Hyperscript;
    window.TextPatcher = TextPatcher;

    var assertions = 0;
    var failed = false;
    var failedOn;
    var failMessages = [];

    var ASSERTS = [];
    var runASSERTS = function () {
        ASSERTS.forEach(function (f, index) {
            f(index);
        });
    };

    var assert = function (test, msg) {
        ASSERTS.push(function (i) {
            if (test()) {
                assertions++;
            } else {
                failed = true;
                failedOn = assertions;
                failMessages.push({
                    test: i,
                    message: msg
                });
            }
        });
    };

    var $body = $('body');

    /*  FIXME
        Chrome reorganizes your HTML such that id and class are in a opposite
        orders. We need to do an equality check on the hyperjson, outerHTML
        differences are not informative. */
    var roundTrip = function (target) {
        assert(function () {
            var hjson = Hyperjson.fromDOM(target);
            var cloned = Hyperjson.callOn(hjson, Hyperscript);

            var success = cloned.outerHTML === target.outerHTML;

            if (!success) {
                var op = TextPatcher.diff(target.outerHTML, cloned.outerHTML);
                window.DEBUG = {
                    error: "Expected equality between A and B",
                    A: target.outerHTML,
                    B: cloned.outerHTML,
                    diff: op
                };
                console.log(JSON.stringify(window.DEBUG, null, 2));
                TextPatcher.log(op);
            }

            return success;
        }, "Round trip serialization introduced artifacts.");
    };

    [   '#target',
        '#widget',
        '#quot',
    ].forEach(function (sel) {
        roundTrip($(sel)[0]);
    });

    var strungJSON = function (orig) {
        var result;
        assert(function () {
            result = JSON.stringify(JSON.parse(orig));
            return result === orig;
        }, "expected result (" + result + ") to equal original (" + orig + ")");
    };

    [   '{"border":"1","style":{"width":"500px"}}',
        '{"style":{"width":"500px"},"border":"1"}',
    ].forEach(function (orig) {
        strungJSON(orig);
    });

    //assert(function () { }, "this is expected to fail");

    /*  TODO Test how browsers handle weird elements
        like "_moz-resizing":"true"

        and anything else you can think of.

        Start with Hyperjson, turn it into a DOM and come back
    */

    var swap = function (str, dict) {
        return str.replace(/\{\{(.*?)\}\}/g, function (all, key) {
            return typeof dict[key] !== 'undefined'? dict[key] : all;
        });
    };

    var multiline = function (f) {
        var str;
        f.toString().replace(/\/\*([\s\S]*)\*\//g, function (all, out) {
            str = out;
        });
        return str || '';
    };

    var formatFailures = function () {
        var template = multiline(function () { /*

Failed on test number {{test}} with error:
> "{{message}}"

*/});
        return failMessages.map(function (obj) {
            console.log(obj);
            return swap(template, obj);
        }).join("\n");
    };

    runASSERTS();

    $("body").html(function (i, val) {
        var dict = {
            previous: val,
            totalAssertions: ASSERTS.length,
            passedAssertions: assertions,
            plural: (assertions === 1? '' : 's'),
            failMessages: formatFailures()
        };

        var SUCCESS = swap(multiline(function(){/*

{{passedAssertions}} / {{totalAssertions}} test{{plural}} passed.

{{failMessages}}

{{previous}}
        */}), dict);

        var report = SUCCESS;

        return report;
    });

    var $report = $('.report');
    $report.addClass(failed?'failure':'success');

});
<|endoftext|>


<commit_before>function Database($scope) {
	//new PostingController();
	PouchDB.DEBUG = true;
	var db = 'ppnet_suelz';

	$scope.db = new PouchDB(db, {
		debug: true,
		auto_compaction: true
	});
	//$scope.db = new PouchDB('ppnet');

	//AMAZON
	//$scope.remoteCouch = 'http://107.20.67.201:5984/'+db;

	//FI-Ware
	//$scope.remoteCouch = 'http://130.206.83.238:5984/'+db';

	$scope.remoteCouch = 'http://couchdb.simple-url.com:5984/' + db;

	// Function for continuous sync

	$scope.sync = function() {
		console.log('sync');
		var opts = {
			continuous: true,
			include_docs: true
		};
		$scope.db.replicate.from($scope.remoteCouch, opts);
	};

	// Inital Replication from remote to local (data-subset: only POSTs not older than 24hours)
	var initialReplicateFrom = function(time) {
		console.log('START: initialReplicateFrom (' + time + ')');
		var args = {
			complete: function() {
				console.log('FINISH: initialReplicateFrom (' + time + ') args');
				//initialReplicateFromOld(time);
			},
			onChange: function(change) {},
			filter: function(doc, req) {
				var oldest_timestamp = time - (86400 * 1000);

				//if (doc.created > oldest_timestamp && doc.type && doc.type == "POST") {
				if (doc.created > oldest_timestamp) {
					return true;
				} else {
					return false;
				}

			}
		};
		$scope.db.replicate.from($scope.remoteCouch, args);
	};

	if ($scope.remoteCouch) {
		$scope.sync();
		initialReplicateFrom(new Date().getTime());
	}
	Offline.on('up', function() {
		$scope.sync();
		initialReplicateFrom(new Date().getTime());
	}, '');
}<commit_msg>new DB<commit_after>function Database($scope) {
	//new PostingController();
	PouchDB.DEBUG = true;
	var db = 'ppnet_0603';

	$scope.db = new PouchDB(db, {
		debug: true,
		auto_compaction: true
	});
	//$scope.db = new PouchDB('ppnet');

	//AMAZON
	//$scope.remoteCouch = 'http://107.20.67.201:5984/'+db;

	//FI-Ware
	//$scope.remoteCouch = 'http://130.206.83.238:5984/'+db';

	$scope.remoteCouch = 'http://couchdb.simple-url.com:5984/' + db;
	// Function for continuous sync

	$scope.sync = function() {
		console.log('sync');
		var opts = {
			continuous: true,
			include_docs: true
		};
		$scope.db.replicate.from($scope.remoteCouch, opts);
	};

	// Inital Replication from remote to local (data-subset: only POSTs not older than 24hours)
	var initialReplicateFrom = function(time) {
		console.log('START: initialReplicateFrom (' + time + ')');
		var args = {
			complete: function() {
				console.log('FINISH: initialReplicateFrom (' + time + ') args');
				//initialReplicateFromOld(time);
			},
			onChange: function(change) {},
			filter: function(doc, req) {
				var oldest_timestamp = time - (86400 * 1000);

				//if (doc.created > oldest_timestamp && doc.type && doc.type == "POST") {
				if (doc.created > oldest_timestamp) {
					return true;
				} else {
					return false;
				}

			}
		};
		$scope.db.replicate.from($scope.remoteCouch, args);
	};

	if ($scope.remoteCouch) {
		$scope.sync();
		initialReplicateFrom(new Date().getTime());
	}
	Offline.on('up', function() {
		$scope.sync();
		initialReplicateFrom(new Date().getTime());
	}, '');
}<|endoftext|>


<commit_before>/*global URLify*/
(function($) {
    'use strict';
    $.fn.prepopulate = function(dependencies, maxLength, allowUnicode) {
        /*
            Depends on urlify.js
            Populates a selected field with the values of the dependent fields,
            URLifies and shortens the string.
            dependencies - array of dependent fields ids
            maxLength - maximum length of the URLify'd string
            allowUnicode - Unicode support of the URLify'd string
        */
        return this.each(function() {
            var prepopulatedField = $(this);

            var populate = function() {
                // Bail if the field's value has been changed by the user
                if (prepopulatedField.data('_changed')) {
                    return;
                }

                var values = [];
                $.each(dependencies, function(i, field) {
                    field = $(field);
                    if (field.val().length > 0) {
                        values.push(field.val());
                    }
                });
                prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode));
            };

            prepopulatedField.data('_changed', false);
            prepopulatedField.change(function() {
                prepopulatedField.data('_changed', true);
            });

            if (!prepopulatedField.val()) {
                $(dependencies.join(',')).keyup(populate).change(populate).focus(populate);
            }
        });
    };
})(django.jQuery);
<commit_msg>Update tmp/admin/js/prepopulate.js<commit_after><|endoftext|>