<commit_before>casper.on('remote.message', function(message) {
    this.echo('Message: '+ JSON.stringify(message));
});

casper.on('page.error', function(message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function() {
    this.evaluate(function() {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function(oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs   = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP    = function() {},
                    fBound  = function() {
                        return fToBind.apply(this instanceof fNOP
                                             ? this
                                             : oThis,
                                             aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 16, function suite(test) {
    casper.start('https://project-m-staging.herokuapp.com/', function() {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function() {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

     // test for supporter membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function() {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function() {
       this.click('input[name="isEnrolled"][value="No"]');
       this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function() {
       this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function() {
       this.click('input[name="isMemberOfOtherParty"][value="No"]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function() {
        this.click('button');
        casper.then(function() {
            test.assertSelectorHasText('h1.form-title', 'Details');  //find the title
        });
    });

    casper.run(function () {
        test.done();
    });
});
<commit_msg>add Details page test<commit_after>casper.on('remote.message', function(message) {
    this.echo('Message: '+ JSON.stringify(message));
});

casper.on('page.error', function(message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function() {
    this.evaluate(function() {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function(oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs   = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP    = function() {},
                    fBound  = function() {
                        return fToBind.apply(this instanceof fNOP
                                             ? this
                                             : oThis,
                                             aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 16, function suite(test) {
    casper.start('https://project-m-staging.herokuapp.com/', function() {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function() {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

     // test for supporter membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function() {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function() {
       this.click('input[name="isEnrolled"][value="No"]');
       this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function() {
       this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function() {
       this.click('input[name="isMemberOfOtherParty"][value="No"]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function() {
        this.click('button');
        casper.then(function() {
            test.assertSelectorHasText('h1.form-title', 'Details');  //find the title
        });
    });

// Details page tests

    //Residential Address Only

    casper.then(function() {
      this.sendKeys('input[id=firstName]', 'Connor');
      this.sendKeys('input[id=lastName]', 'Melbourne');
      this.sendKeys('input[id=dateOfBirth]', '12/08/2014');
      this.sendKeys('input[id="residentialAddress[address]"]', 'Laboriosam at inventore unde quo iure adipisicing ut voluptas sed soluta ut');
      this.sendKeys('input[id="residentialAddress[suburb]"]', 'Incidunt modi necessitatibus rem vitae modi eiusmod voluptatem numquam corporis laboriosam consequatur Eos reprehenderit');
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });

      this.sendKeys('input[id="residentialAddress[postcode]"]', '35191');
      this.sendKeys('input[id=email]', 'qoku@gmail.com');
      this.sendKeys('input[id=primaryPhoneNumber]', '0412345678');

      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });
    casper.run(function () {
        test.done();
    });
});
<|endoftext|>


<commit_before>
function cardValue(card) {
  return 2 + ('234567891JQKA'.indexOf(card.rank.charAt(0)));
}

function cardIndex(card) {
  return ('AKQJ198765432'.indexOf(card.rank.charAt(0)));
}

var new_strategy = true;

module.exports = {

  VERSION: "Goku JS - it's over 9004 (" + (new_strategy ? 'new' : 'old') + ')',

  bet_request: function(game_state) {
    var player = game_state.players[game_state.in_action];
    var cards = player.hole_cards;
    var post_flop = game_state.community_cards.length > 0;

    var all_in = player.stack;

    if (new_strategy) {
      var suited = cards[0].suit == cards[1].suit;
      var same_rank = cards[0].rank == cards[1].rank;
      var min_rank = Math.min(cardIndex(cards[0]), cardIndex(cards[1]));
      var max_rank = Math.max(cardIndex(cards[0]), cardIndex(cards[1]));
      var data = [
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 19.9, 19.3],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 16.3, 13.5, 12.7],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 18.6, 14.7, 13.5, 10.6, 8.5 ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 11.9, 10.5, 7.7 , 6.5 ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 14.4, 6.9 , 4.9 , 3.7 ],
          [20, 18.0, 13.0, 13.3, 17.5, 20  , 20  , 20  , 20  , 18.8, 10.1, 2.7 , 2.5 ],
          [20, 16.1, 10.3, 8.5 , 9.0 , 10.8, 14.7, 20  , 20  , 20  , 13.9, 2.5 , 2.1 ],
          [20, 15.1, 9.6 , 6.5 , 5.7 , 5.2 , 7.0 , 10.7, 20  , 20  , 16.3, 2.3 , 2.0 ],
          [20, 14.2, 8.9 , 6.0 , 4.1 , 3.5 , 3.0 , 2.6 , 2.4 , 20  , 20  , 2.4 , 2.0,],
          [20, 13.1, 7.9 , 5.4 , 3.8 , 2.7 , 2.3 , 2.1 , 2.0 , 2.1 , 20  , 2.2 , 1.8 ],
          [20, 12.2, 7.5 , 5.0 , 3.4 , 2.5 , 1.9 , 1.8 , 1.7 , 1.8 , 1.6 , 20  , 1.7 ],
          [20, 11.6, 7.0 , 4.6 , 2.9 , 2.2 , 1.8 , 1.6 , 1.5 , 1.5 , 1.4 , 1.4 ,20   ]
      ];

      var mult = 0;

      if (suited) {
        mult = data[max_rank][min_rank];
      } else {
        mult = data[min_rank][max_rank];
      }

      return Math.floor(mult * 2 * game_state.small_blind);

    } else {
      if ('AK'.indexOf(cards[0].rank) != -1 && 'AK'.indexOf(cards[1].rank) != -1) {
        return all_in;
      }

      if (cards[0].rank == cards[1].rank) {
        return all_in;
      }

      if (cards[0].suit == cards[1].suit &&
          Math.abs(cardValue(cards[0]) - cardValue(cards[1])) == 1)
      {
        return all_in;
      }

      if ((game_state.in_action + 2) % 4 == player.dealer &&
          (game_state.pot < 8 * game_state.small_blind || game_state.pot < 300))
      {
        return all_in;
      }

      if (Math.random() < 0.1) {
        return all_in;
      }
    }

    return 0;
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Subtracting current buy in<commit_after>
function cardValue(card) {
  return 2 + ('234567891JQKA'.indexOf(card.rank.charAt(0)));
}

function cardIndex(card) {
  return ('AKQJ198765432'.indexOf(card.rank.charAt(0)));
}

var new_strategy = true;

module.exports = {

  VERSION: "Goku JS - it's over 9004 (" + (new_strategy ? 'new' : 'old') + ')',

  bet_request: function(game_state) {
    var player = game_state.players[game_state.in_action];
    var cards = player.hole_cards;
    var post_flop = game_state.community_cards.length > 0;

    var all_in = player.stack;

    if (new_strategy) {
      var suited = cards[0].suit == cards[1].suit;
      var same_rank = cards[0].rank == cards[1].rank;
      var min_rank = Math.min(cardIndex(cards[0]), cardIndex(cards[1]));
      var max_rank = Math.max(cardIndex(cards[0]), cardIndex(cards[1]));
      var data = [
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 19.9, 19.3],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 16.3, 13.5, 12.7],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 18.6, 14.7, 13.5, 10.6, 8.5 ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 11.9, 10.5, 7.7 , 6.5 ],
          [20, 20  , 20  , 20  , 20  , 20  , 20  , 20  , 20  , 14.4, 6.9 , 4.9 , 3.7 ],
          [20, 18.0, 13.0, 13.3, 17.5, 20  , 20  , 20  , 20  , 18.8, 10.1, 2.7 , 2.5 ],
          [20, 16.1, 10.3, 8.5 , 9.0 , 10.8, 14.7, 20  , 20  , 20  , 13.9, 2.5 , 2.1 ],
          [20, 15.1, 9.6 , 6.5 , 5.7 , 5.2 , 7.0 , 10.7, 20  , 20  , 16.3, 2.3 , 2.0 ],
          [20, 14.2, 8.9 , 6.0 , 4.1 , 3.5 , 3.0 , 2.6 , 2.4 , 20  , 20  , 2.4 , 2.0,],
          [20, 13.1, 7.9 , 5.4 , 3.8 , 2.7 , 2.3 , 2.1 , 2.0 , 2.1 , 20  , 2.2 , 1.8 ],
          [20, 12.2, 7.5 , 5.0 , 3.4 , 2.5 , 1.9 , 1.8 , 1.7 , 1.8 , 1.6 , 20  , 1.7 ],
          [20, 11.6, 7.0 , 4.6 , 2.9 , 2.2 , 1.8 , 1.6 , 1.5 , 1.5 , 1.4 , 1.4 ,20   ]
      ];

      var mult = 0;

      if (suited) {
        mult = data[max_rank][min_rank];
      } else {
        mult = data[min_rank][max_rank];
      }

      return Math.floor(mult * 2 * game_state.small_blind) - game_state.current_buy_in;

    } else {
      if ('AK'.indexOf(cards[0].rank) != -1 && 'AK'.indexOf(cards[1].rank) != -1) {
        return all_in;
      }

      if (cards[0].rank == cards[1].rank) {
        return all_in;
      }

      if (cards[0].suit == cards[1].suit &&
          Math.abs(cardValue(cards[0]) - cardValue(cards[1])) == 1)
      {
        return all_in;
      }

      if ((game_state.in_action + 2) % 4 == player.dealer &&
          (game_state.pot < 8 * game_state.small_blind || game_state.pot < 300))
      {
        return all_in;
      }

      if (Math.random() < 0.1) {
        return all_in;
      }
    }

    return 0;
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>var util = require('util'),
    oneDay = 86400;

module.exports = function (connectOrSession) {
    var Store;
    var existingColumnFamilyException = 'Cannot add already existing column family';

    if (connectOrSession.session && connectOrSession.session.Store) {
        // Express 3
        Store = connectOrSession.session.Store;
    } else if (connectOrSession.Store) {
        // Express 4
        Store = connectOrSession.Store;
    } else {
        throw new Error('The supplied parameter is neither Express3 object or Express4 session object.');
    }

    /**
     * Initialize CassandraCqlStore with the given `options`.
     *
     * @param {Object} options
     * @api public
     */
    function CassandraCqlStore(options) {
        Store.call(this, options);

        this.table = options.table || 'connect_session';
        this.ttl = options.ttl;
        this.client = options.client;
        this.readConsistency = options.readConsistency || 1;
        this.writeConsistency = options.writeConsistency || 0;

        var cql = util.format('CREATE TABLE %s (sid text PRIMARY KEY, session text)', this.table);

        this.client.execute(cql, function (err) {
            if (err && err.message.indexOf(existingColumnFamilyException) === -1) {

                // Some kind of error have occurred while trying to connect to cassandra
                throw err;
            }
        });

        this.getSession = util.format('SELECT session FROM %s WHERE sid = ?', this.table);
        this.deleteSession = util.format('DELETE FROM %s WHERE sid = ?', this.table);
    }

    /**
     * Inherit from `Store`.
     */
    CassandraCqlStore.prototype.__proto__ = Store.prototype;

    /**
     * Attempt to fetch session by the given `sid`.
     *
     * @param {String} sid
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.get = function (sid, callback) {
        this.client.executeAsPrepared(this.getSession, [sid], this.readConsistency, function (err, result) {
            if (err) {
                return callback(err);
            }

            if (!result || !result.rows || result.rows.length !== 1) {

                // Session not found
                return callback();
            }

            var session = result.rows[0].get('session');
            if (!session) {
                return callback();
            }

            return callback(null, JSON.parse(session));
        });
    };

    /**
     * Persist the given `session` object associated with the given `sid`.
     *
     * @param {String} sid
     * @param {Session} session
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.set = function (sid, session, callback) {
        var maxAge = session.cookie.maxAge,
            ttl = this.ttl || ('number' === typeof maxAge ? maxAge / 1000 | 0 : oneDay),
            cql = util.format('UPDATE %s USING TTL %d SET session = ? WHERE sid = ?', this.table, ttl);

        this.client.executeAsPrepared(cql, [JSON.stringify(session), sid], this.writeConsistency, callback);
    };

    /**
     * Destroy the session associated with the given `sid`.
     *
     * @param {String} sid
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.destroy = function (sid, callback) {
        this.client.executeAsPrepared(this.deleteSession, [sid], this.writeConsistency, callback);
    };

    return CassandraCqlStore;
};<commit_msg>Replace deprecated client.executeAsPrepared  with client.execute<commit_after>var util = require('util'),
    oneDay = 86400;

module.exports = function (connectOrSession) {
    var Store;
    var existingColumnFamilyException = 'Cannot add already existing column family';

    if (connectOrSession.session && connectOrSession.session.Store) {
        // Express 3
        Store = connectOrSession.session.Store;
    } else if (connectOrSession.Store) {
        // Express 4
        Store = connectOrSession.Store;
    } else {
        throw new Error('The supplied parameter is neither Express3 object or Express4 session object.');
    }

    /**
     * Initialize CassandraCqlStore with the given `options`.
     *
     * @param {Object} options
     * @api public
     */
    function CassandraCqlStore(options) {
        Store.call(this, options);

        this.table = options.table || 'connect_session';
        this.ttl = options.ttl;
        this.client = options.client;
        this.readConsistency = options.readConsistency || 1;
        this.writeConsistency = options.writeConsistency || 0;

        var cql = util.format('CREATE TABLE %s (sid text PRIMARY KEY, session text)', this.table);

        this.client.execute(cql, function (err) {
            if (err && err.message.indexOf(existingColumnFamilyException) === -1) {

                // Some kind of error have occurred while trying to connect to cassandra
                throw err;
            }
        });

        this.getSession = util.format('SELECT session FROM %s WHERE sid = ?', this.table);
        this.deleteSession = util.format('DELETE FROM %s WHERE sid = ?', this.table);
    }

    /**
     * Inherit from `Store`.
     */
    CassandraCqlStore.prototype.__proto__ = Store.prototype;

    /**
     * Attempt to fetch session by the given `sid`.
     *
     * @param {String} sid
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.get = function (sid, callback) {
        this.client.execute(this.getSession, [sid], this.readConsistency, function (err, result) {
            if (err) {
                return callback(err);
            }

            if (!result || !result.rows || result.rows.length !== 1) {

                // Session not found
                return callback();
            }

            var session = result.rows[0].get('session');
            if (!session) {
                return callback();
            }

            return callback(null, JSON.parse(session));
        });
    };

    /**
     * Persist the given `session` object associated with the given `sid`.
     *
     * @param {String} sid
     * @param {Session} session
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.set = function (sid, session, callback) {
        var maxAge = session.cookie.maxAge,
            ttl = this.ttl || ('number' === typeof maxAge ? maxAge / 1000 | 0 : oneDay),
            cql = util.format('UPDATE %s USING TTL %d SET session = ? WHERE sid = ?', this.table, ttl);

        this.client.execute(cql, [JSON.stringify(session), sid], this.writeConsistency, callback);
    };

    /**
     * Destroy the session associated with the given `sid`.
     *
     * @param {String} sid
     * @param {Function} callback
     * @api public
     */
    CassandraCqlStore.prototype.destroy = function (sid, callback) {
        this.client.execute(this.deleteSession, [sid], this.writeConsistency, callback);
    };

    return CassandraCqlStore;
};
<|endoftext|>


<commit_before>var [
    /*-1 */COMMENT,
    /* 0 */SPACE,
    /* 1 */STRAP,
    /* 2 */STAMP,
    /* 3 */VALUE,
    /* 4 */QUOTED,
    /* 5 */PIECE,
    /* 6 */EXPRESS,
    /* 7 */SCOPED,
] = new Array(20).fill(0).map((_, a) => a - 1);

class Program extends Array {
    COMMENT = COMMENT
    SPACE = SPACE
    STAMP = STRAP
    STAMP = STAMP
    VALUE = VALUE
    QUOTED = QUOTED
    PIECE = PIECE
    EXPRESS = EXPRESS
    SCOPED = SCOPED
    toString() {
        var lasttype;
        var result = [];
        var run = function (o) {
            switch (o.type) {
                case QUOTED:
                    if (!o.length) {
                        result.push(o.text);
                        break;
                    }
                case SCOPED:
                    result.push(o.entry);
                    o.forEach(run);
                    result.push(o.leave);
                    break;
                default:
                    if ([STRAP, EXPRESS, VALUE].indexOf(lasttype) >= 0 && [STRAP, EXPRESS, VALUE].indexOf(o.type) >= 0) result.push(" ");
                    if (o instanceof Object) {
                        result.push(o.text);
                    }
                    else {
                        result.push(o);
                    }
            }
            lasttype = o.type;
        };
        this.forEach(run);
        return result.join("");
    }
}

class Javascript {
    quotes = [
        [/'/, /'/, /\\[\s\S]/],
        [/"/, /"/, /\\[\s\S]/],
        ["/", /\/[imgyu]*/, /\\[\s\S]|\[(\\[\s\S]|[^\]])+\]/],
        ["`", "`", /\\[\s\S]/, ["${", "}"]],
    ]
    comments = [
        ["//", /(?=[\r\n\u2028\u2029])/],
        ["/*", "*/"],
    ]
    scopes = [
        ["(", ")"],
        ["[", "]"],
        ["{", "}"],
    ]
    stamps = "/=+;|:?<>-!~@#%^&*,".split("")
    value_reg = /^(false|true|null|Infinity|NaN|undefined|arguments|this)$/
    transive = /^(new|void|in|typeof|delete|case|return|await|export|default|instanceof|throw|extends)$/
    straps = `if,in,do
    var,for,new,try,let
    else,case,void,with,enum,from
    async,while,break,catch,throw,const,yield,class,await
    return,typeof,delete,switch,export,import
    default,finally,extends
    function,continue,debugger
    instanceof`.trim().split(/[\r\n,\s]+/)
    spaces = ["\\u00a0", " ", "\\t", "\\v", "\\b", "\\r", "\\n", "\\u2028", "\\u2029", "\\u3000"]
    nocase = false
    lastIndex = 0
    compile(s) {
        return s.replace(/\\[\s\S]|[\[\]\(\)\{\}\+\-\*\?\:\$\^\!\|\>\<\\\/]/g, function (m) {
            if (m.length > 1) {
                return m;
            }
            return "\\" + m;
        });
    }
    createRegExp(source, g) {
        source = source.map(s => s instanceof RegExp ? s.source : this.compile(s));
        var flag = this.nocase ? "i" : "";
        var s = source.join("|");
        if (g) return new RegExp(`${s}`, "g" + flag);
        if (source.length > 1) return new RegExp(`^(${s})$`, flag);
        return new RegExp(`^${s}$`, flag);
    }

    exec(text) {
        if (!this.entry_reg) this.commit();
        var index = this.lastIndex;
        var parents = [];
        var lasttype;
        var queue = new Program;
        var save = function (type) {
            if (lasttype === STAMP && type === STAMP) {
                scope.end = end;
                scope.text = text.slice(scope.start, scope.end);
            }
            else {
                lasttype = type;
                queue.push({
                    type,
                    start,
                    end,
                    text: m
                });
            }
        };
        var get4uncomment = function (list) {
            var dist = [];
            for (var cx = list.length - 1; cx >= 0; cx--) {
                var u = list[cx];
                if (u.type === COMMENT || u.type === SPACE) continue;
                dist.unshift(u);
                if (dist.length >= 4) break;
            }
            return dist;
        };
        loop: while (index < text.length) {
            var reg = this.entry_reg;
            var start = reg.lastIndex = index;
            var match = reg.exec(text);
            if (!match) return null;
            var end = match[0].length + match.index;
            this.lastIndex = index = end;
            var m = match[0];
            var parent = parents[parents.length - 1];
            if (parent && this.quote_map[parent.entry] && queue.leave_map[m] === queue.entry) {
                delete queue.leave_map;
                queue.end = end;
                queue.leave = m;
                queue = parents.pop();
                continue;
            }
            test: if (this.quote_map.hasOwnProperty(m) || queue.type === QUOTED) {
                let list = get4uncomment(queue);
                if (queue.type !== QUOTED && this.stamp_reg.test(m) && list.length > 0) {
                    let last = list[list.length - 1];
                    if (last.type === VALUE || last.type === EXPRESS || last.type === QUOTED) break test;
                    let prev = list[list.length - 2];
                    if (last.type === SCOPED) switch (last.entry) {
                        case "[":
                            break;
                        case "{":
                            if (list.length < 2) {
                                if (!parents.length) break;
                                let parent = parents[parents.length - 1];
                                if (parent.entry === "(" || parent.entry === "[") break test;
                                break;
                            }
                            if (prev.type === STAMP) break test;
                            if (prev.type === STRAP) {
                                if (this.transive.test(prev.text)) break test;
                                break;
                            }
                            var prev2 = queue[queue.length - 2];
                            if (prev2.type === STAMP && prev2.text !== ";") {
                                break;
                            }
                            break;
                        case "(":
                            if (list.length < 2) break test;
                            if (prev.type === STRAP) {
                                if (/^(if|for|with|switch|while|catch)$/.test(prev.text)) break;
                            }
                            break test;
                    }
                }
                if (queue.type === QUOTED) {
                    var quote = this.quote_map[queue.entry];
                    var scope = {};
                    scope.type = PIECE;
                } else {
                    var scope = [];
                    var quote = this.quote_map[m];
                    scope.type = this.comment_entry.test(m) ? COMMENT : QUOTED;
                }
                scope.start = start;
                var reg = quote.reg;
                queue.push(scope);
                parents.push(queue);
                queue = scope;
                while (index < text.length) {
                    reg.lastIndex = index;
                    var match = reg.exec(text);
                    if (!match) {
                        index = text.length;
                        break;
                    }
                    var m1 = m;
                    var m = match[0];
                    index = this.lastIndex = match.index + m.length;
                    if (quote.length === 2) {
                        break;
                    }
                    if (quote.end.test(m)) {
                        break;
                    }
                    if (quote.length === 3) {
                        continue;
                    }
                    if (quote.length >= 4) {
                        var scope = [];
                        scope.entry = m;
                        scope.type = SCOPED;
                        scope.start = match.index;
                        scope.leave_map = quote.leave;
                        start = queue.start + queue.entry.length;
                        end = match.index;
                        m = text.slice(start, end);
                        save(PIECE);
                        queue.entry = m1;
                        queue.push(scope);
                        parents.push(queue);
                        queue = scope;
                        continue loop;
                    }
                }
                if (queue.type === PIECE) {
                    queue.text = text.slice(queue.start, match.index);
                    queue.end = match.index;
                    queue = parents.pop();
                    queue.leave = m;
                } else {
                    queue.end = index;
                    queue.text = text.slice(queue.start, index);
                }
                queue = parents.pop();
                continue;
            }
            if (this.space_reg.test(m)) {
                if (/^[\r\n\u2028\u2029]/.test(m)) {
                    m = m.replace(/\r\n|\r|\n/g, "\r\n");
                    save(SPACE);
                }
                lasttype = SPACE;
                continue;
            }
            if (this.strap_reg.test(m)) {
                save(STRAP);
                continue;
            }
            if (this.value_reg.test(m)) {
                save(VALUE);
                continue;
            }
            if (this.express_reg.test(m)) {
                save(EXPRESS);
                continue;
            }

            if (this.scope_entry[m]) {
                var scope = [];
                scope.entry = m;
                scope.type = SCOPED;
                queue.push(scope);
                parents.push(queue);
                queue = scope;
                scope.start = match.index;
                continue;
            }
            if (this.scope_leave[m] && queue.entry === this.scope_leave[m]) {
                queue.end = end;
                queue.leave = m;
                queue = parents.pop();
                continue;
            }

            if (this.stamp_reg.test(m)) {
                save(STAMP);
            }

        }
        return queue;
    }
    commit() {
        this.strap_reg = this.createRegExp(this.straps);
        this.comment_entry = this.createRegExp(this.comments.map(m => m[0]));
        var stamps = this.stamps.join("");
        stamps = this.compile(stamps);
        this.stamp_reg = new RegExp(`^[${stamps}]$`);
        var tokens = {};
        var quote_map = {};
        this.quote_map = quote_map;
        var quoteslike = this.comments.concat(this.quotes);
        quoteslike.forEach(q => {
            var a = q[0];
            if (a instanceof RegExp) a = a.source;
            if (a.length === 1) tokens[a] = true;
            var r = q.slice(2).concat(q[1]).map(q => {
                if (q instanceof Array) {
                    return this.compile(q[0]);
                }
                if (q instanceof RegExp) {
                    return q.source;
                }
                return this.compile(q);
            }).join("|");
            q.reg = new RegExp(r, 'g');
            q.end = this.createRegExp([q[1]]);
            if (q.length >= 4) {
                var map = q.entry = {};
                var end = q.leave = {};
                q.slice(3).forEach(k => {
                    var [a, b] = k;
                    map[a] = b;
                    end[b] = a;
                    tokens[b] = true;
                    tokens[a] = true;
                });
            }
            quote_map[a] = q;
        });
        var scope_entry = {};
        this.scope_entry = scope_entry;
        this.scope_leave = {};
        var scope_leave = this.scope_leave;
        this.scopes.forEach(s => {
            var [a, b] = s;
            scope_entry[a] = b;
            scope_leave[b] = a;
            tokens[a] = true;
            tokens[b] = true;
        });
        this.stamps.forEach(s => {
            tokens[s] = true;
        });
        this.spaces.forEach(s => {
            tokens[s] = true;
        });
        var keys = Object.keys(tokens).join("");
        keys = this.compile(keys);
        var express = `[^${keys}]+`;
        this.express_reg = new RegExp(`^${express}$`);
        var scopes = this.scopes.map(a => a.join("")).join("");
        scopes = this.compile(scopes);
        var spaces = this.spaces.join("");
        spaces = this.compile(spaces);
        this.space_reg = new RegExp(`^[${spaces}]+$`);
        var quotes = this.createRegExp(quoteslike.map(q => q[0]), true).source;
        this.entry_reg = new RegExp([`[${spaces}]+|${quotes}|[${scopes}]|${express}|[${stamps}]`], "g");
    }

}

var program = new Javascript;
function javascript(text, lastIndex = 0) {
    program.lastIndex = lastIndex;
    return program.exec(text);
}

function scan(text) {
    var res = javascript(text, 0);
    return res;
}

module.exports = scan;<commit_msg>修复一些问题<commit_after>var [
    /*-1 */COMMENT,
    /* 0 */SPACE,
    /* 1 */STRAP,
    /* 2 */STAMP,
    /* 3 */VALUE,
    /* 4 */QUOTED,
    /* 5 */PIECE,
    /* 6 */EXPRESS,
    /* 7 */SCOPED,
] = new Array(20).fill(0).map((_, a) => a - 1);

class Program extends Array {
    COMMENT = COMMENT
    SPACE = SPACE
    STAMP = STRAP
    STAMP = STAMP
    VALUE = VALUE
    QUOTED = QUOTED
    PIECE = PIECE
    EXPRESS = EXPRESS
    SCOPED = SCOPED
    toString() {
        var lasttype;
        var result = [];
        var run = function (o) {
            switch (o.type) {
                case QUOTED:
                    if (!o.length) {
                        result.push(o.text);
                        break;
                    }
                case SCOPED:
                    result.push(o.entry);
                    lasttype = SCOPED;
                    o.forEach(run);
                    result.push(o.leave);
                    break;
                default:
                    if ([STRAP, EXPRESS, VALUE].indexOf(lasttype) >= 0 && [STRAP, EXPRESS, VALUE].indexOf(o.type) >= 0) result.push(" ");
                    if (o instanceof Object) {
                        result.push(o.text);
                    }
                    else {
                        result.push(o);
                    }
            }
            lasttype = o.type;
        };
        this.forEach(run);
        return result.join("");
    }
}

class Javascript {
    quotes = [
        [/'/, /'/, /\\[\s\S]/],
        [/"/, /"/, /\\[\s\S]/],
        ["/", /\/[imgyu]*/, /\\[\s\S]|\[(\\[\s\S]|[^\]])+\]/],
        ["`", "`", /\\[\s\S]/, ["${", "}"]],
    ]
    comments = [
        ["//", /(?=[\r\n\u2028\u2029])/],
        ["/*", "*/"],
    ]
    scopes = [
        ["(", ")"],
        ["[", "]"],
        ["{", "}"],
    ]
    stamps = "/=+;|:?<>-!~@#%^&*,".split("")
    value_reg = /^(false|true|null|Infinity|NaN|undefined|arguments|this)$/
    transive = /^(new|void|in|typeof|delete|case|return|await|export|default|instanceof|throw|extends)$/
    straps = `if,in,do
    var,for,new,try,let
    else,case,void,with,enum,from
    async,while,break,catch,throw,const,yield,class,await
    return,typeof,delete,switch,export,import
    default,finally,extends
    function,continue,debugger
    instanceof`.trim().split(/[\r\n,\s]+/)
    spaces = ["\\u00a0", " ", "\\t", "\\v", "\\b", "\\r", "\\n", "\\u2028", "\\u2029", "\\u3000"]
    nocase = false
    lastIndex = 0
    compile(s) {
        return s.replace(/\\[\s\S]|[\[\]\(\)\{\}\+\-\*\?\:\$\^\!\|\>\<\\\/]/g, function (m) {
            if (m.length > 1) {
                return m;
            }
            return "\\" + m;
        });
    }
    createRegExp(source, g) {
        source = source.map(s => s instanceof RegExp ? s.source : this.compile(s));
        var flag = this.nocase ? "i" : "";
        var s = source.join("|");
        if (g) return new RegExp(`${s}`, "g" + flag);
        if (source.length > 1) return new RegExp(`^(${s})$`, flag);
        return new RegExp(`^${s}$`, flag);
    }

    exec(text) {
        if (!this.entry_reg) this.commit();
        var index = this.lastIndex;
        var parents = [];
        var lasttype;
        var queue = new Program;
        var save = function (type) {
            if (lasttype === STAMP && type === STAMP) {
                var scope = queue[queue.length - 1];
                scope.end = end;
                scope.text = text.slice(scope.start, scope.end);
            }
            else {
                lasttype = type;
                queue.push({
                    type,
                    start,
                    end,
                    text: m
                });
            }
        };
        var get4uncomment = function (list) {
            var dist = [];
            for (var cx = list.length - 1; cx >= 0; cx--) {
                var u = list[cx];
                if (u.type === COMMENT || u.type === SPACE) continue;
                dist.unshift(u);
                if (dist.length >= 4) break;
            }
            return dist;
        };
        loop: while (index < text.length) {
            var reg = this.entry_reg;
            var start = reg.lastIndex = index;
            var match = reg.exec(text);
            if (!match) return null;
            var end = match[0].length + match.index;
            this.lastIndex = index = end;
            var m = match[0];
            var parent = parents[parents.length - 1];
            if (parent && this.quote_map[parent.entry] && queue.leave_map[m] === queue.entry) {
                delete queue.leave_map;
                queue.end = end;
                queue.leave = m;
                queue = parents.pop();
                lasttype = queue.type;
                continue;
            }
            test: if (this.quote_map.hasOwnProperty(m) || queue.type === QUOTED) {
                let list = get4uncomment(queue);
                if (queue.type !== QUOTED && this.stamp_reg.test(m) && list.length > 0) {
                    let last = list[list.length - 1];
                    if (last.type === VALUE || last.type === EXPRESS || last.type === QUOTED) break test;
                    let prev = list[list.length - 2];
                    if (last.type === SCOPED) switch (last.entry) {
                        case "[":
                            break;
                        case "{":
                            if (list.length < 2) {
                                if (!parents.length) break;
                                let parent = parents[parents.length - 1];
                                if (parent.entry === "(" || parent.entry === "[") break test;
                                break;
                            }
                            if (prev.type === STAMP) break test;
                            if (prev.type === STRAP) {
                                if (this.transive.test(prev.text)) break test;
                                break;
                            }
                            var prev2 = queue[queue.length - 2];
                            if (prev2.type === STAMP && prev2.text !== ";") {
                                break;
                            }
                            break;
                        case "(":
                            if (list.length < 2) break test;
                            if (prev.type === STRAP) {
                                if (/^(if|for|with|switch|while|catch)$/.test(prev.text)) break;
                            }
                            break test;
                    }
                }
                if (queue.type === QUOTED) {
                    var quote = this.quote_map[queue.entry];
                    var scope = {};
                    scope.type = PIECE;
                } else {
                    var scope = [];
                    var quote = this.quote_map[m];
                    scope.type = this.comment_entry.test(m) ? COMMENT : QUOTED;
                }
                lasttype = scope.type;
                scope.start = start;
                var reg = quote.reg;
                queue.push(scope);
                parents.push(queue);
                queue = scope;
                while (index < text.length) {
                    reg.lastIndex = index;
                    var match = reg.exec(text);
                    if (!match) {
                        index = text.length;
                        break;
                    }
                    var m1 = m;
                    var m = match[0];
                    index = this.lastIndex = match.index + m.length;
                    if (quote.length === 2) {
                        break;
                    }
                    if (quote.end.test(m)) {
                        break;
                    }
                    if (quote.length === 3) {
                        continue;
                    }
                    if (quote.length >= 4) {
                        var scope = [];
                        scope.entry = m;
                        scope.type = SCOPED;
                        scope.start = match.index;
                        scope.leave_map = quote.leave;
                        start = queue.start + queue.entry.length;
                        end = match.index;
                        m = text.slice(start, end);
                        save(PIECE);
                        queue.entry = m1;
                        queue.push(scope);
                        parents.push(queue);
                        lasttype = scope.type;
                        queue = scope;
                        continue loop;
                    }
                }
                if (queue.type === PIECE) {
                    queue.text = text.slice(queue.start, match.index);
                    queue.end = match.index;
                    queue = parents.pop();
                    queue.leave = m;
                } else {
                    queue.end = index;
                    queue.text = text.slice(queue.start, index);
                }
                queue = parents.pop();
                lasttype = queue.type;
                continue;
            }
            if (this.space_reg.test(m)) {
                if (/^[\r\n\u2028\u2029]/.test(m)) {
                    m = m.replace(/\r\n|\r|\n/g, "\r\n");
                    save(SPACE);
                }
                lasttype = SPACE;
                continue;
            }
            if (this.strap_reg.test(m)) {
                save(STRAP);
                continue;
            }
            if (this.value_reg.test(m)) {
                save(VALUE);
                continue;
            }
            if (this.express_reg.test(m)) {
                save(EXPRESS);
                continue;
            }

            if (this.scope_entry[m]) {
                var scope = [];
                scope.entry = m;
                scope.type = SCOPED;
                queue.push(scope);
                parents.push(queue);
                queue = scope;
                scope.start = match.index;
                lasttype = scope.type;
                continue;
            }
            if (this.scope_leave[m] && queue.entry === this.scope_leave[m]) {
                queue.end = end;
                queue.leave = m;
                queue = parents.pop();
                lasttype = queue.type;
                continue;
            }

            if (this.stamp_reg.test(m)) {
                save(STAMP);
            }

        }
        return queue;
    }
    commit() {
        this.strap_reg = this.createRegExp(this.straps);
        this.comment_entry = this.createRegExp(this.comments.map(m => m[0]));
        var stamps = this.stamps.join("");
        stamps = this.compile(stamps);
        this.stamp_reg = new RegExp(`^[${stamps}]$`);
        var tokens = {};
        var quote_map = {};
        this.quote_map = quote_map;
        var quoteslike = this.comments.concat(this.quotes);
        quoteslike.forEach(q => {
            var a = q[0];
            if (a instanceof RegExp) a = a.source;
            if (a.length === 1) tokens[a] = true;
            var r = q.slice(2).concat(q[1]).map(q => {
                if (q instanceof Array) {
                    return this.compile(q[0]);
                }
                if (q instanceof RegExp) {
                    return q.source;
                }
                return this.compile(q);
            }).join("|");
            q.reg = new RegExp(r, 'g');
            q.end = this.createRegExp([q[1]]);
            if (q.length >= 4) {
                var map = q.entry = {};
                var end = q.leave = {};
                q.slice(3).forEach(k => {
                    var [a, b] = k;
                    map[a] = b;
                    end[b] = a;
                    tokens[b] = true;
                    tokens[a] = true;
                });
            }
            quote_map[a] = q;
        });
        var scope_entry = {};
        this.scope_entry = scope_entry;
        this.scope_leave = {};
        var scope_leave = this.scope_leave;
        this.scopes.forEach(s => {
            var [a, b] = s;
            scope_entry[a] = b;
            scope_leave[b] = a;
            tokens[a] = true;
            tokens[b] = true;
        });
        this.stamps.forEach(s => {
            tokens[s] = true;
        });
        this.spaces.forEach(s => {
            tokens[s] = true;
        });
        var keys = Object.keys(tokens).join("");
        keys = this.compile(keys);
        var express = `[^${keys}]+`;
        this.express_reg = new RegExp(`^${express}$`);
        var scopes = this.scopes.map(a => a.join("")).join("");
        scopes = this.compile(scopes);
        var spaces = this.spaces.join("");
        spaces = this.compile(spaces);
        this.space_reg = new RegExp(`^[${spaces}]+$`);
        var quotes = this.createRegExp(quoteslike.map(q => q[0]), true).source;
        this.entry_reg = new RegExp([`[${spaces}]+|${quotes}|[${scopes}]|${express}|[${stamps}]`], "g");
    }

}

var program = new Javascript;
function javascript(text, lastIndex = 0) {
    program.lastIndex = lastIndex;
    return program.exec(text);
}

function scan(text) {
    var res = javascript(text, 0);
    return res;
}

module.exports = scan;<|endoftext|>


<commit_before>/*global define*/
/*global Markdown*/
define([
    'underscore',
    'app',
    'backbone',
    'text!apps/notes/show/templates/item.html',
    'checklist',
    'tags',
    'prettify',
    'backbone.mousetrap', 'marionette',
    'pagedown-extra'
], function (_, App, Backbone, Template, Checklist, Tags, prettify) {
    'use strict';

    var View = Backbone.Marionette.ItemView.extend({
        template: _.template(Template),

        className: 'content-notes',

        ui: {
            editBtn  : '.btn-edit',
            favorite : '.favorite span',
            progress : '.progress-bar',
            percent  : '.progress-percent',
            notebook : '.notebook-name'
        },

        events: {
            'click #restoreNote'  : 'restoreFromTrash',
            'click .favorite'  : 'favorite',
            'click .task [type="checkbox"]': 'toggleTask',
            'click .btn-toggle-sidebar': 'toggleSidebar'
        },

        keyboardEvents: {
            'up'   : 'scrollTop',
            'down' : 'scrollDown'
        },

        initialize: function() {
            // Setting shortcuts
            var configs = App.settings;
            this.keyboardEvents[configs.actionsEdit] = 'editNote';
            this.keyboardEvents[configs.actionsRotateStar] = 'favorite';
            this.keyboardEvents[configs.actionsRemove] = 'deleteNote';

            // Model events
            this.listenTo(this.model, 'change:isFavorite', this.changeFavorite);
            this.listenTo(this.model, 'change:taskCompleted', this.taskProgress, this);
        },

        onRender: function () {
            // Google code prettify
            var code = null;
            this.$('pre').addClass('prettyprint').each(function (idx, el) {
                code = el.firstChild;
                code.innerHTML = prettify.prettyPrintOne(code.innerHTML);
            });

            // Make table look good
            this.$('table').addClass('table table-bordered');
        },

        /**
         * Decrypt content and title
         */
        serializeData: function () {
            var data = _.extend(this.model.toJSON(), this.options.decrypted),
                converter;

            // Convert from markdown to HTML
            // converter = Markdown.getSanitizingConverter();
            converter = new Markdown.Converter();
            Markdown.Extra.init(converter);

            // Customize markdown converter
            converter.hooks.chain('postNormalization', function (text) {
                text = new Checklist().toHtml(text);
                return new Tags().toHtml(text);
            });

            data.content = converter.makeHtml(data.content);
            data.title = converter.makeHtml(data.title);
            data.notebook = App.Encryption.API.decrypt(data.notebook);

            // Show title
            document.title = data.title;
            return data;
        },

        restoreFromTrash: function (e) {
            e.preventDefault();
            this.model.save({'trash': 0});
            App.navigateBack();
        },

        changeFocus: function () {
            this.model.trigger('changeFocus');
        },

        changeFavorite: function () {
            var sidebar = $('#note-' + this.model.get('id') + ' .favorite');
            if (this.model.get('isFavorite') === 1) {
                this.ui.favorite.removeClass('icon-star-empty');
                sidebar.removeClass('icon-star-empty');
            } else {
                this.ui.favorite.addClass('icon-star-empty');
                sidebar.addClass('icon-star-empty');
            }
        },

        /**
         * Add note item to your favorite notes list
         */
        favorite: function () {
            var isFavorite = (this.model.get('isFavorite') === 1) ? 0 : 1;
            this.model.trigger('update:any');
            this.model.save({'isFavorite': isFavorite});
            return false;
        },

        /**
         * Redirect to edit page
         */
        editNote: function () {
            var uri = this.ui.editBtn.attr('href');
            App.navigate(uri);
        },

        /**
         * Redirect to deleting page
         */
        deleteNote: function() {
            App.navigate('/notes/remove/' + this.model.get('id'), true);
        },

        /**
         * Toggle task status
         */
        toggleTask: function (e) {
            var task = $(e.target),
                taskId = parseInt(task.attr('data-task'), null),
                content = App.Encryption.API.decrypt(this.model.get('content')),
                text = new Checklist().toggle(content, taskId);

            // Save result
            this.model.trigger('updateTaskProgress', text);
        },

        /**
         * Shows percentage of completed tasks
         */
        taskProgress: function () {
            var percent = Math.floor(this.model.get('taskCompleted') * 100 / this.model.get('taskAll'));
            this.ui.progress.css({width: percent + '%'}, this.render, this);
            this.ui.percent.html(percent + '%');
        },

        /**
         * Scroll page to top when user hits up button
         */
        scrollTop: function () {
            var Top = this.$('.ui-body').scrollTop();
            this.$('.ui-body').scrollTop(Top - 50);
        },

        /**
         * Scroll page down when user hits down button
         */
        scrollDown: function () {
            var Top = this.$('.ui-body').scrollTop();
            this.$('.ui-body').scrollTop(Top + 50);
        },

        /**
         * Show sidebar
         */
        toggleSidebar: function (e) {
            e.preventDefault();
            App.navigate('/notes/p1', {trigger: false});
            App.trigger('notes:toggle', this.options.args);
        },

        templateHelpers: function() {
            return {
                i18n: $.t,

                getProgress: function() {
                    return Math.floor(this.taskCompleted * 100 / this.taskAll);
                },

                getContent: function() {
                    return this.content;
                },

                createdDate: function() {
                    return new Date(this.created).toLocaleDateString();
                }
            };
        }

    });

    return View;
});
<commit_msg>issue #22: HTML tags in title<commit_after>/*global define*/
/*global Markdown*/
define([
    'underscore',
    'app',
    'backbone',
    'text!apps/notes/show/templates/item.html',
    'checklist',
    'tags',
    'prettify',
    'backbone.mousetrap', 'marionette',
    'pagedown-extra'
], function (_, App, Backbone, Template, Checklist, Tags, prettify) {
    'use strict';

    var View = Backbone.Marionette.ItemView.extend({
        template: _.template(Template),

        className: 'content-notes',

        ui: {
            editBtn  : '.btn-edit',
            favorite : '.favorite span',
            progress : '.progress-bar',
            percent  : '.progress-percent',
            notebook : '.notebook-name'
        },

        events: {
            'click #restoreNote'  : 'restoreFromTrash',
            'click .favorite'  : 'favorite',
            'click .task [type="checkbox"]': 'toggleTask',
            'click .btn-toggle-sidebar': 'toggleSidebar'
        },

        keyboardEvents: {
            'up'   : 'scrollTop',
            'down' : 'scrollDown'
        },

        initialize: function() {
            // Setting shortcuts
            var configs = App.settings;
            this.keyboardEvents[configs.actionsEdit] = 'editNote';
            this.keyboardEvents[configs.actionsRotateStar] = 'favorite';
            this.keyboardEvents[configs.actionsRemove] = 'deleteNote';

            // Model events
            this.listenTo(this.model, 'change:isFavorite', this.changeFavorite);
            this.listenTo(this.model, 'change:taskCompleted', this.taskProgress, this);
        },

        onRender: function () {
            // Google code prettify
            var code = null;
            this.$('pre').addClass('prettyprint').each(function (idx, el) {
                code = el.firstChild;
                code.innerHTML = prettify.prettyPrintOne(code.innerHTML);
            });

            // Make table look good
            this.$('table').addClass('table table-bordered');
        },

        /**
         * Decrypt content and title
         */
        serializeData: function () {
            var data = _.extend(this.model.toJSON(), this.options.decrypted),
                converter;

            // Convert from markdown to HTML
            // converter = Markdown.getSanitizingConverter();
            converter = new Markdown.Converter();
            Markdown.Extra.init(converter);

            // Customize markdown converter
            converter.hooks.chain('postNormalization', function (text) {
                text = new Checklist().toHtml(text);
                return new Tags().toHtml(text);
            });

            data.content = converter.makeHtml(data.content);
            data.notebook = App.Encryption.API.decrypt(data.notebook);

            // Show title
            document.title = data.title;

            data.title = converter.makeHtml(data.title);
            return data;
        },

        restoreFromTrash: function (e) {
            e.preventDefault();
            this.model.save({'trash': 0});
            App.navigateBack();
        },

        changeFocus: function () {
            this.model.trigger('changeFocus');
        },

        changeFavorite: function () {
            var sidebar = $('#note-' + this.model.get('id') + ' .favorite');
            if (this.model.get('isFavorite') === 1) {
                this.ui.favorite.removeClass('icon-star-empty');
                sidebar.removeClass('icon-star-empty');
            } else {
                this.ui.favorite.addClass('icon-star-empty');
                sidebar.addClass('icon-star-empty');
            }
        },

        /**
         * Add note item to your favorite notes list
         */
        favorite: function () {
            var isFavorite = (this.model.get('isFavorite') === 1) ? 0 : 1;
            this.model.trigger('update:any');
            this.model.save({'isFavorite': isFavorite});
            return false;
        },

        /**
         * Redirect to edit page
         */
        editNote: function () {
            var uri = this.ui.editBtn.attr('href');
            App.navigate(uri);
        },

        /**
         * Redirect to deleting page
         */
        deleteNote: function() {
            App.navigate('/notes/remove/' + this.model.get('id'), true);
        },

        /**
         * Toggle task status
         */
        toggleTask: function (e) {
            var task = $(e.target),
                taskId = parseInt(task.attr('data-task'), null),
                content = App.Encryption.API.decrypt(this.model.get('content')),
                text = new Checklist().toggle(content, taskId);

            // Save result
            this.model.trigger('updateTaskProgress', text);
        },

        /**
         * Shows percentage of completed tasks
         */
        taskProgress: function () {
            var percent = Math.floor(this.model.get('taskCompleted') * 100 / this.model.get('taskAll'));
            this.ui.progress.css({width: percent + '%'}, this.render, this);
            this.ui.percent.html(percent + '%');
        },

        /**
         * Scroll page to top when user hits up button
         */
        scrollTop: function () {
            var Top = this.$('.ui-body').scrollTop();
            this.$('.ui-body').scrollTop(Top - 50);
        },

        /**
         * Scroll page down when user hits down button
         */
        scrollDown: function () {
            var Top = this.$('.ui-body').scrollTop();
            this.$('.ui-body').scrollTop(Top + 50);
        },

        /**
         * Show sidebar
         */
        toggleSidebar: function (e) {
            e.preventDefault();
            App.navigate('/notes/p1', {trigger: false});
            App.trigger('notes:toggle', this.options.args);
        },

        templateHelpers: function() {
            return {
                i18n: $.t,

                getProgress: function() {
                    return Math.floor(this.taskCompleted * 100 / this.taskAll);
                },

                getContent: function() {
                    return this.content;
                },

                createdDate: function() {
                    return new Date(this.created).toLocaleDateString();
                }
            };
        }

    });

    return View;
});
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.5.3-zzz.6";
}
<commit_msg>Update version string to 2.5.3-zzz.7<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.5.3-zzz.7";
}
<|endoftext|>


<commit_before>function load_songs(textarea) {
    var encoded_uri = textarea.value;
    var decoded = decodeURIComponent(encoded_uri);
    var without_protocol = decoded.replace("irealb://", "");
    var unsplitted = without_protocol.split("==0=0===");
    for(i in unsplitted) {
        song = unsplitted[i].split("=");
        title = song[0];
        author = song[1];
        localStorage[title + " (" + author + ")"] = unsplitted[i]
    }
}
function swap(splitted, i, j) {
    tmp = splitted[i];
    splitted[i] = splitted[j];
    splitted[j] = tmp;
}
function mirror_swap(str, start, size) {
    var splitted = str.split('');
    var count = Math.floor(size / 2);
    for(var i = 0; i < count; i++) {
        swap(splitted, start + i, size + start - i);
    }
    return splitted.join("");
}
function unwarble(warbled) {
    var unwarbled = warbled.replace('1r34LbKcu7', '');
    for(var i = 0; i + 51 < unwarbled.length; i += 50) {
        unwarbled = mirror_swap(mirror_swap(mirror_swap(unwarbled, i + 10, 29), i + 5, 39), i, 49)
    }
    return unwarbled.replace(/XyQ/g, "   ").replace(/Kcl/g, "| x").replace(/LZ/g, "|");
}
function get_sheet(unwarbled) {
    unwarbled = unwarbled.replace(/\*([ABC])/g, "$1");
    unwarbled = unwarbled.replace(/\[/g, " ");
    unwarbled = unwarbled.replace(/T(.)(.)/g, "$1$1");
    unwarbled = unwarbled.replace(/\^/g, "Δ");
    var splitted = unwarbled.split('');
    var open_div = "
";
    var close_div = "
";
    var open_span = "";
    var close_span = "";
    var out = open_div + open_span;
    var bars = 0;
    for(i = 0; i < splitted.length; i++) {
        var c = splitted[i];
        var add = "";
        if(c == "|") {
            c = close_span;
            bars += 1;
            if(bars < 4)
            {
                c += open_span
            }
        }
        else { if(c == "x") { c = "%"; } }
        if(bars == 4 || c == '}' || c == ']') {
            bars = 0;
            add = close_div + open_div + open_span;
        }
        out += c + add;
    }
    return out + close_span + close_div;
}
function line_to_mma_chords(line) {
    var chords = line.split(" ");
    if(chords.length == 2) {
        chords = [chords[0], "/", chords[1]];
    }
    return chords.join(" ");
}
function play_mma(mma) {
  var worker = new Worker("//rawgit.com/yazgoo/pypyjs-mma/master/worker.js")
  worker.postMessage([mma]);
  console.log('Message posted to worker');
  worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(btoa(e.data));
    data = e.data
      console.log("playing " + data);
    play(data);
  }
}
function play_song(unwarbled) {
    var previous = "";
    unwarbled = unwarbled.replace(/T../, '?Groove Swing\n')
        .replace(/\{/g, "\n?Repeat\n").replace(/}/g, "\n?RepeatEnd\n")
        .replace(/\*./g, "").replace(/N1/g, "\n?RepeatEnding\\2\n").replace("][", "")
        .replace("[", "\n")
        .replace(/N2/g, "").replace("Z", "").replace(/s/g, " ").replace(/,/g, " ")
        .replace(/-/g, "m").replace(/\^/g, "M").replace(/h/g, "dim")
        .replace(/\|/g, "\n").replace(/\]\[/g, "\n").replace(/\[/, "\n")
        .replace(/l/g, "\n").replace(/x/g, "").replace("/\([^\)]*\)/, "")
    splitted = unwarbled.split("\n");
    var previous = "";
    k = 0;
    for(var i = 0; i < splitted.length; i++) {
        var line = splitted[i];
        if(line.length == 0 || line[0] == '?') previous += line.replace(/\?/g, "")
        else {
            previous += "" + k + " " + line_to_mma_chords(line);
            k += 1;
        }
        previous += "\n";
    }
    console.log(previous);
    play_mma(previous);
}
function show_song(title) {
    var song = localStorage[title];
    localStorage["last_song"] = song;
    var splitted = song.split("=");
    var title = splitted[0];
    var author = splitted[1];
    var unwarbled = unwarble(splitted[6]);
    set_content(""+title+" ("+author+")"
            + "<input type=button value='>' onclick=\"play_song('"+unwarbled+"')\"/>

"
            + get_sheet(unwarbled));
}
var songs_list_written;
var songs_list_div;
function add_songs_list() {
  var i;
  s = ""
    for(i = songs_list_written; i < (songs_list_written + 100) && i < localStorage.length; i++) {
        var title = localStorage.key(i);
        s += "" + title  + "
";
    }
  songs_list_div.innerHTML += s;
    songs_list_written += 100;
    if(i < localStorage.length) setTimeout(add_songs_list(), 500);
}
function show_songs_list(div) {
    songs_list_div = div;
    div.innerHTML = "";
    songs_list_written = 0;
    add_songs_list();
}
function set_content(str) {
    var content = document.getElementById("content");
    content.innerHTML = str;
}
function show_imports() {
    set_content("<input type=text onchange='load_songs(this)'/>");
}
function show_about() {
    set_content('Mooche is free software (as in freedom).
'
            +'This means it guarantees 4 fundamentals rights:
'
            +'
'
            +'
Freedom 0: The freedom to run the program for any purpose.
'
            +'
Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.
'
            +'
Freedom 2: The freedom to redistribute and make copies so you can help your neighbor.
'
            +'
Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in general) to the public, so that the whole community benefits.
'
            +'
'
            +'')
}
function show_songs() {
    show_songs_list(document.getElementById('content'));
}
function show_songs_or_last_song() {
    if(localStorage["last_song"] != null) {
        show_song("last_song");
    }
    else {
        show_songs();
    }
}

<commit_msg>ignoring parantheses<commit_after>function load_songs(textarea) {
    var encoded_uri = textarea.value;
    var decoded = decodeURIComponent(encoded_uri);
    var without_protocol = decoded.replace("irealb://", "");
    var unsplitted = without_protocol.split("==0=0===");
    for(i in unsplitted) {
        song = unsplitted[i].split("=");
        title = song[0];
        author = song[1];
        localStorage[title + " (" + author + ")"] = unsplitted[i]
    }
}
function swap(splitted, i, j) {
    tmp = splitted[i];
    splitted[i] = splitted[j];
    splitted[j] = tmp;
}
function mirror_swap(str, start, size) {
    var splitted = str.split('');
    var count = Math.floor(size / 2);
    for(var i = 0; i < count; i++) {
        swap(splitted, start + i, size + start - i);
    }
    return splitted.join("");
}
function unwarble(warbled) {
    var unwarbled = warbled.replace('1r34LbKcu7', '');
    for(var i = 0; i + 51 < unwarbled.length; i += 50) {
        unwarbled = mirror_swap(mirror_swap(mirror_swap(unwarbled, i + 10, 29), i + 5, 39), i, 49)
    }
    return unwarbled.replace(/XyQ/g, "   ").replace(/Kcl/g, "| x").replace(/LZ/g, "|");
}
function get_sheet(unwarbled) {
    unwarbled = unwarbled.replace(/\*([ABC])/g, "$1");
    unwarbled = unwarbled.replace(/\[/g, " ");
    unwarbled = unwarbled.replace(/T(.)(.)/g, "$1$1");
    unwarbled = unwarbled.replace(/\^/g, "Δ");
    var splitted = unwarbled.split('');
    var open_div = "
";
    var close_div = "
";
    var open_span = "";
    var close_span = "";
    var out = open_div + open_span;
    var bars = 0;
    for(i = 0; i < splitted.length; i++) {
        var c = splitted[i];
        var add = "";
        if(c == "|") {
            c = close_span;
            bars += 1;
            if(bars < 4)
            {
                c += open_span
            }
        }
        else { if(c == "x") { c = "%"; } }
        if(bars == 4 || c == '}' || c == ']') {
            bars = 0;
            add = close_div + open_div + open_span;
        }
        out += c + add;
    }
    return out + close_span + close_div;
}
function line_to_mma_chords(line) {
    var chords = line.split(" ");
    if(chords.length == 2) {
        chords = [chords[0], "/", chords[1]];
    }
    return chords.join(" ");
}
function play_mma(mma) {
  var worker = new Worker("//rawgit.com/yazgoo/pypyjs-mma/master/worker.js")
  worker.postMessage([mma]);
  console.log('Message posted to worker');
  worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(btoa(e.data));
    data = e.data
      console.log("playing " + data);
    play(data);
  }
}
function play_song(unwarbled) {
    var previous = "";
    unwarbled = unwarbled.replace(/T../, '?Groove Swing\n')
        .replace(/\{/g, "\n?Repeat\n").replace(/}/g, "\n?RepeatEnd\n")
        .replace(/\*./g, "").replace(/N1/g, "\n?RepeatEnding\\2\n").replace("][", "")
        .replace("[", "\n")
        .replace(/N2/g, "").replace("Z", "").replace(/s/g, " ").replace(/,/g, " ")
        .replace(/-/g, "m").replace(/\^/g, "M").replace(/h/g, "dim")
        .replace(/\|/g, "\n").replace(/\]\[/g, "\n").replace(/\[/, "\n")
        .replace(/l/g, "\n").replace(/x/g, "").replace(/\([^\)]*\)/g, "")/* lets ignore stuff under () for now*/
    splitted = unwarbled.split("\n");
    var previous = "";
    k = 0;
    for(var i = 0; i < splitted.length; i++) {
        var line = splitted[i];
        if(line.length == 0 || line[0] == '?') previous += line.replace(/\?/g, "")
        else {
            previous += "" + k + " " + line_to_mma_chords(line);
            k += 1;
        }
        previous += "\n";
    }
    console.log(previous);
    play_mma(previous);
}
function show_song(title) {
    var song = localStorage[title];
    localStorage["last_song"] = song;
    var splitted = song.split("=");
    var title = splitted[0];
    var author = splitted[1];
    var unwarbled = unwarble(splitted[6]);
    set_content(""+title+" ("+author+")"
            + "<input type=button value='>' onclick=\"play_song('"+unwarbled+"')\"/>

"
            + get_sheet(unwarbled));
}
var songs_list_written;
var songs_list_div;
function add_songs_list() {
  var i;
  s = ""
    for(i = songs_list_written; i < (songs_list_written + 100) && i < localStorage.length; i++) {
        var title = localStorage.key(i);
        s += "" + title  + "
";
    }
  songs_list_div.innerHTML += s;
    songs_list_written += 100;
    if(i < localStorage.length) setTimeout(add_songs_list(), 500);
}
function show_songs_list(div) {
    songs_list_div = div;
    div.innerHTML = "";
    songs_list_written = 0;
    add_songs_list();
}
function set_content(str) {
    var content = document.getElementById("content");
    content.innerHTML = str;
}
function show_imports() {
    set_content("<input type=text onchange='load_songs(this)'/>");
}
function show_about() {
    set_content('Mooche is free software (as in freedom).
'
            +'This means it guarantees 4 fundamentals rights:
'
            +'
'
            +'
Freedom 0: The freedom to run the program for any purpose.
'
            +'
Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.
'
            +'
Freedom 2: The freedom to redistribute and make copies so you can help your neighbor.
'
            +'
Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in general) to the public, so that the whole community benefits.
'
            +'
'
            +'')
}
function show_songs() {
    show_songs_list(document.getElementById('content'));
}
function show_songs_or_last_song() {
    if(localStorage["last_song"] != null) {
        show_song("last_song");
    }
    else {
        show_songs();
    }
}

<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    var hand;
    var in_action = game_state.in_action;
    var goodStartingHand = ['10', 'J', 'K', 'Q', 'A'];
    hand.push(game_state.players[0].hole_cards[0].rank);
    hand.push(game_state.players[0].hole_cards[1].rank);
    console.log(in_action);
    bet(1000);
    console.log( 'game state + bet' );
    console.log( game_state );
    console.log( bet );
  },

  showdown: function(game_state) {

  }

};
<commit_msg>get hand<commit_after>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    var hand = [];
    var in_action;
    var goodStartingHand = ['10', 'J', 'K', 'Q', 'A'];
    var in_action = game_state[in_action];
    hand.push(game_state.players[0].hole_cards[0].rank);
    hand.push(game_state.players[0].hole_cards[1].rank);
    console.log(in_action);
    bet(1000);
    console.log( 'game state + bet' );
    console.log( game_state );
    console.log( bet );
  },

  showdown: function(game_state) {

  }

};
<|endoftext|>


<commit_before>(function(){
  function StoryNavCtrl($scope){
    var testStory = {
      title: 'TestStory Title',
      description: 'Test of story nav system.',
      summary: 'First story to test story nav system',
      keywords: ['test'],
      system: 'default',
      rating: 'unrated', //TODO set this as default in Rails
      pages: []
    };

    $scope.currentStory = testStory;

    //NOTE Need to have choices properly generate their ID
    var Page = function(args){
      this.parentPage = args.parentPage;
      this.title = args.title;
      this.summary = args.summary;
      this.content = args.content;
      this.choices = [];
      this.endpoint = args.endpoint;

//      for(var i = 0; i < args.choices.length; i++){
//        this.choices.push()
//      }

      /**************************************/
      //FIXME dfsljfasdj
      this.tempChoices = args.choices;
      /**************************************/

      this.init = function(){
        this.id = $scope.getPageID(this.parentPage);
        console.log('assigned id', this.id);
      }

//      this.initChoices = function(){
//        for(var i = 0; i < this.tempChoices.length; i++){
//          this.choices.push(new Choice(this.tempChoices[i].text, i, this));
//        }
//      }
    };

    $scope.getPageID = function(parentPage, index=-1){
      console.log('recieved', [parentPage,index]);
      if(parentPage===null){
        return '1';
      }else{
        console.log('non-null parent', parentPage.title)
        var lastChar = parentPage.id[parentPage.id.length -1];
//        var childIndex = parentPage.choices.indexOf(page);
//        console.log('childIndex', childIndex);

        if(angular.isNumber(parseInt(lastChar))){
          return parentPage.id + indexToAlpha(index);
        }else{
          return parentPage.id + (index+1);
        }
      }
    }

    var indexToAlpha = function(index){
//      console.log('convert to ', String.fromCharCode(index + 65));
      return String.fromCharCode(index + 65);
    }

    function Choice(text, index, parentPage){
//      console.log('index in choice', index);
      return {text: text, dest: $scope.getPageID(parentPage, index)};
    }

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: null,
          title: 'Initial page', //String
          summary: 'First page', //String
          content: 'You see two doors. Which do you choose?', //String
          choices: [
                        {text: 'Left door', parentPage: this},
                        {text: 'Right door', parentPage: this}
                   ],
          endpoint: false //Boolean
        }
      )
    );

    $scope.currentPage = $scope.currentStory.pages[0];

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: $scope.currentStory.pages[0],
          title: 'Left door', //String
          summary: 'First page', //String
          content: 'You entered the left door.', //String
          choices: [ ],
          endpoint: true //Boolean
        }
      )
    );

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: $scope.currentStory.pages[0],
          title: 'Right door', //String
          summary: 'First page', //String
          content: 'You entered the right door.', //String
          choices: [ ],
          endpoint: true //Boolean
        }
      )
    );

    var getPageByID = function(id){
      for(var i in $scope.currentStory.pages){
        if($scope.currentStory.pages[i].id === id){
          return $scope.currentStory.pages[i];
        }
      }

      return undefined;
    }

    $scope.setPage = function(pageID){
      $scope.currentPage = getPageByID(pageID);
    }

    var initializePages = function(){
      for (var i = 0; i < $scope.currentStory.pages.length; i++){
        $scope.currentStory.pages[i].init();
      }

//      for (var i = 0; i < $scope.currentStory.pages.length; i++){
//        $scope.currentStory.pages[i].initChoices();
//      }
    }

    $scope.$on('$viewContentLoaded', function(){
      console.log('content loaded');
      initializePages();
    });
  }

  angular
    .module('fatebook')
//    .controller('StoryNavCtrl', ['StoryNavSrv', StoryNavCtrl]);
    .controller('StoryNavCtrl', ['$scope', StoryNavCtrl]);
})();<commit_msg>2-level branching working. nth-level branching WIP<commit_after>(function(){
  function StoryNavCtrl($scope){
    var testStory = {
      title: 'TestStory Title',
      description: 'Test of story nav system.',
      summary: 'First story to test story nav system',
      keywords: ['test'],
      system: 'default',
      rating: 'unrated', //TODO set this as default in Rails
      pages: []
    };

    $scope.currentStory = testStory;

    //NOTE Need to have choices properly generate their ID
    var Page = function(args){
      this.parentPage = args.parentPage;
      this.id = args.id;
      this.title = args.title;
      this.summary = args.summary;
      this.content = args.content;
      this.choices = args.choices; //Displayed to user
      this.branches = []; //Ref to other pages
      this.endpoint = args.endpoint;

      this.init = function(){
        if(this.parentPage){
          this.parentPage.branches.push(this);
        }
      }
    };

    var generateBranchIDs = function(){
      var pages = $scope.currentStory.pages;

      console.log('pages',pages);

      pages[0].id = '1';

      for(var i = 1; i < pages.length; i++){
          if(pages[i].parentPage){
            var lastChar = pages[i].parentPage.id[pages[i].parentPage.id.length -1];
            var childIndex = pages[i].parentPage.branches.indexOf(pages[i]);

            if(angular.isNumber(parseInt(lastChar))){
              pages[i].id = pages[i].parentPage.id + indexToAlpha(childIndex);
            }else{
              return pages[i].parentPage.id + (childIndex+1);
            }
        }
      }
    }

    var indexToAlpha = function(index){
      return String.fromCharCode(index + 65);
    }

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: null,
          title: 'Initial page', //String
          summary: 'First page', //String
          content: 'You see two doors. Which do you choose?', //String
          choices: [
                        {text: 'Left door', dest: '1A'},
                        {text: 'Right door', dest: '1B'}
                   ],
          endpoint: false //Boolean
        }
      )
    );

    $scope.currentPage = $scope.currentStory.pages[0];

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: $scope.currentStory.pages[0],
          title: 'Left door', //String
          summary: 'First page', //String
          content: 'You entered the left door.', //String
          choices: [
            {text: 'Something else', dest: '1A1'}
          ],
          endpoint: true //Boolean
        }
      )
    );

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: $scope.currentStory.pages[0],
          title: 'Right door', //String
          summary: 'First page', //String
          content: 'You entered the right door.', //String
          endpoint: true //Boolean
        }
      )
    );

    $scope.currentStory.pages.push(
      new Page(
        {
          parentPage: $scope.currentStory.pages[1],
          title: 'Super last', //String
          summary: 'First page', //String
          content: 'Even more final.', //String
          endpoint: true //Boolean
        }
      )
    );

    $scope.setPage = function(pageID){
      var choices = $scope.currentPage.choices;
      var pages = $scope.currentStory.pages;

      for(var i in pages){
        for(var j in choices){
          if (pages[i].id === choices[j].dest){
            $scope.currentPage = pages[i];
          }
        }
      }

      return null;
    }

    var initializePages = function(){
      for (var i = 0; i < $scope.currentStory.pages.length; i++){
        $scope.currentStory.pages[i].init();
      }
    }

    $scope.$on('$viewContentLoaded', function(){
      initializePages();
      generateBranchIDs();
    });
  }

  angular
    .module('fatebook')
//    .controller('StoryNavCtrl', ['StoryNavSrv', StoryNavCtrl]);
    .controller('StoryNavCtrl', ['$scope', StoryNavCtrl]);
})();<|endoftext|>


<commit_before>import _ from 'underscore';
import { D2ItemTransformer } from './d2-itemTransformer';
import { D2PerkRater } from './d2-perkRater';

/**
 * Get the community reviews from the DTR API for a specific item.
 *
 * @class D2ReviewsFetcher
 */
class D2ReviewsFetcher {
  constructor($q, $http, trackerErrorHandler, loadingTracker, reviewDataCache, userFilter, dimPlatformService) {
    this.$q = $q;
    this.$http = $http;
    this._itemTransformer = new D2ItemTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
    this._loadingTracker = loadingTracker;
    this._reviewDataCache = reviewDataCache;
    this._userFilter = userFilter;
    this._dimPlatformService = dimPlatformService;
    this._perkRater = new D2PerkRater();
  }

  _getItemReviewsCall(item, platformSelection) {
    const queryString = `reviews?page=1&platform=${platformSelection}`;

    return {
      method: 'POST',
      url: `https://db-api.destinytracker.com/api/external/reviews?${queryString}`, // TODO: pagination
      data: item,
      dataType: 'json'
    };
  }

  _getItemReviewsPromise(item, platformSelection) {
    const postWeapon = this._itemTransformer.getRollAndPerks(item);

    const promise = this.$q
      .when(this._getItemReviewsCall(postWeapon, platformSelection))
      .then(this.$http)
      .then(this._trackerErrorHandler.handleErrors.bind(this._trackerErrorHandler), this._trackerErrorHandler.handleErrors.bind(this._trackerErrorHandler))
      .then((response) => { return response.data; });

    this._loadingTracker.addPromise(promise);

    return promise;
  }

  _getUserReview(reviewData) {
    // bugbug: will need to use membership service if isReviewer flag stays broke
    return _.find(reviewData.reviews, { isReviewer: true });
  }

  _sortAndIgnoreReviews(item) {
    if (item.writtenReviews) {
      item.writtenReviews.sort(this._sortReviews);

      item.writtenReviews.forEach((writtenReview) => {
        writtenReview.isIgnored = this._userFilter.conditionallyIgnoreReview(writtenReview);
      });
    }
  }

  _markUserReview(reviewData) {
    const membershipInfo = this._dimPlatformService.getActive();
    const membershipId = membershipInfo.membershipId;

    _.each(reviewData.reviews, (review) => {
      if (review.reviewer.membershipId === membershipId) {
        review.isReviewer = true;
      }
    });

    return reviewData;
  }

  _attachReviews(item, reviewData) {
    const userReview = this._getUserReview(reviewData);

    // TODO: reviewData has two very different shapes depending on whether it's from cache or from the service
    item.totalReviews = reviewData.totalReviews === undefined ? reviewData.ratingCount : reviewData.totalReviews;
    item.writtenReviews = _.filter(reviewData.reviews, 'text'); // only attach reviews with text associated

    this._sortAndIgnoreReviews(item);

    if (userReview) {
      item.userVote = userReview.voted;
      item.userReview = userReview.text;
      item.userReviewPros = userReview.pros;
      item.userReviewCons = userReview.cons;
    }

    this._reviewDataCache.addReviewsData(item, reviewData);

    this._perkRater.ratePerks(item);
  }

  _sortReviews(a, b) {
    if (a.isReviewer) {
      return -1;
    }

    if (b.isReviewer) {
      return 1;
    }

    if (a.isHighlighted) {
      return -1;
    }

    if (b.isHighlighted) {
      return 1;
    }

    const ratingDiff = b.rating - a.rating;

    if (ratingDiff !== 0) {
      return ratingDiff;
    }

    const aDate = new Date(a.timestamp);
    const bDate = new Date(b.timestamp);

    return bDate - aDate;
  }

  _attachCachedReviews(item,
    cachedItem) {
    item.communityReviews = cachedItem.reviews;

    this._attachReviews(item, cachedItem);

    if (cachedItem.userRating) {
      item.userRating = cachedItem.userRating;
    }

    if (cachedItem.review) {
      item.userReview = cachedItem.review;
    }

    if (cachedItem.pros) {
      item.userReviewPros = cachedItem.pros;
    }

    if (cachedItem.cons) {
      item.userReviewCons = cachedItem.cons;
    }
  }

  /**
   * Get community (which may include the current user's) reviews for a given item and attach
   * them to the item.
   * Attempts to fetch data from the cache first.
   *
   * @param {any} item
   * @param {number} platformSelection
   * @returns {void}
   *
   * @memberof D2ReviewsFetcher
   */
  getItemReviews(item, platformSelection) {
    if (!item.reviewable) {
      return;
    }
    const ratingData = this._reviewDataCache.getRatingData(item);

    if (ratingData && ratingData.reviewsDataFetched) {
      this._attachCachedReviews(item,
        ratingData);

      return;
    }

    this._getItemReviewsPromise(item, platformSelection)
      .then((reviewData) => this._markUserReview(reviewData))
      .then((reviewData) => this._attachReviews(item,
        reviewData));
  }
}

export { D2ReviewsFetcher };
<commit_msg>A little less redundant with the queryString.<commit_after>import _ from 'underscore';
import { D2ItemTransformer } from './d2-itemTransformer';
import { D2PerkRater } from './d2-perkRater';

/**
 * Get the community reviews from the DTR API for a specific item.
 *
 * @class D2ReviewsFetcher
 */
class D2ReviewsFetcher {
  constructor($q, $http, trackerErrorHandler, loadingTracker, reviewDataCache, userFilter, dimPlatformService) {
    this.$q = $q;
    this.$http = $http;
    this._itemTransformer = new D2ItemTransformer();
    this._trackerErrorHandler = trackerErrorHandler;
    this._loadingTracker = loadingTracker;
    this._reviewDataCache = reviewDataCache;
    this._userFilter = userFilter;
    this._dimPlatformService = dimPlatformService;
    this._perkRater = new D2PerkRater();
  }

  _getItemReviewsCall(item, platformSelection) {
    const queryString = `page=1&platform=${platformSelection}`;

    return {
      method: 'POST',
      url: `https://db-api.destinytracker.com/api/external/reviews?${queryString}`, // TODO: pagination
      data: item,
      dataType: 'json'
    };
  }

  _getItemReviewsPromise(item, platformSelection) {
    const postWeapon = this._itemTransformer.getRollAndPerks(item);

    const promise = this.$q
      .when(this._getItemReviewsCall(postWeapon, platformSelection))
      .then(this.$http)
      .then(this._trackerErrorHandler.handleErrors.bind(this._trackerErrorHandler), this._trackerErrorHandler.handleErrors.bind(this._trackerErrorHandler))
      .then((response) => { return response.data; });

    this._loadingTracker.addPromise(promise);

    return promise;
  }

  _getUserReview(reviewData) {
    // bugbug: will need to use membership service if isReviewer flag stays broke
    return _.find(reviewData.reviews, { isReviewer: true });
  }

  _sortAndIgnoreReviews(item) {
    if (item.writtenReviews) {
      item.writtenReviews.sort(this._sortReviews);

      item.writtenReviews.forEach((writtenReview) => {
        writtenReview.isIgnored = this._userFilter.conditionallyIgnoreReview(writtenReview);
      });
    }
  }

  _markUserReview(reviewData) {
    const membershipInfo = this._dimPlatformService.getActive();
    const membershipId = membershipInfo.membershipId;

    _.each(reviewData.reviews, (review) => {
      if (review.reviewer.membershipId === membershipId) {
        review.isReviewer = true;
      }
    });

    return reviewData;
  }

  _attachReviews(item, reviewData) {
    const userReview = this._getUserReview(reviewData);

    // TODO: reviewData has two very different shapes depending on whether it's from cache or from the service
    item.totalReviews = reviewData.totalReviews === undefined ? reviewData.ratingCount : reviewData.totalReviews;
    item.writtenReviews = _.filter(reviewData.reviews, 'text'); // only attach reviews with text associated

    this._sortAndIgnoreReviews(item);

    if (userReview) {
      item.userVote = userReview.voted;
      item.userReview = userReview.text;
      item.userReviewPros = userReview.pros;
      item.userReviewCons = userReview.cons;
    }

    this._reviewDataCache.addReviewsData(item, reviewData);

    this._perkRater.ratePerks(item);
  }

  _sortReviews(a, b) {
    if (a.isReviewer) {
      return -1;
    }

    if (b.isReviewer) {
      return 1;
    }

    if (a.isHighlighted) {
      return -1;
    }

    if (b.isHighlighted) {
      return 1;
    }

    const ratingDiff = b.rating - a.rating;

    if (ratingDiff !== 0) {
      return ratingDiff;
    }

    const aDate = new Date(a.timestamp);
    const bDate = new Date(b.timestamp);

    return bDate - aDate;
  }

  _attachCachedReviews(item,
    cachedItem) {
    item.communityReviews = cachedItem.reviews;

    this._attachReviews(item, cachedItem);

    if (cachedItem.userRating) {
      item.userRating = cachedItem.userRating;
    }

    if (cachedItem.review) {
      item.userReview = cachedItem.review;
    }

    if (cachedItem.pros) {
      item.userReviewPros = cachedItem.pros;
    }

    if (cachedItem.cons) {
      item.userReviewCons = cachedItem.cons;
    }
  }

  /**
   * Get community (which may include the current user's) reviews for a given item and attach
   * them to the item.
   * Attempts to fetch data from the cache first.
   *
   * @param {any} item
   * @param {number} platformSelection
   * @returns {void}
   *
   * @memberof D2ReviewsFetcher
   */
  getItemReviews(item, platformSelection) {
    if (!item.reviewable) {
      return;
    }
    const ratingData = this._reviewDataCache.getRatingData(item);

    if (ratingData && ratingData.reviewsDataFetched) {
      this._attachCachedReviews(item,
        ratingData);

      return;
    }

    this._getItemReviewsPromise(item, platformSelection)
      .then((reviewData) => this._markUserReview(reviewData))
      .then((reviewData) => this._attachReviews(item,
        reviewData));
  }
}

export { D2ReviewsFetcher };
<|endoftext|>


<commit_before>/*! Page length control via links for DataTables
 * 2014 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     LengthLinks
 * @description Page length control via links for DataTables
 * @version     1.1.0
 * @file        dataTables.searchHighlight.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 * @copyright   Copyright 2014 SpryMedia Ltd.
 *
 * License      MIT - http://datatables.net/license/mit
 *
 * This feature plug-in for DataTables adds page length control links to the
 * DataTable. The `dom` option can be used to insert the control using the `L`
 * character option and it uses the `lengthMenu` options of DataTables to
 * determine what to display.
 *
 * @example
 *   $('#myTable').DataTable( {
 *     dom: 'Lfrtip'
 *   } );
 *
 * @example
 *   $('#myTable').DataTable( {
 *     lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
 *     dom: 'Lfrtip'
 *   } );
 */

(function(window, document, $, undefined) {

$.fn.dataTable.LengthLinks = function ( inst ) {
	var api = new $.fn.dataTable.Api( inst );
	var settings = api.settings()[0];
	var container = $('

').addClass( settings.oClasses.sLength );
	var lastLength = -1;

	// API so the feature wrapper can return the node to insert
	this.container = function () {
		return container[0];
	};

	// Listen for events to change the page length
	container.on( 'click.dtll', 'a', function (e) {
		e.preventDefault();
		api.page.len( $(this).data('length')*1 ).draw( false );
	} );

	// Update on each draw
	api.on( 'draw', function () {
		// No point in updating - nothing has changed
		if ( api.page.len() === lastLength ) {
			return;
		}

		var menu = settings.aLengthMenu;
		var lang = menu.length===2 && $.isArray(menu[0]) ? menu[1] : menu;
		var lens = menu.length===2 && $.isArray(menu[0]) ? menu[0] : menu;

		var out = $.map( lens, function (el, i) {
			return el == api.page.len() ?
				''+lang[i]+'' :
				''+lang[i]+'';
		} );

		container.html( settings.oLanguage.sLengthMenu.replace( '_MENU_', out.join(' | ') ) );
		lastLength = api.page.len();
	} );

	api.on( 'destroy', function () {
		container.off( 'click.dtll', 'a' );
	} );
};

// Subscribe the feature plug-in to DataTables, ready for use
$.fn.dataTable.ext.feature.push( {
	"fnInit": function( settings ) {
		var l = new $.fn.dataTable.LengthLinks( settings );
		return l.container();
	},
	"cFeature": "L",
	"sFeature": "LengthLinks"
} );

})(window, document, jQuery);
<commit_msg>Fix - features: Length links wasn't operating correctly with an initial default page length of -1 (all rows)<commit_after>/*! Page length control via links for DataTables
 * 2014 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     LengthLinks
 * @description Page length control via links for DataTables
 * @version     1.1.0
 * @file        dataTables.searchHighlight.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 * @copyright   Copyright 2014 SpryMedia Ltd.
 *
 * License      MIT - http://datatables.net/license/mit
 *
 * This feature plug-in for DataTables adds page length control links to the
 * DataTable. The `dom` option can be used to insert the control using the `L`
 * character option and it uses the `lengthMenu` options of DataTables to
 * determine what to display.
 *
 * @example
 *   $('#myTable').DataTable( {
 *     dom: 'Lfrtip'
 *   } );
 *
 * @example
 *   $('#myTable').DataTable( {
 *     lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
 *     dom: 'Lfrtip'
 *   } );
 */

(function(window, document, $, undefined) {

$.fn.dataTable.LengthLinks = function ( inst ) {
	var api = new $.fn.dataTable.Api( inst );
	var settings = api.settings()[0];
	var container = $('

').addClass( settings.oClasses.sLength );
	var lastLength = null;

	// API so the feature wrapper can return the node to insert
	this.container = function () {
		return container[0];
	};

	// Listen for events to change the page length
	container.on( 'click.dtll', 'a', function (e) {
		e.preventDefault();
		api.page.len( $(this).data('length')*1 ).draw( false );
	} );

	// Update on each draw
	api.on( 'draw', function () {
		// No point in updating - nothing has changed
		if ( api.page.len() === lastLength ) {
			return;
		}

		var menu = settings.aLengthMenu;
		var lang = menu.length===2 && $.isArray(menu[0]) ? menu[1] : menu;
		var lens = menu.length===2 && $.isArray(menu[0]) ? menu[0] : menu;

		var out = $.map( lens, function (el, i) {
			return el == api.page.len() ?
				''+lang[i]+'' :
				''+lang[i]+'';
		} );

		container.html( settings.oLanguage.sLengthMenu.replace( '_MENU_', out.join(' | ') ) );
		lastLength = api.page.len();
	} );

	api.on( 'destroy', function () {
		container.off( 'click.dtll', 'a' );
	} );
};

// Subscribe the feature plug-in to DataTables, ready for use
$.fn.dataTable.ext.feature.push( {
	"fnInit": function( settings ) {
		var l = new $.fn.dataTable.LengthLinks( settings );
		return l.container();
	},
	"cFeature": "L",
	"sFeature": "LengthLinks"
} );

})(window, document, jQuery);
<|endoftext|>