<commit_before>/*---LEFT BAR ACCORDION----*/
$(function () {
    $('#nav-accordion').dcAccordion({
        eventType: 'click',
        autoClose: true,
        saveState: true,
        disableLink: true,
        speed: 'slow',
        showCount: false,
        autoExpand: true,
//        cookie: 'dcjq-accordion-1',
        classExpand: 'dcjq-current-parent'
    });
});

var Script = function () {

//    sidebar dropdown menu auto scrolling
    jQuery('#sidebar .sub-menu > a').click(function () {
        var o = ($(this).offset());
        diff = 250 - o.top;
        if (diff > 0)
            $("#sidebar").scrollTo("-=" + Math.abs(diff), 500);
        else
            $("#sidebar").scrollTo("+=" + Math.abs(diff), 500);
    });

//    sidebar toggle

    $(function () {
        function responsiveView() {
            var wSize = $(window).width();
            if (wSize <= 768) {
                $('#container').addClass('sidebar-close');
                $('#sidebar > ul').hide();
            }

            if (wSize > 768) {
                $('#container').removeClass('sidebar-close');
                $('#sidebar > ul').show();
            }
        }

        $(window).on('load', responsiveView);
        $(window).on('resize', responsiveView);
    });

    $('.icon-reorder').click(function () {
        if ($('#sidebar > ul').is(":visible") === true) {
            $('#main-content').css({
                'margin-left': '0px'
            });
            $('#sidebar').css({
                'margin-left': '-210px'
            });
            $('#sidebar > ul').hide();
            $("#container").addClass("sidebar-closed");
        } else {
            $('#main-content').css({
                'margin-left': '210px'
            });
            $('#sidebar > ul').show();
            $('#sidebar').css({
                'margin-left': '0'
            });
            $("#container").removeClass("sidebar-closed");
        }
    });

// custom scrollbar
    $("#sidebar").niceScroll({
        styler: "fb",
        cursorcolor: "#e8403f",
        cursorwidth: '3',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled: false,
        cursorborder: ''
    });

    $("html").niceScroll({
        styler: "fb",
        cursorcolor: "#e8403f",
        cursorwidth: '6',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled: false,
        cursorborder: '',
        zindex: '1000'
    });

// widget tools

    jQuery('.panel .tools .icon-chevron-down').click(function () {
        var el = jQuery(this).parents(".panel").children(".panel-body");
        if (jQuery(this).hasClass("icon-chevron-down")) {
            jQuery(this).removeClass("icon-chevron-down").addClass("icon-chevron-up");
            el.slideUp(200);
        } else {
            jQuery(this).removeClass("icon-chevron-up").addClass("icon-chevron-down");
            el.slideDown(200);
        }
    });

    jQuery('.panel .tools .icon-remove').click(function () {
        jQuery(this).parents(".panel").parent().remove();
    });

//    tool tips
    $('.tooltips').tooltip();

//    popovers
    $('.popovers').popover();

// custom bar chart
    if ($(".custom-bar-chart")) {
        $(".bar").each(function () {
            var i = $(this).find(".value").html();
            $(this).find(".value").html("");
            $(this).find(".value").animate({
                height: i
            }, 2000)
        })
    }

}();

//chosen selection
$(function () {
    $(".chosen-select").chosen();
});

//it work's too for delete-confirm
/*$('.delete-confirm').click(function (){
 var answer = confirm("You really like to delete this Item?");
 if (answer) {
 return true;
 }else{
 return false;
 }
 });*/

//delete confirm message
function confirmDelete() {
    return confirm('Are you sure you want to delete!!!');
}

//delete confirm function
$(".delete-confirm").click(function (event) {
    event.stopPropagation();
    if (confirmDelete()) {
        return true;
    }
    else {
        event.preventDefault();
        return false;
    }
});

//when enable datepicker in specific field only
/*$(function() {
 $( "#acme_purchasebundle_purchase_purchaseDate" ).datepicker();
 });*/

//datepicker function for purchase and issue
$(function () {
    $('.date-picker').datepicker({dateFormat: 'dd-mm-yy'});
});

//confirm delete function
$(document).on("click", "a.confirm-delete", function (e) {
    if (!confirmDelete()) {
        e.stopPropagation();
        return false;
    }
    return true;
});

//date picker start(report)
if (top.location != location) {
    top.location.href = document.location.href;
}
$(function () {
    window.prettyPrint && prettyPrint();
    $('.default-date-picker').datepicker({
        format: 'dd-mm-yyyy'
    });
    $('.dpYears').datepicker();
    $('.dpMonths').datepicker();

    var startDate = new Date(2012, 1, 20);
    var endDate = new Date(2012, 1, 25);
    $('.dp4').datepicker()
        .on('changeDate', function (ev) {
            if (ev.date.valueOf() > endDate.valueOf()) {
                $('.alert').show().find('strong').text('The start date can not be greater then the end date');
            } else {
                $('.alert').hide();
                startDate = new Date(ev.date);
                $('#startDate').text($('.dp4').data('date'));
            }
            $('.dp4').datepicker('hide');
        });
    $('.dp5').datepicker()
        .on('changeDate', function (ev) {
            if (ev.date.valueOf() < startDate.valueOf()) {
                $('.alert').show().find('strong').text('The end date can not be less then the start date');
            } else {
                $('.alert').hide();
                endDate = new Date(ev.date);
                $('.endDate').text($('.dp5').data('date'));
            }
            $('.dp5').datepicker('hide');
        });

    // disabling dates
    var nowTemp = new Date();
    var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

    var checkin = $('.dpd1').datepicker({
        onRender: function (date) {
            return date.valueOf() < now.valueOf() ? 'disabled' : '';
        }
    }).on('changeDate', function (ev) {
        if (ev.date.valueOf() > checkout.date.valueOf()) {
            var newDate = new Date(ev.date)
            newDate.setDate(newDate.getDate() + 1);
            checkout.setValue(newDate);
        }
        checkin.hide();
        $('.dpd2')[0].focus();
    }).data('datepicker');
    var checkout = $('.dpd2').datepicker({
        onRender: function (date) {
            return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
        }
    }).on('changeDate', function (ev) {
        checkout.hide();
    }).data('datepicker');
});

//form submit functionality
$(function () {
    $('#search-form').submit(
        function (evt) {
            $("#loading-full,.loading-ball").fadeIn();
            evt.preventDefault();
            var searchVal = $.trim($('input[type="text"]', $(this)).val());
            if (searchVal.length > 1) {
                window.location = $(this).attr('action') + '/' + searchVal;
            }
        }
    );
});

//for modal
$(function () {
    var modalRequestRunning = false;
    $('body').on('click', '.ajax-modal[data-toggle="modal"]', function (e) {
        e.preventDefault();
        if (modalRequestRunning)
            return false;
        modalRequestRunning = true;
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            type: "GET",
            success: function (response) {
                modalRequestRunning = false;
                $('

').html(response).modal();
            }
        });
        return false;
    });
});

//enable tooltip
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

//sortable
var xhr;

function sortableList(obj){
    xhr && xhr.abort && xhr.abort();
    xhr  =  $.ajax({
            type        : "POST",
            url         : Routing.generate('invoice_sort'),
            data        : obj,
            dataType    : "json",
            success     : function(result) {
                if(result.success){
                    //console.log(result.jobs);
                    $('.sort-parm').html(result.entities).removeClass('sort-parm');
                    //var array = $.parseJSON(result.query);
                   // console.log(array);
                    //$('#search_data_list').html(arrayToHtml(array));
                }
            },
            error: function(result){
                console.log(result.message);
            }
        });
}

$(function () {
    var arrow_array = ['&#8592','&#8595','&#8593'];
    var order = null;
    var label = null; //hardcoded

    $('#sort th a').click(function(){
        $('.sort-parm').removeClass('sort-parm');
        //current_arrow = $('#sort b').text();
        $(this).addClass('current_label');
        $(this).parent().parent().parent().parent().children('tbody').addClass('sort-parm');

        label = $(this).text().replace(/[^\w\s]/gi, '');
        //console.log(cat);
        var arrow_state = ['arrow_normal','arrow_down','arrow_up'];
        var next_arrow=1;

        var current_arrow = $('.current_label').children('b').attr('id');
        console.log(' + current_arrow '+current_arrow);
       /* for(var i = 0 ; i<arrow_state.length ; i++){
            console.log(arrow_state[i]);
            if(current_arrow === arrow_state[i]){
                console.log('arrow find');
                next_arrow=i;
                //console.log(next_arrow);
            }

        }*/
        //console.log('next arrow '+next_arrow);
        //console.log(current_arrow);
        if(current_arrow === arrow_state[2]){
            order = "ASC";
        }
        if(current_arrow === arrow_state[1]){
            order = "DESC";
        }

        for(var i = 0;i<arrow_state.length;i++){
            //next_arrow++;
            if(current_arrow === arrow_state[i]){
                console.log(current_arrow);
                if(i === arrow_state.length -1){
                    next_arrow = 0;
                    console.log('next_arrow should be 0--'+next_arrow);
                }else{
                    next_arrow = i+1;
                    console.log('next_arrow should be '+(i+1)+' '+ next_arrow);
                }

            }
            //console.log(next_arrow);
        }
        var obj = {
            kind : label,
            order : order
        };
        $('.current_label b').replaceWith(''+arrow_array[next_arrow]+'');
        $('.current_label').removeClass('current_label');
        if(next_arrow !== 0){
            sortableList(obj);
        }else{
            xhr && xhr.abort && xhr.abort();
        }
    });
});

<commit_msg>invoice js fix<commit_after>/*---LEFT BAR ACCORDION----*/
$(function () {
    $('#nav-accordion').dcAccordion({
        eventType: 'click',
        autoClose: true,
        saveState: true,
        disableLink: true,
        speed: 'slow',
        showCount: false,
        autoExpand: true,
//        cookie: 'dcjq-accordion-1',
        classExpand: 'dcjq-current-parent'
    });
});

var Script = function () {

//    sidebar dropdown menu auto scrolling
    jQuery('#sidebar .sub-menu > a').click(function () {
        var o = ($(this).offset());
        diff = 250 - o.top;
        if (diff > 0)
            $("#sidebar").scrollTo("-=" + Math.abs(diff), 500);
        else
            $("#sidebar").scrollTo("+=" + Math.abs(diff), 500);
    });

//    sidebar toggle

    $(function () {
        function responsiveView() {
            var wSize = $(window).width();
            if (wSize <= 768) {
                $('#container').addClass('sidebar-close');
                $('#sidebar > ul').hide();
            }

            if (wSize > 768) {
                $('#container').removeClass('sidebar-close');
                $('#sidebar > ul').show();
            }
        }

        $(window).on('load', responsiveView);
        $(window).on('resize', responsiveView);
    });

    $('.icon-reorder').click(function () {
        if ($('#sidebar > ul').is(":visible") === true) {
            $('#main-content').css({
                'margin-left': '0px'
            });
            $('#sidebar').css({
                'margin-left': '-210px'
            });
            $('#sidebar > ul').hide();
            $("#container").addClass("sidebar-closed");
        } else {
            $('#main-content').css({
                'margin-left': '210px'
            });
            $('#sidebar > ul').show();
            $('#sidebar').css({
                'margin-left': '0'
            });
            $("#container").removeClass("sidebar-closed");
        }
    });

// custom scrollbar
    $("#sidebar").niceScroll({
        styler: "fb",
        cursorcolor: "#e8403f",
        cursorwidth: '3',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled: false,
        cursorborder: ''
    });

    $("html").niceScroll({
        styler: "fb",
        cursorcolor: "#e8403f",
        cursorwidth: '6',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled: false,
        cursorborder: '',
        zindex: '1000'
    });

// widget tools

    jQuery('.panel .tools .icon-chevron-down').click(function () {
        var el = jQuery(this).parents(".panel").children(".panel-body");
        if (jQuery(this).hasClass("icon-chevron-down")) {
            jQuery(this).removeClass("icon-chevron-down").addClass("icon-chevron-up");
            el.slideUp(200);
        } else {
            jQuery(this).removeClass("icon-chevron-up").addClass("icon-chevron-down");
            el.slideDown(200);
        }
    });

    jQuery('.panel .tools .icon-remove').click(function () {
        jQuery(this).parents(".panel").parent().remove();
    });

//    tool tips
    $('.tooltips').tooltip();

//    popovers
    $('.popovers').popover();

// custom bar chart
    if ($(".custom-bar-chart")) {
        $(".bar").each(function () {
            var i = $(this).find(".value").html();
            $(this).find(".value").html("");
            $(this).find(".value").animate({
                height: i
            }, 2000)
        })
    }

}();

//chosen selection
$(function () {
    $(".chosen-select").chosen();
});

//it work's too for delete-confirm
/*$('.delete-confirm').click(function (){
 var answer = confirm("You really like to delete this Item?");
 if (answer) {
 return true;
 }else{
 return false;
 }
 });*/

//delete confirm message
function confirmDelete() {
    return confirm('Are you sure you want to delete!!!');
}

//delete confirm function
$(".delete-confirm").click(function (event) {
    event.stopPropagation();
    if (confirmDelete()) {
        return true;
    }
    else {
        event.preventDefault();
        return false;
    }
});

//when enable datepicker in specific field only
/*$(function() {
 $( "#acme_purchasebundle_purchase_purchaseDate" ).datepicker();
 });*/

//datepicker function for purchase and issue
$(function () {
    $('.date-picker').datepicker({dateFormat: 'dd-mm-yy'});
});

//confirm delete function
$(document).on("click", "a.confirm-delete", function (e) {
    if (!confirmDelete()) {
        e.stopPropagation();
        return false;
    }
    return true;
});

//date picker start(report)
if (top.location != location) {
    top.location.href = document.location.href;
}
$(function () {
    window.prettyPrint && prettyPrint();
    $('.default-date-picker').datepicker({
        format: 'dd-mm-yyyy'
    });
    $('.dpYears').datepicker();
    $('.dpMonths').datepicker();

    var startDate = new Date(2012, 1, 20);
    var endDate = new Date(2012, 1, 25);
    $('.dp4').datepicker()
        .on('changeDate', function (ev) {
            if (ev.date.valueOf() > endDate.valueOf()) {
                $('.alert').show().find('strong').text('The start date can not be greater then the end date');
            } else {
                $('.alert').hide();
                startDate = new Date(ev.date);
                $('#startDate').text($('.dp4').data('date'));
            }
            $('.dp4').datepicker('hide');
        });
    $('.dp5').datepicker()
        .on('changeDate', function (ev) {
            if (ev.date.valueOf() < startDate.valueOf()) {
                $('.alert').show().find('strong').text('The end date can not be less then the start date');
            } else {
                $('.alert').hide();
                endDate = new Date(ev.date);
                $('.endDate').text($('.dp5').data('date'));
            }
            $('.dp5').datepicker('hide');
        });

    // disabling dates
    var nowTemp = new Date();
    var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

    var checkin = $('.dpd1').datepicker({
        onRender: function (date) {
            return date.valueOf() < now.valueOf() ? 'disabled' : '';
        }
    }).on('changeDate', function (ev) {
        if (ev.date.valueOf() > checkout.date.valueOf()) {
            var newDate = new Date(ev.date)
            newDate.setDate(newDate.getDate() + 1);
            checkout.setValue(newDate);
        }
        checkin.hide();
        $('.dpd2')[0].focus();
    }).data('datepicker');
    var checkout = $('.dpd2').datepicker({
        onRender: function (date) {
            return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
        }
    }).on('changeDate', function (ev) {
        checkout.hide();
    }).data('datepicker');
});

//form submit functionality
$(function () {
    $('#search-form').submit(
        function (evt) {
            $("#loading-full,.loading-ball").fadeIn();
            evt.preventDefault();
            var searchVal = $.trim($('input[type="text"]', $(this)).val());
            if (searchVal.length > 1) {
                window.location = $(this).attr('action') + '/' + searchVal;
            }
        }
    );
});

//for modal
$(function () {
    var modalRequestRunning = false;
    $('body').on('click', '.ajax-modal[data-toggle="modal"]', function (e) {
        e.preventDefault();
        if (modalRequestRunning)
            return false;
        modalRequestRunning = true;
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            type: "GET",
            success: function (response) {
                modalRequestRunning = false;
                $('

').html(response).modal();
            }
        });
        return false;
    });
});

//enable tooltip
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

//sortable
var xhr;

function sortableList(obj){
    xhr && xhr.abort && xhr.abort();
    xhr  =  $.ajax({
            type        : "POST",
            url         : Routing.generate('invoice_sort'),
            data        : obj,
            dataType    : "json",
            success     : function(result) {
                if(result.success){
                    //console.log(result.jobs);
                    $('.sort-parm').html(result.entities).removeClass('sort-parm');
                    //var array = $.parseJSON(result.query);
                   // console.log(array);
                    //$('#search_data_list').html(arrayToHtml(array));
                }
            },
            error: function(result){
                console.log(result.message);
            }
        });
}

$(function () {
    var arrow_array = ['&#8592','&#8595','&#8593'];
    var order = null;
    var label = null; //hardcoded

    $('#sort th a').click(function(){
        $('.sort-parm').removeClass('sort-parm');
        //current_arrow = $('#sort b').text();
        $(this).addClass('current_label');
        $(this).parent().parent().parent().parent().children('tbody').addClass('sort-parm');

        label = $(this).text().replace(/[^\w\s]/gi, '');
        //console.log(cat);
        var arrow_state = ['arrow_normal','arrow_down','arrow_up'];
        var next_arrow=1;

        var current_arrow = $('.current_label').children('b').attr('id');
        console.log(' + current_arrow '+current_arrow);
       /* for(var i = 0 ; i<arrow_state.length ; i++){
            console.log(arrow_state[i]);
            if(current_arrow === arrow_state[i]){
                console.log('arrow find');
                next_arrow=i;
                //console.log(next_arrow);
            }

        }*/
        //console.log('next arrow '+next_arrow);
        //console.log(current_arrow);
        if(current_arrow === arrow_state[2]){
            order = "ASC";
        }
        if(current_arrow === arrow_state[1]){
            order = "DESC";
        }

        for(var i = 0;i<arrow_state.length;i++){
            //next_arrow++;
            if(current_arrow === arrow_state[i]){
                console.log(current_arrow);
                if(i === arrow_state.length -1){
                    next_arrow = 0;
                    console.log('next_arrow should be 0--'+next_arrow);
                }else{
                    next_arrow = i+1;
                    console.log('next_arrow should be '+(i+1)+' '+ next_arrow);
                }

            }
            //console.log(next_arrow);
        }
        var obj = {
            kind : label,
            order : order
        };
        $('.current_label b').replaceWith(''+arrow_array[next_arrow]+'');
        $('.current_label').removeClass('current_label');
        if(next_arrow !== 0){
            sortableList(obj);
        }else{
            xhr && xhr.abort && xhr.abort();
        }
    });
});

<|endoftext|>


<commit_before>var rank = require('./rank');

Array.prototype.contains = function (element) {
    return this.indexOf(element) > -1;
};

module.exports = {

    VERSION: "MadFoldBot v2.3",

    bet_request: function (game_state, bet) {
        return this.strategy1(game_state, bet);
    },

    showdown: function (game_state) {

    },

    strategy1: function (game_state, bet) {
        var our_bet = this.getBet(game_state);
        console.log('OUR BET: ' + our_bet);

        bet(our_bet);
    },

    getBet: function (game_state) {
        var all_cards = this.getAllCards(game_state);
        var myself = game_state.players[game_state.in_action];
        var call = game_state.current_buy_in - myself["bet"];

        var isAllIn = this.isAllIn(game_state);
        console.log('CURRENT CALL: ' + call);

        if (false && isAllIn) {
            console.log("WARNING - ALL IN!!!");

            if (game_state.community_cards.length < 1) {
                if (
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
                ) {
                } else {
                    return 0;
                }
            }
        } else {

        }

        if (game_state.community_cards.length < 1) {
            console.log('PREFLOP');
            // we're before flop
            if (lameCards(myself.hole_cards)) {
                console.log('LAME CARDS');
                return 0;
            } else {
                if (toNum(myself.hole_cards[1].rank) > 9 && toNum(myself.hole_cards[0].rank) > 9) {
                    console.log('HIGH CARDS. DOING CALL');
                    return call;
                }

                return 0;
            }
        }

        var our_hand = rank.rank(all_cards);

        console.log('OUR HAND');
        console.log(our_hand);

        if (our_hand.contains('flush')) {
            return 10000;
        }

        if (our_hand.contains('full_house')) {
            return 10000;
        }

        if (our_hand.contains('tree_of_a_kind')) {
            return 700;
        }

        if (our_hand.contains('two_pairs')) {
            return 250;
        }

        if (our_hand.contains('pair')) {
            return 100;
        }

        return 0;
    },

    isAllIn: function (game_state) {
        var players = game_state.players;

        for (var i in players) {
            if (i != game_state.in_action && players[i].status == "active" && players[i].stack == 0 && players[i].bet > 200) {
                return true;
            }
        }

        return false;
    },

    getAllCards: function (game_state) {
        var cards = [];
        var community_cards = game_state.community_cards;

        for (var p in game_state.players) {
            if (typeof game_state.players[p]['hole_cards'] != 'undefined') {
                cards = game_state.players[p]['hole_cards'];
            }
        }

        cards = cards.concat(community_cards);

        return cards;
    }

};

function toNum(c) {
    switch (c) {
        case 'J':
            return 11;
        case 'Q':
            return 12;
        case 'K':
            return 13;
        case 'A':
            return 14;

        default:
            return c;
    }
}

function lameCards(cards) {
   /* if (
        toNum(cards[0].rank) >= 12 || toNum(cards[1].rank) >= 12
    ) {
        return false;
    } else if (cards[0].rank == 'A' || cards[1].rank == 'A') {
        return false;
    }
    else */ if (
        (toNum(cards[0].rank) < 4 || toNum(cards[1].rank) < 4) && cards[0].rank != cards[1].rank
    ) {
        return true
    } else {
        return false
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        if (players[i].status == "active") {
            sum += players[i].stack;
        }
    }
    return sum / players.length;
}

function compute_chip_factor(g) {
    var average_stack = compute_avg_stack(g.players);
    var myself = g.players[g.in_action];

    var strength = (myself.stack > average_stack) ? (myself.stack / average_stack) : 0.5;

    if (g.current_buy_in < g.pot) {
        return strength;
    }
    else {
        return strength * g.pot / g.current_buy_in;
    }
}<commit_msg>game state<commit_after>var rank = require('./rank');

Array.prototype.contains = function (element) {
    return this.indexOf(element) > -1;
};

module.exports = {

    VERSION: "MadFoldBot v2.3",

    bet_request: function (game_state, bet) {
        return this.strategy1(game_state, bet);
    },

    showdown: function (game_state) {

    },

    strategy1: function (game_state, bet) {
        var our_bet = this.getBet(game_state);
        console.log('OUR BET: ' + our_bet);

        bet(our_bet);
    },

    getBet: function (game_state) {
        var all_cards = this.getAllCards(game_state);
        var myself = game_state.players[game_state.in_action];
        var call = game_state.current_buy_in - myself["bet"];

        var isAllIn = this.isAllIn(game_state);
        console.log('CURRENT CALL: ' + call);

        if (false && isAllIn) {
            console.log("WARNING - ALL IN!!!");

            if (game_state.community_cards.length < 1) {
                if (
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'A') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'Q' && myself.hole_cards[1].rank == 'Q') ||
                    (myself.hole_cards[0].rank == 'A' && myself.hole_cards[1].rank == 'K') ||
                    (myself.hole_cards[0].rank == 'K' && myself.hole_cards[1].rank == 'A')
                ) {
                } else {
                    return 0;
                }
            }
        } else {

        }

        if (game_state.community_cards.length < 1) {
            console.log('PREFLOP');
            // we're before flop
            if (lameCards(myself.hole_cards)) {
                console.log('LAME CARDS');
                return 0;
            } else {
                if (toNum(myself.hole_cards[1].rank) > 9 && toNum(myself.hole_cards[0].rank) > 9) {
                    console.log('HIGH CARDS. DOING CALL');
                    return call;
                }

                if (compute_chip_factor(game_state) > 3) {
                    console.log('CHIP FACTOR');
                    return call;
                }
                else {
                    return 0;
                }
            }
        }

        var our_hand = rank.rank(all_cards);

        console.log('OUR HAND');
        console.log(our_hand);

        if (our_hand.contains('flush')) {
            return 10000;
        }

        if (our_hand.contains('full_house')) {
            return 10000;
        }

        if (our_hand.contains('tree_of_a_kind')) {
            return 700;
        }

        if (our_hand.contains('two_pairs')) {
            return 250;
        }

        if (our_hand.contains('pair')) {
            return 100;
        }

        return 0;
    },

    isAllIn: function (game_state) {
        var players = game_state.players;

        for (var i in players) {
            if (i != game_state.in_action && players[i].status == "active" && players[i].stack == 0 && players[i].bet > 200) {
                return true;
            }
        }

        return false;
    },

    getAllCards: function (game_state) {
        var cards = [];
        var community_cards = game_state.community_cards;

        for (var p in game_state.players) {
            if (typeof game_state.players[p]['hole_cards'] != 'undefined') {
                cards = game_state.players[p]['hole_cards'];
            }
        }

        cards = cards.concat(community_cards);

        return cards;
    }

};

function toNum(c) {
    switch (c) {
        case 'J':
            return 11;
        case 'Q':
            return 12;
        case 'K':
            return 13;
        case 'A':
            return 14;

        default:
            return c;
    }
}

function lameCards(cards) {
    /* if (
     toNum(cards[0].rank) >= 12 || toNum(cards[1].rank) >= 12
     ) {
     return false;
     } else if (cards[0].rank == 'A' || cards[1].rank == 'A') {
     return false;
     }
     else */
    if (
        (toNum(cards[0].rank) < 4 || toNum(cards[1].rank) < 4) && cards[0].rank != cards[1].rank
    ) {
        return true
    } else {
        return false
    }
}

function compute_avg_stack(players) {
    var sum = 0;
    for (var i in players) {
        if (players[i].status == "active") {
            sum += players[i].stack;
        }
    }
    return sum / players.length;
}

function compute_chip_factor(g) {
    var average_stack = compute_avg_stack(g.players);
    var myself = g.players[g.in_action];

    var strength = (myself.stack > average_stack) ? (myself.stack / average_stack) : 0.5;

    if (g.current_buy_in < g.pot) {
        return strength;
    }
    else {
        return strength * g.pot / g.current_buy_in;
    }
}<|endoftext|>


<commit_before>/**
 *
 */
Ext.define('converter.Form', {
	extend: 'Ext.form.Panel',

    /* i18n */
    uploadFileLabel: "Upload File",
    selectFileButtonText: "Select File:",
    waitingMessageText: "Waiting...",
    /* ~i18n */

    width: 600,
    height: 400,

    initComponent: function() {

	    this.items = [{
				    	items: [{
					    	xtype: 'panel',
					        height: 300,
					        margin: 2
				        }]
	    			},
	    			{
	    				xtype: 'panel',
	    				items : this.getInstitutionButtons()
	    			},
	    			{
		                xtype: 'filefield',
		                name: 'uploadfile',
		                fieldLabel: this.uploadFileLabel,
		                msgTarget: 'side',
		                allowBlank: false,
		                anchor: '100%',
		                margin: 2,
		                buttonText: this.selectFileButtonText
	    			}],

		this.buttons = [{
			text: 'Upload',
		    handler: function() {
				if(this.isValid()) {
					this.submit({
						url: 'dataportal/uploadFile',
						waitMsg: this.waitingMessageText,
				        sucess: function(form, action) {

				        },
				        failure: function(form, action) {

				        }
				    })
				} else {
					// TODO is form is not valid
				}
		    }},{
		    	text: 'Cancel'
		    }]
    	this.callParent(arguments);
    },

    /**
     *
     */
	getInstitutionButtons: function() {

	}
});<commit_msg>Create converter institution buttons dinamically<commit_after>/**
 *
 */
Ext.define('converter.Form', {
	extend : 'Ext.form.Panel',

	/* i18n */
	uploadFileLabel : "Upload File",
	selectFileButtonText : "Select File:",
	waitingMessageText : "Waiting...",
	uploadButtonText : "Upload",
	cancelButtonText : 'Cancel',
	/* ~i18n */

	width : 600,
	height : 400,
	getInstitutionButtonsItems : [],

	institutionPanel : Ext.create('Ext.panel.Panel', {}),

	initComponent : function() {

		this.getInstitutionButtons();

		this.items = [ {
			items : [ {
				xtype : 'panel',
				height : 300,
				margin : 2
			} ]
		}, this.institutionPanel, {
			xtype : 'filefield',
			name : 'uploadfile',
			fieldLabel : this.uploadFileLabel,
			msgTarget : 'side',
			allowBlank : false,
			anchor : '100%',
			margin : 2,
			buttonText : this.selectFileButtonText
		} ],

		this.buttons = [ {
			text : this.uploadButtonText,
			handler : function() {
				if (this.isValid()) {
					this.submit({
						url : 'dataportal/uploadFile',
						waitMsg : this.waitingMessageText,
						sucess : function(form, action) {

						},
						failure : function(form, action) {

						}
					})
				} else {
					// TODO is form is not valid
				}
			}
		}, {
			text : this.cancelButtonText
		} ]
		this.callParent(arguments);
	},

	/**
	 *
	 */
	getInstitutionButtons : function() {

		Ext.define('Converter', {
			extend : 'Ext.data.Model',
			fields : [ 'name', 'institution_name', 'institution_realname',
					'institution_url' ]
		})

		var store = Ext.create('Ext.data.Store', {
			model : 'Converter',
			proxy : {
				type : 'ajax',
				url : 'converter',
				extraParams : {
					converters : true
				},
				reader : {
					type : 'xml',
					record : 'converter',
					root : 'converters'
				}
			}
		})

		var items = new Array();

		store.load({
			scope : this,
			callback : function(records, operation, success) {
				if (success) {
					for ( var indexRecord in records) {
						var record = records[indexRecord];
						this.institutionPanel.add(Ext.create('Ext.Button', {
							text : record.data.name,
							handler : this.assignConverter
						}))
					}
				}
			}
		});
	}
});<|endoftext|>


<commit_before>"use strict";
if (process.env.NODE_ENV === "test") {
  exports.osmbc_version = "1.8.4";
} else {
  exports.osmbc_version = "3.0.1b";
}

<commit_msg>Version<commit_after>"use strict";
if (process.env.NODE_ENV === "test") {
  exports.osmbc_version = "1.8.4";
} else {
  exports.osmbc_version = "3.0.1c";
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 United States Government as represented by the Administrator of the
 * National Aeronautics and Space Administration. All Rights Reserved.
 */
/**
 * It is basically a collection of KmlRecords.
 * @exports KmlParser
 */
define([
        '../../error/ArgumentError',
        '../../util/jszip',
        './KmlFileCache',
        './styles/KmlStyle',
        './styles/KmlStyleMap',
        './KmlTimeSpan',
        './KmlTimeStamp',
        '../../util/Logger',
        '../../util/Promise',
        '../../util/Remote',
        '../../util/XmlDocument',
        './KmlElements',
        './KmlObject'
    ],
    function (ArgumentError,
              JsZip,
              KmlFileCache,
              KmlStyle,
              KmlStyleMap,
              KmlTimeSpan,
              KmlTimeStamp,
              Logger,
              Promise,
              Remote,
              XmlDocument,
              KmlElements,
              KmlObject) {
        "use strict";

        /**
         * Constructs an object for Kml file. Applications usually don't call this constructor.
         * Parses associated KmlFile and allows user to draw the whole KmlFile in passed layer. The whole file is
         * rendered in one Layer.
         * @constructor
         * @param options {Object}
         * @param options.document {String} String representing the document if it is local.
         * @param options.url {String} Url of the remote document.
         * @param options.local {Boolean} True if the document is local.
         * @param options.controls {KmlControls[]} List of controls applied to this File.
         * @alias KmlFile
         * @classdesc Support for Kml File parsing and display.
         */
        var KmlFile = function (options) {
            var self = this;
            if (!options || (!options.document && !options.url)) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "KmlFile", "constructor", "invalidDocumentPassed")
                );
            }

            // Default values.
            options.local = options.local || false;
            this._controls = options.controls || null;

            var filePromise;
            if (options.local) {
                this._document = new XmlDocument(options.document).dom();
                filePromise = new Promise(function (resolve) {
                    window.setTimeout(function () {
                        resolve(self);
                    }, 0);
                });
                KmlFileCache.add('', filePromise);
                return filePromise;
            } else {
                // Load the document
                filePromise = new Promise(function (resolve) {
                    var promise = self.requestUrl(options.url, options);
                    promise.then(function (loadedDocument) {
                        var rootDocument;
                        if (options.url.indexOf('.kmz') == -1) {
                            rootDocument = loadedDocument;
                        } else {
                            var kmzFile = new JsZip();
                            kmzFile.load(loadedDocument);
                            kmzFile.files.forEach(function (file) {
                                if (file.endsWith(".kml") && rootDocument == null) {
                                    rootDocument = file.asText();
                                }
                            });
                        }
                        self._document = new XmlDocument(rootDocument).dom();
                        window.setTimeout(function () {
                            resolve(self);
                        }, 0);
                    });
                });
                KmlFileCache.add(options.url, filePromise);
                return filePromise;
            }
        };

        Object.defineProperties(KmlFile.prototype, {
            /**
             * Contains shapes present in the document. Cache so that we don't need to parse the document every time
             * it is passed through.
             * @type {KmlObject[]}
             * @memberof KmlFile.prototype
             * @readonly
             */
            shapes: {
                get: function () {
                    return this.parseDocument();
                }
            },

            /**
             * Root node of current document associated with this file.
             * @type {Node}
             * @memberof KmlFile.prototype
             * @readonly
             */
            node: {
                get: function () {
                    return this._document.getElementsByTagName("kml")[0];
                }
            }
        });

        /**
         * Calling method from KmlObject on current KmlFile.
         * @see KmlObject.prototype.parse
         */
        KmlFile.prototype.parseDocument = function () {
            return KmlObject.prototype.parse.call(this);
        };

        /**
         * It understands the name of the node and based on this name returns correct shape, which must be instantiated.
         * @param name
         * @returns {KmlObject} Descendant of KmlObject or null if none with given name exists.
         */
        KmlFile.prototype.retrieveElementForNode = KmlObject.prototype.retrieveElementForNode;

        KmlFile.prototype.doesAttributeExist = KmlObject.prototype.doesAttributeExist;

        KmlFile.prototype.getValueOfAttribute = KmlObject.prototype.getValueOfAttribute;

        KmlFile.prototype.retrieveFromCache = KmlObject.prototype.retrieveFromCache;

        KmlFile.prototype.parseOneNode = KmlObject.prototype.parseOneNode;

        KmlFile.prototype.instantiateDescendant = KmlObject.prototype.instantiateDescendant;

        /**
         * It renders all shapes, which are associated with current file.
         * @param options {Object}
         * @param options.layer {Layer} Layer into which the objects should be rendered.
         * @param options.controls {KmlControls[]} Controls to be notified when the file is updated.
         * @throws {ArgumentError} In case the layer into which it should be rendered isn't supplied
         */
        KmlFile.prototype.update = function (options) {
            if (!options.layer) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "KmlFile", "update", "Layer must be defined in order to update document.")
                );
            }

            options.controls = this._controls;
            this.shapes.forEach(function (shape) {
                shape.update(options);
            });
        };

        KmlFile.prototype.requestUrl = function (url, options) {
            options.url = url;
            if ((url.endsWith && url.endsWith(".kmz")) || (url.indexOf(".kmz") != -1)) {
                options.zip = true;
            } else {
                options.ajax = true;
            }

            return new Remote(options);
        };

        KmlFile.prototype.resolveStyle = function (pId) {
            var self = this;
            var id = pId.substring(pId.indexOf('#') + 1, pId.length);
            // It returns promise of the Style.
            return new Promise(function (resolve, reject) {
                var style;
                if(self._document.querySelector) {
                    style = self._document.querySelector("*[id='" + id + "']");
                } else {
                    style = self._document.getElementById(id);
                }
                if (!style || style == null) {
                    reject();
                }

                if(style.nodeName == KmlStyle.prototype.getTagNames()[0]) {
                    resolve(new KmlStyle({objectNode: style}));
                } else if(style.nodeName == KmlStyleMap.prototype.getTagNames()[0]) {
                    resolve(new KmlStyleMap({objectNode: style}));
                } else {
                    Logger.logMessage(Logger.LEVEL_WARNING, "KmlFile", "resolveStyle", "Style must contain either" +
                        " Style node or StyleMap node.");
                }
            });
        };

        return KmlFile;
    });
<commit_msg>Remote was moved.<commit_after>/*
 * Copyright (C) 2014 United States Government as represented by the Administrator of the
 * National Aeronautics and Space Administration. All Rights Reserved.
 */
/**
 * It is basically a collection of KmlRecords.
 * @exports KmlParser
 */
define([
        '../../error/ArgumentError',
        '../../util/jszip',
        './KmlFileCache',
        './styles/KmlStyle',
        './styles/KmlStyleMap',
        './KmlTimeSpan',
        './KmlTimeStamp',
        '../../util/Logger',
        '../../util/Promise',
        './util/Remote',
        '../../util/XmlDocument',
        './KmlElements',
        './KmlObject'
    ],
    function (ArgumentError,
              JsZip,
              KmlFileCache,
              KmlStyle,
              KmlStyleMap,
              KmlTimeSpan,
              KmlTimeStamp,
              Logger,
              Promise,
              Remote,
              XmlDocument,
              KmlElements,
              KmlObject) {
        "use strict";

        /**
         * Constructs an object for Kml file. Applications usually don't call this constructor.
         * Parses associated KmlFile and allows user to draw the whole KmlFile in passed layer. The whole file is
         * rendered in one Layer.
         * @constructor
         * @param options {Object}
         * @param options.document {String} String representing the document if it is local.
         * @param options.url {String} Url of the remote document.
         * @param options.local {Boolean} True if the document is local.
         * @param options.controls {KmlControls[]} List of controls applied to this File.
         * @alias KmlFile
         * @classdesc Support for Kml File parsing and display.
         */
        var KmlFile = function (options) {
            var self = this;
            if (!options || (!options.document && !options.url)) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "KmlFile", "constructor", "invalidDocumentPassed")
                );
            }

            // Default values.
            options.local = options.local || false;
            this._controls = options.controls || null;

            var filePromise;
            if (options.local) {
                this._document = new XmlDocument(options.document).dom();
                filePromise = new Promise(function (resolve) {
                    window.setTimeout(function () {
                        resolve(self);
                    }, 0);
                });
                KmlFileCache.add('', filePromise);
                return filePromise;
            } else {
                // Load the document
                filePromise = new Promise(function (resolve) {
                    var promise = self.requestUrl(options.url, options);
                    promise.then(function (loadedDocument) {
                        var rootDocument;
                        if (options.url.indexOf('.kmz') == -1) {
                            rootDocument = loadedDocument;
                        } else {
                            var kmzFile = new JsZip();
                            kmzFile.load(loadedDocument);
                            kmzFile.files.forEach(function (file) {
                                if (file.endsWith(".kml") && rootDocument == null) {
                                    rootDocument = file.asText();
                                }
                            });
                        }
                        self._document = new XmlDocument(rootDocument).dom();
                        window.setTimeout(function () {
                            resolve(self);
                        }, 0);
                    });
                });
                KmlFileCache.add(options.url, filePromise);
                return filePromise;
            }
        };

        Object.defineProperties(KmlFile.prototype, {
            /**
             * Contains shapes present in the document. Cache so that we don't need to parse the document every time
             * it is passed through.
             * @type {KmlObject[]}
             * @memberof KmlFile.prototype
             * @readonly
             */
            shapes: {
                get: function () {
                    return this.parseDocument();
                }
            },

            /**
             * Root node of current document associated with this file.
             * @type {Node}
             * @memberof KmlFile.prototype
             * @readonly
             */
            node: {
                get: function () {
                    return this._document.getElementsByTagName("kml")[0];
                }
            }
        });

        /**
         * Calling method from KmlObject on current KmlFile.
         * @see KmlObject.prototype.parse
         */
        KmlFile.prototype.parseDocument = function () {
            return KmlObject.prototype.parse.call(this);
        };

        /**
         * It understands the name of the node and based on this name returns correct shape, which must be instantiated.
         * @param name
         * @returns {KmlObject} Descendant of KmlObject or null if none with given name exists.
         */
        KmlFile.prototype.retrieveElementForNode = KmlObject.prototype.retrieveElementForNode;

        KmlFile.prototype.doesAttributeExist = KmlObject.prototype.doesAttributeExist;

        KmlFile.prototype.getValueOfAttribute = KmlObject.prototype.getValueOfAttribute;

        KmlFile.prototype.retrieveFromCache = KmlObject.prototype.retrieveFromCache;

        KmlFile.prototype.parseOneNode = KmlObject.prototype.parseOneNode;

        KmlFile.prototype.instantiateDescendant = KmlObject.prototype.instantiateDescendant;

        /**
         * It renders all shapes, which are associated with current file.
         * @param options {Object}
         * @param options.layer {Layer} Layer into which the objects should be rendered.
         * @param options.controls {KmlControls[]} Controls to be notified when the file is updated.
         * @throws {ArgumentError} In case the layer into which it should be rendered isn't supplied
         */
        KmlFile.prototype.update = function (options) {
            if (!options.layer) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "KmlFile", "update", "Layer must be defined in order to update document.")
                );
            }

            options.controls = this._controls;
            this.shapes.forEach(function (shape) {
                shape.update(options);
            });
        };

        KmlFile.prototype.requestUrl = function (url, options) {
            options.url = url;
            if ((url.endsWith && url.endsWith(".kmz")) || (url.indexOf(".kmz") != -1)) {
                options.zip = true;
            } else {
                options.ajax = true;
            }

            return new Remote(options);
        };

        KmlFile.prototype.resolveStyle = function (pId) {
            var self = this;
            var id = pId.substring(pId.indexOf('#') + 1, pId.length);
            // It returns promise of the Style.
            return new Promise(function (resolve, reject) {
                var style;
                if(self._document.querySelector) {
                    style = self._document.querySelector("*[id='" + id + "']");
                } else {
                    style = self._document.getElementById(id);
                }
                if (!style || style == null) {
                    reject();
                }

                if(style.nodeName == KmlStyle.prototype.getTagNames()[0]) {
                    resolve(new KmlStyle({objectNode: style}));
                } else if(style.nodeName == KmlStyleMap.prototype.getTagNames()[0]) {
                    resolve(new KmlStyleMap({objectNode: style}));
                } else {
                    Logger.logMessage(Logger.LEVEL_WARNING, "KmlFile", "resolveStyle", "Style must contain either" +
                        " Style node or StyleMap node.");
                }
            });
        };

        return KmlFile;
    });
<|endoftext|>


<commit_before>
$(document).ready(function(){

	var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

	};
		BrowserDetect.init();

	/***************************************************/
	/*************** HEADER ****************************/
	/***************************************************/

	/*************** USER LOGIN ************************/

	$('#sign-in').click(function(){
		$('#user-modal-body').empty().append('');
		$('#user-modal').modal('show');
		return false;
	});

	$('#user-modal').bind('authenticated',function(){
		$('#sign-in').hide();
		$('#user-dropdown').show();
		$('#jda-header-me').show();
		if(!_.isUndefined(window.jda))jda.app.userAuthenticated();
		return false;
	});

	$('#user-modal').bind('close',function(){$("#user-modal-close").trigger('click');});

	/*************** ACCOUNT SETTINGS ************************/

	$('#account-settings').click(function(){
		$('#user-modal-body').empty().append('');
		$('#user-modal').modal('show');
		return false;

	});

	/************  BUG REPORT **********************/

	$('.bug-report').click(function(e){e.stopPropagation();});

	$('.bug-report').parent().click(function(){
		$('.bug-unsubmitted').show();
		$('.bug-submitted').hide();
	});

	$('.close-bug').click(function(){
		$('.bug-report').parent().trigger('click');
	});

	$('.submit-bug').click(function(){

		var bug = new Backbone.Model({

			url:window.location.href,
			hash: window.location.hash.substr(1),
			description: $('.bug-description').val(),
			email: $('.bug-email').val(),
			browser: BrowserDetect.browser,
			version: BrowserDetect.version,
			os:BrowserDetect.OS,
			login:sessionStorage.getItem('user')

		});

		bug.url="../bugs/report.php";
		bug.save();
		$('.bug-description').attr('value','');
		$('.bug-unsubmitted').fadeOut('fast',function(){
				$('.bug-submitted').fadeIn();
		});

	});

	/*************** LANGUAGE TOGGLE ************************/
	$('#jda-language-toggle').find('.btn').click(function(){
		if(!$(this).hasClass('active')){
			console.log('switching languages');
			$('#jda-language-toggle').find('.btn').removeClass('active');
			$(this).addClass('active');
			console.log($(this).data('language'));
			if($(this).data('language')=='en') window.location =  window.location.href.replace('/ja/','/en/');
			else window.location =  window.location.href.replace('/en/','/ja/');
		}

	});

	$('.jda-home-featured-collection-text-block').height(Math.max($(window).height()-50, 600)).click(function(){

		window.open("search?#view_type=thumb&collection="+$(this).data('id')+"&content=all&","_self");

	});

	$(window).resize(function() {
      $('.jda-home-featured-collection').height(Math.max($(window).height()-50, 600));
  });

	// Shorthand the application namespace
	//http://documentcloud.github.com/visualsearch/
	VisualSearch = VS.init({
		container : $('.visual_search'),
		query     : '',
		callbacks : {

			loaded	: function(){

				if($(location).attr('href').indexOf('home')>=0){
					$('.VS-search-box').css('width','270px');
					$('#VS-search input').css('width', '200px');
				} else{
					$('.VS-search-box').css('width','500px');
					$('#VS-search input').css('width', '430px');
				}
				$("#jda-home-search-div, #search-bar").fadeTo('slow',1);
				$('#VS-search input').attr('placeholder', 'Explore the Archive');

				$('#VS-search input').css('padding-top', '9px');
				$('#VS-search input').focus(function(){
					//$(this).attr('placeholder', '');
					$(this).css('width', '3px');
				});

				$('#jda-go-button').click(function(){
					var query = VisualSearch.searchBox.value();
					window.location = 'search#q=' + query;
				});
			},

			search : function(){

			var facets = VisualSearch.searchQuery.models;

			var tagQuery = "tag:";
			var textQuery = "";
			//var usernameQuery = "";

			_.each(facets, function(facet){
				console.log(facet.get('category'));
				switch ( facet.get('category') )
				{
					case 'text':
						textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
						textQuery=textQuery.replace(/^#/, '');
						break;
					case 'tag':
						tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
						tagQuery=tagQuery.replace(/^#/, '');
						break;
					/*
					case 'user':
						usernameQuery = facet.get('value');
						break;
					*/
			    }
			});

			var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

			window.location = 'search#q=' + query;

			},

			clearSearch : function(){ $('input').val('');},
			// These are the facets that will be autocompleted in an empty input.
			facetMatches : function(callback)
			{
				callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag','text'
				]);
			},
			// These are the values that match specific categories, autocompleted
			// in a category's input field.  searchTerm can be used to filter the
			// list on the server-side, prior to providing a list to the widget.
			valueMatches : function(facet, searchTerm, callback)
			{
				switch (facet)
				{
					case 'user':
						callback([]);
						break;
					case 'tag':
						callback([]);
						break;
					case 'keyword':
						callback([]);
						break;
					case 'text':
						callback([]);
						break;
					case 'data:time & place':
						callback([]);
						break;
				}
			}
		} //callbacks
	});

	$('#jda-go-button').click(function(){
	  	var e = jQuery.Event("keydown");
		e.which = 13;

		//For whatever reason there are two ways of telling VS to search
		//based on whether the facet has been created yet or not
		if ( $(".search_facet_input_container input").length ){
			$(".search_facet_input_container input").trigger(e);
		} else{
			VisualSearch.searchBox.searchEvent(e);
		}

  		return false;
  	});

});<commit_msg>fixed homepage layout in FF and IE<commit_after>
$(document).ready(function(){

	var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

	};
		BrowserDetect.init();

	/***************************************************/
	/*************** HEADER ****************************/
	/***************************************************/

	/*************** USER LOGIN ************************/

	$('#sign-in').click(function(){
		$('#user-modal-body').empty().append('');
		$('#user-modal').modal('show');
		return false;
	});

	$('#user-modal').bind('authenticated',function(){
		$('#sign-in').hide();
		$('#user-dropdown').show();
		$('#jda-header-me').show();
		if(!_.isUndefined(window.jda))jda.app.userAuthenticated();
		return false;
	});

	$('#user-modal').bind('close',function(){$("#user-modal-close").trigger('click');});

	/*************** ACCOUNT SETTINGS ************************/

	$('#account-settings').click(function(){
		$('#user-modal-body').empty().append('');
		$('#user-modal').modal('show');
		return false;

	});

	/************  BUG REPORT **********************/

	$('.bug-report').click(function(e){e.stopPropagation();});

	$('.bug-report').parent().click(function(){
		$('.bug-unsubmitted').show();
		$('.bug-submitted').hide();
	});

	$('.close-bug').click(function(){
		$('.bug-report').parent().trigger('click');
	});

	$('.submit-bug').click(function(){

		var bug = new Backbone.Model({

			url:window.location.href,
			hash: window.location.hash.substr(1),
			description: $('.bug-description').val(),
			email: $('.bug-email').val(),
			browser: BrowserDetect.browser,
			version: BrowserDetect.version,
			os:BrowserDetect.OS,
			login:sessionStorage.getItem('user')

		});

		bug.url="../bugs/report.php";
		bug.save();
		$('.bug-description').attr('value','');
		$('.bug-unsubmitted').fadeOut('fast',function(){
				$('.bug-submitted').fadeIn();
		});

	});

	/*************** LANGUAGE TOGGLE ************************/
	$('#jda-language-toggle').find('.btn').click(function(){
		if(!$(this).hasClass('active')){
			console.log('switching languages');
			$('#jda-language-toggle').find('.btn').removeClass('active');
			$(this).addClass('active');
			console.log($(this).data('language'));
			if($(this).data('language')=='en') window.location =  window.location.href.replace('/ja/','/en/');
			else window.location =  window.location.href.replace('/en/','/ja/');
		}

	});

	$('.jda-home-featured-collection').height(Math.max($(window).height()-50, 600));

	$('.jda-home-featured-collection-text-block').click(function(){

		window.open("search?#view_type=thumb&collection="+$(this).data('id')+"&content=all&","_self");

	});

	$(window).resize(function() {
      $('.jda-home-featured-collection').height(Math.max($(window).height()-50, 600));
  });

	// Shorthand the application namespace
	//http://documentcloud.github.com/visualsearch/
	VisualSearch = VS.init({
		container : $('.visual_search'),
		query     : '',
		callbacks : {

			loaded	: function(){

				if($(location).attr('href').indexOf('home')>=0){
					$('.VS-search-box').css('width','270px');
					$('#VS-search input').css('width', '200px');
				} else{
					$('.VS-search-box').css('width','500px');
					$('#VS-search input').css('width', '430px');
				}
				$("#jda-home-search-div, #search-bar").fadeTo('slow',1);
				$('#VS-search input').attr('placeholder', 'Explore the Archive');

				$('#VS-search input').css('padding-top', '9px');
				$('#VS-search input').focus(function(){
					//$(this).attr('placeholder', '');
					$(this).css('width', '3px');
				});

				$('#jda-go-button').click(function(){
					var query = VisualSearch.searchBox.value();
					window.location = 'search#q=' + query;
				});
			},

			search : function(){

			var facets = VisualSearch.searchQuery.models;

			var tagQuery = "tag:";
			var textQuery = "";
			//var usernameQuery = "";

			_.each(facets, function(facet){
				console.log(facet.get('category'));
				switch ( facet.get('category') )
				{
					case 'text':
						textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
						textQuery=textQuery.replace(/^#/, '');
						break;
					case 'tag':
						tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
						tagQuery=tagQuery.replace(/^#/, '');
						break;
					/*
					case 'user':
						usernameQuery = facet.get('value');
						break;
					*/
			    }
			});

			var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

			window.location = 'search#q=' + query;

			},

			clearSearch : function(){ $('input').val('');},
			// These are the facets that will be autocompleted in an empty input.
			facetMatches : function(callback)
			{
				callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag','text'
				]);
			},
			// These are the values that match specific categories, autocompleted
			// in a category's input field.  searchTerm can be used to filter the
			// list on the server-side, prior to providing a list to the widget.
			valueMatches : function(facet, searchTerm, callback)
			{
				switch (facet)
				{
					case 'user':
						callback([]);
						break;
					case 'tag':
						callback([]);
						break;
					case 'keyword':
						callback([]);
						break;
					case 'text':
						callback([]);
						break;
					case 'data:time & place':
						callback([]);
						break;
				}
			}
		} //callbacks
	});

	$('#jda-go-button').click(function(){
	  	var e = jQuery.Event("keydown");
		e.which = 13;

		//For whatever reason there are two ways of telling VS to search
		//based on whether the facet has been created yet or not
		if ( $(".search_facet_input_container input").length ){
			$(".search_facet_input_container input").trigger(e);
		} else{
			VisualSearch.searchBox.searchEvent(e);
		}

  		return false;
  	});

});<|endoftext|>


<commit_before>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W', '<left>', '<right>', '<up>'],
    heading: [-60, 60, 0, -60, 60, 0],
    shift: [0, 0, 8, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['A', 'D', '<left>', '<right>'],
    heading: [-180, 180, -180, 180],
    shift: [8, 8, 8, 8],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
  this.update()
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position)]
  var inside =  tile.children[0].contains(current.position)
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position[0], tile.transform.position[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
  self.position = self.geometry.transform.position
  self.update()
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.update = function() {
  this.position = this.geometry.transform.position
  this.angle = this.geometry.transform.angle
  this.scale = this.geometry.transform.scale
}<commit_msg>Add reverse button inside path<commit_after>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W', '<left>', '<right>', '<up>'],
    heading: [-60, 60, 0, -60, 60, 0],
    shift: [0, 0, 8, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['W', 'S', '<up>', '<down>'],
    heading: [0, 0, 0, 0],
    shift: [1, -1, 1, -1],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
  this.update()
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position)]
  var inside =  tile.children[0].contains(current.position)
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position[0], tile.transform.position[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
    self.movement.path.reset()
    self.movement.path.clear()
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
  self.position = self.geometry.transform.position
  self.update()
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.update = function() {
  this.position = this.geometry.transform.position
  this.angle = this.geometry.transform.angle
  this.scale = this.geometry.transform.scale
}<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.layout = "2.5.2";
}
<commit_msg>Update version string to 2.5.3-pre.1<commit_after>if (enyo && enyo.version) {
	enyo.version.layout = "2.5.3-pre.1";
}
<|endoftext|>


<commit_before>// REACT COMPONENTS
import React from 'react';
import {
  Table
} from 'semantic-ui-react';

// CUSTOM COMPONENTS
// Both the table and graph should just be added to a results page, but
// this will do for now

// BENEFIT LOGIC
import { getSNAPBenefits } from '../programs/federal/snap';
import { getHousingBenefit } from '../programs/massachusetts/housing';

// OBJECT MANIPULATION
import { cloneDeep } from 'lodash';

const getSignSymbol = function ( num ) {
  if ( num > 0 ) { return '+'; }
  else if ( num < 0 ) { return '-'; }
  else { return ''; }
};  // End getSignSymbol()

const BenefitsTable = function ( props ) {

  var client        = props.client,
      currentClient = cloneDeep( client ),
      futureClient  = cloneDeep( currentClient );
  // Hack because everything's using future value instead
  // of just using current value.
  currentClient.future.earned = currentClient.current.earned;

  var SNAPBenefitCurrent  = client.current.hasSnap ? Math.round( getSNAPBenefits( client, 'current' ) * 12 ) : 0,
      SNAPBenefitFuture   = client.current.hasSnap ? Math.round( getSNAPBenefits( client, 'future' ) * 12 ) : 0,
      SNAPDiff            = SNAPBenefitFuture - SNAPBenefitCurrent,
      sec8BenefitCurrent  = client.current.hasHousing ? Math.round( getHousingBenefit( client ) * 12 ) : 0,
      sec8BenefitFuture   = client.current.hasHousing ? Math.round( getHousingBenefit( client ) * 12 ) : 0,
      sec8Diff            = sec8BenefitFuture - sec8BenefitCurrent,
      totalBenefitCurrent = SNAPBenefitCurrent + sec8BenefitCurrent,
      totalBenefitFuture  = SNAPBenefitFuture + sec8BenefitFuture,
      totalDiff           = SNAPDiff + sec8Diff,
      incomeCurrent       = Math.round( currentClient.current.earned * 12 ),
      incomeFuture        = Math.round( futureClient.future.earned * 12 ),
      incomeDiff          = incomeFuture - incomeCurrent,
      netCurrent          = totalBenefitCurrent + incomeCurrent,
      netFuture           = totalBenefitFuture + incomeFuture,
      netDiff             = totalDiff + incomeDiff;

const   columnHeaderStyle = {
                            background: 'rgba(0, 181, 173, 1)',
                            color: 'white',
                            fontSize: '1.3em',
                            fontWeight: 900,
                            textAlign: 'center',
                            borderRadius: 'inherit',
                            letterSpacing: '0.02em',
                            }
      , totalsRowStyle    = {
                            borderTop: "2px solid rgba(0, 181, 173, 1)",
                            fontWeight: 700,
                            fontSize: '1.1em',
                            padingTop: '0.25em'
                              }
      , rowHeaderStyle    = {
                    fontSize: '1.1em',
                    fontWeight: 700,
                    textAlign: 'left'
                    }
      , totalsRowHeaderStyle = {
                    fontSize: '1.2em',
                    fontWeight: 700,
                    textAlign: 'left',
                    borderTop: "2px solid rgba(0, 181, 173, 1)",
                    padingTop: '0.25em'

      };

const SNAPBenefitRow = function( props ){
  if(!currentClient.current.hasSnap ) return (null)
    return (

SNAP

${SNAPBenefitCurrent} / year

${SNAPBenefitFuture} / year

{ getSignSymbol(SNAPDiff) } ${Math.abs(SNAPDiff)} / year

    )
  };

const Sec8BenefitRow  = function( props ){
  if(!currentClient.current.hasHousing) return (null)
    return (

Section 8 Housing

${sec8BenefitCurrent} / year

${sec8BenefitFuture} / year

{ getSignSymbol(sec8Diff) } ${Math.abs(sec8Diff)} / year

    )
};

const TotalBenefitsRow = function( props ){
  if(!currentClient.current.hasSnap || !currentClient.current.hasHousing) return (null)
    return(

Total Benefits

${totalBenefitCurrent} / year

${totalBenefitFuture} / year

{ getSignSymbol(totalDiff) } ${Math.abs(totalDiff)} / year

    )
};

const IncomeRow = function ( props ) {
    return (

Income

${incomeCurrent} / year

${incomeFuture} / year

{ getSignSymbol(incomeDiff) } ${Math.abs(incomeDiff)} / year

    )
};

const TotalsRow = function ( props ) {
    return (

Net Total

${netCurrent} / year

${netFuture} / year

{ getSignSymbol(netDiff) } ${Math.abs(netDiff)} / year

    )
  };

  return (

Benefit

Current Benefits

New Estimate

Difference

          <SNAPBenefitRow client={currentClient} />
          <Sec8BenefitRow client={currentClient} />
          <TotalBenefitsRow client={currentClient} />
          <IncomeRow />
          <TotalsRow />

  )

};  // End BenefitsTable(<>)

export {
	BenefitsTable
};
<commit_msg>Fixes #377, housing current result changes to future result.<commit_after>// REACT COMPONENTS
import React from 'react';
import {
  Table
} from 'semantic-ui-react';

// CUSTOM COMPONENTS
// Both the table and graph should just be added to a results page, but
// this will do for now

// BENEFIT LOGIC
import { getSNAPBenefits } from '../programs/federal/snap';
import { getHousingBenefit } from '../programs/massachusetts/housing';

// OBJECT MANIPULATION
import { cloneDeep } from 'lodash';

const getSignSymbol = function ( num ) {
  if ( num > 0 ) { return '+'; }
  else if ( num < 0 ) { return '-'; }
  else { return ''; }
};  // End getSignSymbol()

const BenefitsTable = function ( props ) {

  var client = cloneDeep( props.client ),
      curr   = client.current;

  var SNAPBenefitCurrent  = curr.hasSnap ? Math.round( getSNAPBenefits( client, 'current' ) * 12 ) : 0,
      SNAPBenefitFuture   = curr.hasSnap ? Math.round( getSNAPBenefits( client, 'future' ) * 12 ) : 0,
      SNAPDiff            = SNAPBenefitFuture - SNAPBenefitCurrent,
      sec8BenefitCurrent  = curr.hasHousing ? Math.round( (curr.contractRent - curr.rentShare) * 12 ) : 0,
      sec8BenefitFuture   = curr.hasHousing ? Math.round( getHousingBenefit( client ) * 12 ) : 0,
      sec8Diff            = sec8BenefitFuture - sec8BenefitCurrent,
      totalBenefitCurrent = SNAPBenefitCurrent + sec8BenefitCurrent,
      totalBenefitFuture  = SNAPBenefitFuture + sec8BenefitFuture,
      totalDiff           = SNAPDiff + sec8Diff,
      incomeCurrent       = Math.round( curr.earned * 12 ),
      incomeFuture        = Math.round( client.future.earned * 12 ),
      incomeDiff          = incomeFuture - incomeCurrent,
      netCurrent          = totalBenefitCurrent + incomeCurrent,
      netFuture           = totalBenefitFuture + incomeFuture,
      netDiff             = totalDiff + incomeDiff;

const   columnHeaderStyle = {
                            background: 'rgba(0, 181, 173, 1)',
                            color: 'white',
                            fontSize: '1.3em',
                            fontWeight: 900,
                            textAlign: 'center',
                            borderRadius: 'inherit',
                            letterSpacing: '0.02em',
                            }
      , totalsRowStyle    = {
                            borderTop: "2px solid rgba(0, 181, 173, 1)",
                            fontWeight: 700,
                            fontSize: '1.1em',
                            padingTop: '0.25em'
                              }
      , rowHeaderStyle    = {
                    fontSize: '1.1em',
                    fontWeight: 700,
                    textAlign: 'left'
                    }
      , totalsRowHeaderStyle = {
                    fontSize: '1.2em',
                    fontWeight: 700,
                    textAlign: 'left',
                    borderTop: "2px solid rgba(0, 181, 173, 1)",
                    padingTop: '0.25em'

      };

const SNAPBenefitRow = function( props ){
  if(!client.current.hasSnap ) return (null)
    return (

SNAP

${SNAPBenefitCurrent} / year

${SNAPBenefitFuture} / year

{ getSignSymbol(SNAPDiff) } ${Math.abs(SNAPDiff)} / year

    )
  };

const Sec8BenefitRow  = function( props ){
  if(!client.current.hasHousing) return (null)
    return (

Section 8 Housing

${sec8BenefitCurrent} / year

${sec8BenefitFuture} / year

{ getSignSymbol(sec8Diff) } ${Math.abs(sec8Diff)} / year

    )
};

const TotalBenefitsRow = function( props ){
  if(!client.current.hasSnap || !client.current.hasHousing) return (null)
    return(

Total Benefits

${totalBenefitCurrent} / year

${totalBenefitFuture} / year

{ getSignSymbol(totalDiff) } ${Math.abs(totalDiff)} / year

    )
};

const IncomeRow = function ( props ) {
    return (

Income

${incomeCurrent} / year

${incomeFuture} / year

{ getSignSymbol(incomeDiff) } ${Math.abs(incomeDiff)} / year

    )
};

const TotalsRow = function ( props ) {
    return (

Net Total

${netCurrent} / year

${netFuture} / year

{ getSignSymbol(netDiff) } ${Math.abs(netDiff)} / year

    )
  };

  return (

Benefit

Current Benefits

New Estimate

Difference

          <SNAPBenefitRow client={client} />
          <Sec8BenefitRow client={client} />
          <TotalBenefitsRow client={client} />
          <IncomeRow />
          <TotalsRow />

  )

};  // End BenefitsTable(<>)

export {
	BenefitsTable
};
<|endoftext|>


<commit_before>angular.module('appControllers').controller('TrafficCtrl', TrafficCtrl); // get the main module contollers set
TrafficCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies

// create our controller function with all necessary logic
function TrafficCtrl($rootScope, $scope, $state, $http, $interval) {

	$scope.$parent.helppage = 'plates/traffic-help.html';
	$scope.data_list = [];

	function utcTimeString(epoc) {
		var time = "";
		var val;
		var d = new Date(epoc);
		val = d.getUTCHours();
		time += (val < 10 ? "0" + val : "" + val);
		val = d.getUTCMinutes();
		time += ":" + (val < 10 ? "0" + val : "" + val);
		val = d.getUTCSeconds();
		time += ":" + (val < 10 ? "0" + val : "" + val);
		time += "Z";
		return time;
	}

	function dmsString(val) {
		return [0 | val,
				'° ',
				0 | (val < 0 ? val = -val : val) % 1 * 60,
				"' ",
				0 | val * 60 % 1 * 60,
				'"'].join('');
	}

	function setAircraft(obj, new_traffic) {
		new_traffic.icao_int = obj.Icao_addr;
		new_traffic.icao = obj.Icao_addr.toString(16).toUpperCase();
		new_traffic.tail = obj.Tail;
		new_traffic.lat = dmsString(obj.Lat);
		new_traffic.lon = dmsString(obj.Lng);
		var n = Math.round(obj.Alt / 25) * 25;
		new_traffic.alt = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		new_traffic.heading = Math.round(obj.Track / 5) * 5;
		var s = Math.round(obj.Speed / 5) * 5;
		if (obj.Speed_valid) {
			new_traffic.speed = s.toString();
		} else {
			new_traffic.speed = "---";
		}
		new_traffic.vspeed = Math.round(obj.Vvel / 100) * 100
		new_traffic.age = Date.parse(obj.Last_seen);
		new_traffic.time = utcTimeString(new_traffic.age);
		new_traffic.src = obj.Last_source; // 1=ES, 2=UAT
		// return new_aircraft;
	}

	function connect($scope) {
		if (($scope === undefined) || ($scope === null))
			return; // we are getting called once after clicking away from the status page

		if (($scope.socket === undefined) || ($scope.socket === null)) {
			socket = new WebSocket(URL_TRAFFIC_WS);
			$scope.socket = socket; // store socket in scope for enter/exit usage
		}

		$scope.ConnectState = "Disconnected";

		socket.onopen = function (msg) {
			// $scope.ConnectStyle = "label-success";
			$scope.ConnectState = "Connected";
		};

		socket.onclose = function (msg) {
			// $scope.ConnectStyle = "label-danger";
			$scope.ConnectState = "Disconnected";
			$scope.$apply();
			setTimeout(connect, 1000);
		};

		socket.onerror = function (msg) {
			// $scope.ConnectStyle = "label-danger";
			$scope.ConnectState = "Problem";
			$scope.$apply();
		};

		socket.onmessage = function (msg) {
			console.log('Received traffic update.')

			var message = JSON.parse(msg.data);
			$scope.raw_data = angular.toJson(msg.data, true);

			if (message.Position_valid) {
				// we need to use an array so AngularJS can perform sorting; it also means we need to loop to find an aircraft in the traffic set
				var found = false;
				for (var i = 0, len = $scope.data_list.length; i < len; i++) {
					if ($scope.data_list[i].icao_int === message.Icao_addr) {
						setAircraft(message, $scope.data_list[i]);
						found = true;
						break;
					}
				}
				if (!found) {
					var new_traffic = {};
					setAircraft(message, new_traffic);
					$scope.data_list.unshift(new_traffic); // add to start of array
				}
				$scope.$apply();
			}
		};
	}

	// perform cleanup every 60 seconds
	var clearStaleTraffic = $interval(function () {
		// remove stail aircraft = anything more than 180 seconds without and update
		var dirty = false;
		var cutoff = Date.now() - (180 * 1000);

		for (var i = len = $scope.data_list.length; i > 0; i--) {
			if ($scope.data_list[i - 1].age < cutoff) {
				$scope.data_list.splice(i - 1, 1);
				dirty = true;
			}
		}
		if (dirty) {
			$scope.raw_data = "";
			$scope.$apply();
		}
	}, (1000 * 60), 0, false);

	$state.get('traffic').onEnter = function () {
		// everything gets handled correctly by the controller
	};

	$state.get('traffic').onExit = function () {
		// disconnect from the socket
		if (($scope.socket !== undefined) && ($scope.socket !== null)) {
			$scope.socket.close();
			$scope.socket = null;
		}
		// stop stale traffic cleanup
		$interval.cancel(clearStaleTraffic);
	};

	// Traffic Controller tasks
	connect($scope); // connect - opens a socket and listens for messages
};<commit_msg>Blank out missing heading in traffic UI<commit_after>angular.module('appControllers').controller('TrafficCtrl', TrafficCtrl); // get the main module contollers set
TrafficCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies

// create our controller function with all necessary logic
function TrafficCtrl($rootScope, $scope, $state, $http, $interval) {

	$scope.$parent.helppage = 'plates/traffic-help.html';
	$scope.data_list = [];

	function utcTimeString(epoc) {
		var time = "";
		var val;
		var d = new Date(epoc);
		val = d.getUTCHours();
		time += (val < 10 ? "0" + val : "" + val);
		val = d.getUTCMinutes();
		time += ":" + (val < 10 ? "0" + val : "" + val);
		val = d.getUTCSeconds();
		time += ":" + (val < 10 ? "0" + val : "" + val);
		time += "Z";
		return time;
	}

	function dmsString(val) {
		return [0 | val,
				'° ',
				0 | (val < 0 ? val = -val : val) % 1 * 60,
				"' ",
				0 | val * 60 % 1 * 60,
				'"'].join('');
	}

	function setAircraft(obj, new_traffic) {
		new_traffic.icao_int = obj.Icao_addr;
		new_traffic.icao = obj.Icao_addr.toString(16).toUpperCase();
		new_traffic.tail = obj.Tail;
		new_traffic.lat = dmsString(obj.Lat);
		new_traffic.lon = dmsString(obj.Lng);
		var n = Math.round(obj.Alt / 25) * 25;
		new_traffic.alt = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		new_traffic.heading = Math.round(obj.Track / 5) * 5;
		var s = Math.round(obj.Speed / 5) * 5;
		if (obj.Speed_valid) {
			new_traffic.speed = s.toString();
			new_traffic.heading = Math.round(obj.Track / 5) * 5;
		} else {
			new_traffic.speed = "---";
			new_traffic.heading = "---";
		}
		new_traffic.vspeed = Math.round(obj.Vvel / 100) * 100
		new_traffic.age = Date.parse(obj.Last_seen);
		new_traffic.time = utcTimeString(new_traffic.age);
		new_traffic.src = obj.Last_source; // 1=ES, 2=UAT
		// return new_aircraft;
	}

	function connect($scope) {
		if (($scope === undefined) || ($scope === null))
			return; // we are getting called once after clicking away from the status page

		if (($scope.socket === undefined) || ($scope.socket === null)) {
			socket = new WebSocket(URL_TRAFFIC_WS);
			$scope.socket = socket; // store socket in scope for enter/exit usage
		}

		$scope.ConnectState = "Disconnected";

		socket.onopen = function (msg) {
			// $scope.ConnectStyle = "label-success";
			$scope.ConnectState = "Connected";
		};

		socket.onclose = function (msg) {
			// $scope.ConnectStyle = "label-danger";
			$scope.ConnectState = "Disconnected";
			$scope.$apply();
			setTimeout(connect, 1000);
		};

		socket.onerror = function (msg) {
			// $scope.ConnectStyle = "label-danger";
			$scope.ConnectState = "Problem";
			$scope.$apply();
		};

		socket.onmessage = function (msg) {
			console.log('Received traffic update.')

			var message = JSON.parse(msg.data);
			$scope.raw_data = angular.toJson(msg.data, true);

			if (message.Position_valid) {
				// we need to use an array so AngularJS can perform sorting; it also means we need to loop to find an aircraft in the traffic set
				var found = false;
				for (var i = 0, len = $scope.data_list.length; i < len; i++) {
					if ($scope.data_list[i].icao_int === message.Icao_addr) {
						setAircraft(message, $scope.data_list[i]);
						found = true;
						break;
					}
				}
				if (!found) {
					var new_traffic = {};
					setAircraft(message, new_traffic);
					$scope.data_list.unshift(new_traffic); // add to start of array
				}
				$scope.$apply();
			}
		};
	}

	// perform cleanup every 60 seconds
	var clearStaleTraffic = $interval(function () {
		// remove stail aircraft = anything more than 180 seconds without and update
		var dirty = false;
		var cutoff = Date.now() - (180 * 1000);

		for (var i = len = $scope.data_list.length; i > 0; i--) {
			if ($scope.data_list[i - 1].age < cutoff) {
				$scope.data_list.splice(i - 1, 1);
				dirty = true;
			}
		}
		if (dirty) {
			$scope.raw_data = "";
			$scope.$apply();
		}
	}, (1000 * 60), 0, false);

	$state.get('traffic').onEnter = function () {
		// everything gets handled correctly by the controller
	};

	$state.get('traffic').onExit = function () {
		// disconnect from the socket
		if (($scope.socket !== undefined) && ($scope.socket !== null)) {
			$scope.socket.close();
			$scope.socket = null;
		}
		// stop stale traffic cleanup
		$interval.cancel(clearStaleTraffic);
	};

	// Traffic Controller tasks
	connect($scope); // connect - opens a socket and listens for messages
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 DeNA Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

"use strict";

var jsx = require("./interface");

var seen = {};

function load(root) {
	var scripts = document.getElementsByTagName("script");

	for (var i = 0, l = scripts.length; i < l; ++i) {
		var script = scripts[i];
		if(script.type === "application/jsx") {
			var id = script.src ? script.src : script.innerHTML;
			if (seen.hasOwnProperty(id)) {
				continue;
			}
			seen[id] = true;

			var t0 = Date.now();

			var platform = new jsx.BrowserPlatform(root);
			var c = new jsx.Compiler(platform);
			var o = new jsx.Optimizer();
			var emitter = new jsx.JavaScriptEmitter(platform);
			c.setEmitter(emitter);

			var sourceFile;
			if(script.src) {
				sourceFile = script.src.replace(/^.*\//, "");
			}
			else {
				sourceFile = "<script>";
				platform.setContent(sourceFile, script.innerHTML);
			}
			c.addSourceFile(null, sourceFile);

			if(jsx.optimizationLevel > 0) {
				var optimizeCommands = [ "lto", "no-assert", "fold-const", "return-if", "inline", "dce", "unbox", "fold-const", "lcse", "dce", "fold-const", "array-length" ];
				o.setup(optimizeCommands);
				o.setEnableRunTimeTypeCheck(false);
				emitter.setEnableRunTimeTypeCheck(false);
			}

			c.setOptimizer(o);

			if(! c.compile()) {
				throw new Error("Failed to compile!");
			}

			var output = emitter.getOutput(sourceFile);

			if(jsx.optimizationLevel > 1) {
				output = platform.applyClosureCompiler(output, "SIMPLE_OPTIMIZATIONS");
			}

			var compiledScript = document.createElement("script");
			var scriptSection  = document.createTextNode(output);
			compiledScript.appendChild(scriptSection);
			script.parentNode.appendChild(compiledScript);

			console.log("jsx-script-loader: load %s in %d ms.",
					sourceFile, (Date.now() - t0));

			var applicationArguments = script.getAttribute("data-arguments");
			if (applicationArguments) {
				var args = JSON.parse(applicationArguments);
				if (args instanceof Array) {
					for (var i = 0; i < args.length; ++i) {
						if (typeof args[i]  !== "string") {
							throw new TypeError("Not an array of string: arguments[i] is " + JSON.stringify(args[i]));
						}
					}
				}
				else {
					throw new TypeError("Not an array of string: " + applicationArguments);
				}
				platform.debug("run _Main.main()@%s with %s", sourceFile, applicationArguments);
				JSX.require(sourceFile)._Main.main$AS(args);
			}
		}
	}
};

exports.ScriptLoader = {
	load: load
};

window.addEventListener("load", function(e) {
	var root = "..";
	try {
		var matched = location.pathname.match(/\/try(?:-on-web)?\/(.*)\/[^\/]*$/);
		root = matched[1].replace(/[^\/]+/g, "..");

	} catch (err) { }

	load(root);
});

<commit_msg>Revert "[web] temporary off "unclassify" from web"<commit_after>/*
 * Copyright (c) 2012 DeNA Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

"use strict";

var jsx = require("./interface");

var seen = {};

function load(root) {
	var scripts = document.getElementsByTagName("script");

	for (var i = 0, l = scripts.length; i < l; ++i) {
		var script = scripts[i];
		if(script.type === "application/jsx") {
			var id = script.src ? script.src : script.innerHTML;
			if (seen.hasOwnProperty(id)) {
				continue;
			}
			seen[id] = true;

			var t0 = Date.now();

			var platform = new jsx.BrowserPlatform(root);
			var c = new jsx.Compiler(platform);
			var o = new jsx.Optimizer();
			var emitter = new jsx.JavaScriptEmitter(platform);
			c.setEmitter(emitter);

			var sourceFile;
			if(script.src) {
				sourceFile = script.src.replace(/^.*\//, "");
			}
			else {
				sourceFile = "<script>";
				platform.setContent(sourceFile, script.innerHTML);
			}
			c.addSourceFile(null, sourceFile);

			if(jsx.optimizationLevel > 0) {
				var optimizeCommands = [ "lto", "no-assert", "fold-const", "return-if", "inline", "dce", "unbox", "fold-const", "lcse", "dce", "fold-const", "array-length", "unclassify" ];
				o.setup(optimizeCommands);
				o.setEnableRunTimeTypeCheck(false);
				emitter.setEnableRunTimeTypeCheck(false);
			}

			c.setOptimizer(o);

			if(! c.compile()) {
				throw new Error("Failed to compile!");
			}

			var output = emitter.getOutput(sourceFile);

			if(jsx.optimizationLevel > 1) {
				output = platform.applyClosureCompiler(output, "SIMPLE_OPTIMIZATIONS");
			}

			var compiledScript = document.createElement("script");
			var scriptSection  = document.createTextNode(output);
			compiledScript.appendChild(scriptSection);
			script.parentNode.appendChild(compiledScript);

			console.log("jsx-script-loader: load %s in %d ms.",
					sourceFile, (Date.now() - t0));

			var applicationArguments = script.getAttribute("data-arguments");
			if (applicationArguments) {
				var args = JSON.parse(applicationArguments);
				if (args instanceof Array) {
					for (var i = 0; i < args.length; ++i) {
						if (typeof args[i]  !== "string") {
							throw new TypeError("Not an array of string: arguments[i] is " + JSON.stringify(args[i]));
						}
					}
				}
				else {
					throw new TypeError("Not an array of string: " + applicationArguments);
				}
				platform.debug("run _Main.main()@%s with %s", sourceFile, applicationArguments);
				JSX.require(sourceFile)._Main.main$AS(args);
			}
		}
	}
};

exports.ScriptLoader = {
	load: load
};

window.addEventListener("load", function(e) {
	var root = "..";
	try {
		var matched = location.pathname.match(/\/try(?:-on-web)?\/(.*)\/[^\/]*$/);
		root = matched[1].replace(/[^\/]+/g, "..");

	} catch (err) { }

	load(root);
});

<|endoftext|>


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