<commit_before>'use strict';

var smtp_test_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
        },
        {'smtp_connect': 1}
    );
};

var smtp_save_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.just_saved_credentials) {
                form.find('.credentials').attr('disabled', true);
                form.find('.save_smtp_connection').hide();
                form.find('.smtp_password').val('');
                form.find('.smtp_password').attr('placeholder', '[saved]');
                form.append('<input type="submit" value="Forget" class="forget_smtp_connection" />');
                $('.forget_smtp_connection').on('click', smtp_forget_action);
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_save': 1}
    );
};

var smtp_forget_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.just_forgot_credentials) {
                form.find('.credentials').prop('disabled', false);
                form.find('.credentials').val('');
                form.append('<input type="submit" value="Save" class="save_smtp_connection" />');
                $('.save_smtp_connection').on('click', smtp_save_action);
                $('.forget_smtp_connection', form).remove();
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_forget': 1}
    );
};

var smtp_delete_action = function(event) {
    if (!hm_delete_prompt()) {
        return false;
    }
    event.preventDefault();
    Hm_Notices.hide(true);
    var form = $(this).parent();
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.deleted_server_id > -1 ) {
                form.parent().remove();
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_delete': 1}
    );
};

var smtp_delete_draft = function(id) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_delete_draft'},
        {'name': 'draft_id', 'value': id}],
        function(res) {
            if (res.draft_id != -1) {
                $('.draft_'+id).remove();
                $('.draft_list').toggle();
            }
        }
    );
};

var save_compose_state = function(no_files, notice) {
    var no_icon = true;
    if (notice) {
        no_icon = false;
    }
    var body = $('.compose_body').val();
    var subject = $('.compose_subject').val();
    var to = $('.compose_to').val();
    var smtp = $('.compose_server').val();
    var cc = $('.compose_cc').val();
    var bcc = $('.compose_bcc').val();
    var inreplyto = $('.compose_in_reply_to').val();
    var draft_id = $('.compose_draft_id').val();
    if (globals.draft_state == body+subject+to+smtp+cc+bcc) {
        return;
    }
    globals.draft_state = body+subject+to+smtp+cc+bcc;

    $('.smtp_send').prop('disabled', true);
    $('.smtp_send').addClass('disabled_input');
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_save_draft'},
        {'name': 'draft_body', 'value': body},
        {'name': 'draft_id', 'value': draft_id},
        {'name': 'draft_smtp', 'value': smtp},
        {'name': 'draft_subject', 'value': subject},
        {'name': 'draft_cc', 'value': cc},
        {'name': 'draft_bcc', 'value': bcc},
        {'name': 'draft_notice', 'value': notice},
        {'name': 'draft_in_reply_to', 'value': inreplyto},
        {'name': 'delete_uploaded_files', 'value': no_files},
        {'name': 'draft_to', 'value': to}],
        function(res) {
            $('.smtp_send').prop('disabled', false);
            $('.smtp_send').removeClass('disabled_input');
            if (res.draft_subject) {
                $('.draft_list .draft_'+draft_id+' a').text(res.draft_subject);
            }
        },
        [],
        no_icon
    );
};

var toggle_recip_flds = function() {
    var symbol = '+';
    if ($('.toggle_recipients').text() == '+') {
        symbol = '-';
    }
    $('.toggle_recipients').text(symbol);
    $('.recipient_fields').toggle();
    return false;
}

if (hm_page_name() === 'servers') {
    $('.test_smtp_connect').on('click', smtp_test_action);
    $('.save_smtp_connection').on('click', smtp_save_action);
    $('.forget_smtp_connection').on('click', smtp_forget_action);
    $('.delete_smtp_connection').on('click', smtp_delete_action);
    var dsp = Hm_Utils.get_from_local_storage('.smtp_section');
    if (dsp === 'block' || dsp === 'none') {
        $('.smtp_section').css('display', dsp);
    }
}

var reset_smtp_form = function() {
    $('.compose_body').val('');
    $('.compose_subject').val('');
    $('.compose_to').val('');
    $('.compose_cc').val('');
    $('.compose_bcc').val('');
    $('.ke-content', $('iframe').contents()).html('');
    $('.uploaded_files').html('');
    save_compose_state(true);
};

var upload_file = function(file) {
    var res = '';
    var form = new FormData();
    var xhr = new XMLHttpRequest;
    Hm_Ajax.show_loading_icon();
    form.append('upload_file', file);
    form.append('hm_ajax_hook', 'ajax_smtp_attach_file');
    form.append('hm_page_key', $('#hm_page_key').val());
    form.append('draft_id', $('.compose_draft_id').val());
    xhr.open('POST', '', true);
    xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4){
            if (hm_encrypt_ajax_requests()) {
                res = Hm_Utils.json_decode(xhr.responseText);
                res = Hm_Utils.json_decode(Hm_Crypt.decrypt(res.payload));
            }
            else {
                res = Hm_Utils.json_decode(xhr.responseText);
            }
            if (res.file_details) {
                $('.uploaded_files').append(res.file_details);
                $('.delete_attachment').on("click", function() { return delete_attachment($(this).data('id'), this); });
            }
            Hm_Ajax.stop_loading_icon();
            if (res.router_user_msgs && !$.isEmptyObject(res.router_user_msgs)) {
                Hm_Notices.show(res.router_user_msgs);
            }
        }
    }
    xhr.send(form);
};

var delete_attachment = function(file, link) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_delete_attachment'},
        {'name': 'attachment_id', 'value': file}],
        function(res) { $(link).parent().parent().remove(); }
    );
    return false;
};

$(function() {
    if (hm_page_name() === 'compose') {
        var interval = Hm_Utils.get_from_global('compose_save_interval', 30);
        Hm_Timer.add_job(function() { save_compose_state(); }, interval, true);
        $('.draft_title').on("click", function() { $('.draft_list').toggle(); });
        $('.toggle_recipients').on("click", function() { return toggle_recip_flds(); });
        $('.smtp_reset').on("click", reset_smtp_form);
        $('.delete_draft').on("click", function() { smtp_delete_draft($(this).data('id')); });
        $('.smtp_save').on("click", function() { save_compose_state(false, true); });
        $('.compose_attach_button').on("click", function() { $('.compose_attach_file').trigger('click'); });
        $('.compose_attach_file').on("change", function() { upload_file(this.files[0]); $('.compose_attach_file').val(''); });
        $('.compose_form').on('submit', function() { Hm_Ajax.show_loading_icon(); $('.smtp_send').addClass('disabled_input'); $('.smtp_send').on("click", function() { return false; }); });
        if ($('.compose_cc').val() || $('.compose_bcc').val()) {
            toggle_recip_flds();
        }
        $('.delete_attachment').on("click", function() { return delete_attachment($(this).data('id'), this); });
    }
});
<commit_msg>[FIX] allow cursor to be placed according to action<commit_after>'use strict';

var smtp_test_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
        },
        {'smtp_connect': 1}
    );
};

var smtp_save_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.just_saved_credentials) {
                form.find('.credentials').attr('disabled', true);
                form.find('.save_smtp_connection').hide();
                form.find('.smtp_password').val('');
                form.find('.smtp_password').attr('placeholder', '[saved]');
                form.append('<input type="submit" value="Forget" class="forget_smtp_connection" />');
                $('.forget_smtp_connection').on('click', smtp_forget_action);
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_save': 1}
    );
};

var smtp_forget_action = function(event) {
    event.preventDefault();
    var form = $(this).parent();
    Hm_Notices.hide(true);
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.just_forgot_credentials) {
                form.find('.credentials').prop('disabled', false);
                form.find('.credentials').val('');
                form.append('<input type="submit" value="Save" class="save_smtp_connection" />');
                $('.save_smtp_connection').on('click', smtp_save_action);
                $('.forget_smtp_connection', form).remove();
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_forget': 1}
    );
};

var smtp_delete_action = function(event) {
    if (!hm_delete_prompt()) {
        return false;
    }
    event.preventDefault();
    Hm_Notices.hide(true);
    var form = $(this).parent();
    Hm_Ajax.request(
        form.serializeArray(),
        function(res) {
            Hm_Notices.show(res.router_user_msgs);
            if (res.deleted_server_id > -1 ) {
                form.parent().remove();
                Hm_Utils.set_unsaved_changes(1);
                Hm_Folders.reload_folders(true);
            }
        },
        {'smtp_delete': 1}
    );
};

var smtp_delete_draft = function(id) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_delete_draft'},
        {'name': 'draft_id', 'value': id}],
        function(res) {
            if (res.draft_id != -1) {
                $('.draft_'+id).remove();
                $('.draft_list').toggle();
            }
        }
    );
};

var save_compose_state = function(no_files, notice) {
    var no_icon = true;
    if (notice) {
        no_icon = false;
    }
    var body = $('.compose_body').val();
    var subject = $('.compose_subject').val();
    var to = $('.compose_to').val();
    var smtp = $('.compose_server').val();
    var cc = $('.compose_cc').val();
    var bcc = $('.compose_bcc').val();
    var inreplyto = $('.compose_in_reply_to').val();
    var draft_id = $('.compose_draft_id').val();
    if (globals.draft_state == body+subject+to+smtp+cc+bcc) {
        return;
    }
    globals.draft_state = body+subject+to+smtp+cc+bcc;

    $('.smtp_send').prop('disabled', true);
    $('.smtp_send').addClass('disabled_input');
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_save_draft'},
        {'name': 'draft_body', 'value': body},
        {'name': 'draft_id', 'value': draft_id},
        {'name': 'draft_smtp', 'value': smtp},
        {'name': 'draft_subject', 'value': subject},
        {'name': 'draft_cc', 'value': cc},
        {'name': 'draft_bcc', 'value': bcc},
        {'name': 'draft_notice', 'value': notice},
        {'name': 'draft_in_reply_to', 'value': inreplyto},
        {'name': 'delete_uploaded_files', 'value': no_files},
        {'name': 'draft_to', 'value': to}],
        function(res) {
            $('.smtp_send').prop('disabled', false);
            $('.smtp_send').removeClass('disabled_input');
            if (res.draft_subject) {
                $('.draft_list .draft_'+draft_id+' a').text(res.draft_subject);
            }
        },
        [],
        no_icon
    );
};

var toggle_recip_flds = function() {
    var symbol = '+';
    if ($('.toggle_recipients').text() == '+') {
        symbol = '-';
    }
    $('.toggle_recipients').text(symbol);
    $('.recipient_fields').toggle();
    return false;
}

if (hm_page_name() === 'servers') {
    $('.test_smtp_connect').on('click', smtp_test_action);
    $('.save_smtp_connection').on('click', smtp_save_action);
    $('.forget_smtp_connection').on('click', smtp_forget_action);
    $('.delete_smtp_connection').on('click', smtp_delete_action);
    var dsp = Hm_Utils.get_from_local_storage('.smtp_section');
    if (dsp === 'block' || dsp === 'none') {
        $('.smtp_section').css('display', dsp);
    }
}

var reset_smtp_form = function() {
    $('.compose_body').val('');
    $('.compose_subject').val('');
    $('.compose_to').val('');
    $('.compose_cc').val('');
    $('.compose_bcc').val('');
    $('.ke-content', $('iframe').contents()).html('');
    $('.uploaded_files').html('');
    save_compose_state(true);
};

var upload_file = function(file) {
    var res = '';
    var form = new FormData();
    var xhr = new XMLHttpRequest;
    Hm_Ajax.show_loading_icon();
    form.append('upload_file', file);
    form.append('hm_ajax_hook', 'ajax_smtp_attach_file');
    form.append('hm_page_key', $('#hm_page_key').val());
    form.append('draft_id', $('.compose_draft_id').val());
    xhr.open('POST', '', true);
    xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4){
            if (hm_encrypt_ajax_requests()) {
                res = Hm_Utils.json_decode(xhr.responseText);
                res = Hm_Utils.json_decode(Hm_Crypt.decrypt(res.payload));
            }
            else {
                res = Hm_Utils.json_decode(xhr.responseText);
            }
            if (res.file_details) {
                $('.uploaded_files').append(res.file_details);
                $('.delete_attachment').on("click", function() { return delete_attachment($(this).data('id'), this); });
            }
            Hm_Ajax.stop_loading_icon();
            if (res.router_user_msgs && !$.isEmptyObject(res.router_user_msgs)) {
                Hm_Notices.show(res.router_user_msgs);
            }
        }
    }
    xhr.send(form);
};

var delete_attachment = function(file, link) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_smtp_delete_attachment'},
        {'name': 'attachment_id', 'value': file}],
        function(res) { $(link).parent().parent().remove(); }
    );
    return false;
};

var get_url_parameter = function (sParam){
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++){
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}

var replace_cursor_positon = function (txtElement) {
    txtElement.val('\r\n\r\n\r\n'+txtElement.val());
    txtElement.prop('selectionEnd',0);
    txtElement.focus();
}

$(function() {
    if (hm_page_name() === 'compose') {
        var interval = Hm_Utils.get_from_global('compose_save_interval', 30);
        Hm_Timer.add_job(function() { save_compose_state(); }, interval, true);
        $('.draft_title').on("click", function() { $('.draft_list').toggle(); });
        $('.toggle_recipients').on("click", function() { return toggle_recip_flds(); });
        $('.smtp_reset').on("click", reset_smtp_form);
        $('.delete_draft').on("click", function() { smtp_delete_draft($(this).data('id')); });
        $('.smtp_save').on("click", function() { save_compose_state(false, true); });
        $('.compose_attach_button').on("click", function() { $('.compose_attach_file').trigger('click'); });
        $('.compose_attach_file').on("change", function() { upload_file(this.files[0]); $('.compose_attach_file').val(''); });
        $('.compose_form').on('submit', function() { Hm_Ajax.show_loading_icon(); $('.smtp_send').addClass('disabled_input'); $('.smtp_send').on("click", function() { return false; }); });
        if ($('.compose_cc').val() || $('.compose_bcc').val()) {
            toggle_recip_flds();
        }
        $('.delete_attachment').on("click", function() { return delete_attachment($(this).data('id'), this); });
        if (get_url_parameter('reply') === '1'){
            replace_cursor_positon ($('textarea[name="compose_body"]'));
        }

    }
});
<|endoftext|>


<commit_before>/* =================================================================================== */
/* JQUERY CONTEXT */
/* =================================================================================== */
(function($)
{
    var _doc = $(document);

    $.initExploitation = function()
    {
        $('#btn_exploitation_modifier').click(function(e) {
            $('#btn_exploitation_modifier').addClass("hidden")
            $('#btn_exploitation_annuler').removeClass("hidden")
            $('#row_form_exploitation').removeClass("hidden");
            $('#row_info_exploitation').addClass("hidden");
        });
    }

    $.initPrelevement = function()
    {
        $('.form-chai button').click(function() {
            $('.form-chai button, .form-chai .form-group, .form-chai p').toggleClass('hidden');
        });
    }

    $.initControleExterne = function()
    {
        $('#checkbox_non_conditionneur').on('change', function() {
            if($(this).is(':checked')) {
                $('#bloc-form-control-externe').addClass('opacity-lg');
                $('#bloc-lieu-prelevement').addClass('opacity-lg');
                $('#bloc-form-control-externe input, #bloc-form-control-externe select, #bloc-lieu-prelevement button, #bloc-lieu-prelevement a, #bloc-form-control-externe button, #bloc-form-control-externe a').attr('disabled', 'disabled');
            } else {
                $('#bloc-form-control-externe').removeClass('opacity-lg');
                $('#bloc-lieu-prelevement').removeClass('opacity-lg');
                $('#bloc-form-control-externe input, #bloc-form-control-externe select, #bloc-lieu-prelevement button, #bloc-lieu-prelevement a, #bloc-form-control-externe button, #bloc-form-control-externe a').removeAttr('disabled');
            }
        });
        if($('#checkbox_non_conditionneur').is(':checked')) {
            $('#checkbox_non_conditionneur').change();
        }
    }

    $.initBtnValidation = function()
    {
        $('#btn-validation').click(function() {
            $(this).parents('form').attr('action', $(this).parents('form').attr('action') + '?redirect=validation');
            $(this).parents('form').submit();
            return false;
        });
    }

    $.initFocusAndErrorToRevendicationField = function()
    {
        var field = $('.error_field_to_focused');
        field.focus();
    }

    $.initRevendicationFadeRow = function()
    {

        $('tr.with_superficie').each(function() {
            var children = $(this).find(" td input");
            if (children.length == 2) {
                var fade = true;
                children.each(function() {
                    if ($(this).val() != "") {
                        fade = false;
                    }
                });
                if (fade) {
                    $(this).addClass('with_superficie_fade');
                }
            }

        });
    }

    $.initRevendicationEventsFadeInOut = function() {
        $('tr.with_superficie_fade').each(function() {
            var tr = $(this);
            var children = $(this).find(" td input");
            children.each(function() {
                $(this).focus(function() {
                    tr.removeClass('with_superficie_fade');
                });
                $(this).blur(function() {
                    $.initRevendicationFadeRow();
                });
            });
        });
    }

    $.initEventErrorRevendicationField = function() {
        var field = $('.error_field_to_focused');
        var divError = field.parent().parent();
        field.each(function() {
            $(this).blur(function() {
                if ($(this).val() != "") {
                    divError.removeClass('has-error');
                } else {
                    divError.addClass('has-error');
                }
            });
        });
    }

    $.initRecapEventsAccordion = function() {
        $('#revendication_accordion tr.trAccordion').click(function() {
            var eventId = $(this).attr('data-target');
            var span = $(this).find('small span');

            var ouverts = $('tr td.hiddenRow div.in');
            if (ouverts.length && (eventId == '#' + ouverts.attr('id'))) {
                span.removeClass('glyphicon-chevron-right');
                span.addClass('glyphicon-chevron-down');
                $(eventId).collapse('hide');
            } else {
                $('tr td.hiddenRow div').each(function() {
                    $('#revendication_accordion tr.trAccordion').each(function() {
                        var span_all = $(this).find('small span');
                        span_all.removeClass('glyphicon-chevron-right');
                        span_all.addClass('glyphicon-chevron-down');
                    });
                    $(this).removeClass('in');
                });
                span.removeClass('glyphicon-chevron-down');
                span.addClass('glyphicon-chevron-right');
                $(eventId).collapse('show');

            }
        });
    }

    $.initCalculAuto = function(){

      $(".edit_vci tr.produits").each(function(){
        var produits = $(this);
        produits.find("input.sum_stock_final").change(function(){
          var sum = 0.0;

          produits.find('input.sum_stock_final').each(function(){
            local = $(this).val();
            if(!local){ local=0.0;}else{ local=parseFloat(local); }
            sum=sum+local;
          });
          produits.find("input.stock_final").val(sum.toFixed(2));
        });

      });

        var sommeRevendication = function() {
            $('#table-revendication tbody tr').each(function() {
                var somme = 0;
                $(this).find('.input_sum_value').each(function() {
                    if($(this).val()) {
                        somme += parseFloat($(this).val());
                    } else {
                    	if ($(this).text()) {
                            somme += parseFloat($(this).text());
                    	}
                    }
                })
                if (!isNaN(somme)) {
	                if ($(this).find('.input_sum_total').is( "input" )) {
	                	$(this).find('.input_sum_total').val(somme.toFixed(2));
	                } else {
	                    $(this).find('.input_sum_total').text(somme.toFixed(2));
	                }
                }
            });

        }

        $('#table-revendication .input_sum_value').on('change', function() {
            sommeRevendication();
        });

    }

    /* =================================================================================== */
    /* FUNCTIONS CALL */
    /* =================================================================================== */
    _doc.ready(function()
    {
        $.initExploitation();
        $.initPrelevement();
        $.initBtnValidation();
        $.initFocusAndErrorToRevendicationField();
        $.initEventErrorRevendicationField();
        $.initCalculAuto();
        $.initRevendicationFadeRow();
        $.initRevendicationEventsFadeInOut();
        $.initControleExterne();

        $.initRecapEventsAccordion();
        $.initValidationDeclaration();

    });

})(jQuery);
<commit_msg>Correction du pb de mise à jour de la somme si pas de vci<commit_after>/* =================================================================================== */
/* JQUERY CONTEXT */
/* =================================================================================== */
(function($)
{
    var _doc = $(document);

    $.initExploitation = function()
    {
        $('#btn_exploitation_modifier').click(function(e) {
            $('#btn_exploitation_modifier').addClass("hidden")
            $('#btn_exploitation_annuler').removeClass("hidden")
            $('#row_form_exploitation').removeClass("hidden");
            $('#row_info_exploitation').addClass("hidden");
        });
    }

    $.initPrelevement = function()
    {
        $('.form-chai button').click(function() {
            $('.form-chai button, .form-chai .form-group, .form-chai p').toggleClass('hidden');
        });
    }

    $.initControleExterne = function()
    {
        $('#checkbox_non_conditionneur').on('change', function() {
            if($(this).is(':checked')) {
                $('#bloc-form-control-externe').addClass('opacity-lg');
                $('#bloc-lieu-prelevement').addClass('opacity-lg');
                $('#bloc-form-control-externe input, #bloc-form-control-externe select, #bloc-lieu-prelevement button, #bloc-lieu-prelevement a, #bloc-form-control-externe button, #bloc-form-control-externe a').attr('disabled', 'disabled');
            } else {
                $('#bloc-form-control-externe').removeClass('opacity-lg');
                $('#bloc-lieu-prelevement').removeClass('opacity-lg');
                $('#bloc-form-control-externe input, #bloc-form-control-externe select, #bloc-lieu-prelevement button, #bloc-lieu-prelevement a, #bloc-form-control-externe button, #bloc-form-control-externe a').removeAttr('disabled');
            }
        });
        if($('#checkbox_non_conditionneur').is(':checked')) {
            $('#checkbox_non_conditionneur').change();
        }
    }

    $.initBtnValidation = function()
    {
        $('#btn-validation').click(function() {
            $(this).parents('form').attr('action', $(this).parents('form').attr('action') + '?redirect=validation');
            $(this).parents('form').submit();
            return false;
        });
    }

    $.initFocusAndErrorToRevendicationField = function()
    {
        var field = $('.error_field_to_focused');
        field.focus();
    }

    $.initRevendicationFadeRow = function()
    {

        $('tr.with_superficie').each(function() {
            var children = $(this).find(" td input");
            if (children.length == 2) {
                var fade = true;
                children.each(function() {
                    if ($(this).val() != "") {
                        fade = false;
                    }
                });
                if (fade) {
                    $(this).addClass('with_superficie_fade');
                }
            }

        });
    }

    $.initRevendicationEventsFadeInOut = function() {
        $('tr.with_superficie_fade').each(function() {
            var tr = $(this);
            var children = $(this).find(" td input");
            children.each(function() {
                $(this).focus(function() {
                    tr.removeClass('with_superficie_fade');
                });
                $(this).blur(function() {
                    $.initRevendicationFadeRow();
                });
            });
        });
    }

    $.initEventErrorRevendicationField = function() {
        var field = $('.error_field_to_focused');
        var divError = field.parent().parent();
        field.each(function() {
            $(this).blur(function() {
                if ($(this).val() != "") {
                    divError.removeClass('has-error');
                } else {
                    divError.addClass('has-error');
                }
            });
        });
    }

    $.initRecapEventsAccordion = function() {
        $('#revendication_accordion tr.trAccordion').click(function() {
            var eventId = $(this).attr('data-target');
            var span = $(this).find('small span');

            var ouverts = $('tr td.hiddenRow div.in');
            if (ouverts.length && (eventId == '#' + ouverts.attr('id'))) {
                span.removeClass('glyphicon-chevron-right');
                span.addClass('glyphicon-chevron-down');
                $(eventId).collapse('hide');
            } else {
                $('tr td.hiddenRow div').each(function() {
                    $('#revendication_accordion tr.trAccordion').each(function() {
                        var span_all = $(this).find('small span');
                        span_all.removeClass('glyphicon-chevron-right');
                        span_all.addClass('glyphicon-chevron-down');
                    });
                    $(this).removeClass('in');
                });
                span.removeClass('glyphicon-chevron-down');
                span.addClass('glyphicon-chevron-right');
                $(eventId).collapse('show');

            }
        });
    }

    $.initCalculAuto = function(){

      $(".edit_vci tr.produits").each(function(){
        var produits = $(this);
        produits.find("input.sum_stock_final").change(function(){
          var sum = 0.0;

          produits.find('input.sum_stock_final').each(function(){
            local = $(this).val();
            if(!local){ local=0.0;}else{ local=parseFloat(local); }
            sum=sum+local;
          });
          produits.find("input.stock_final").val(sum.toFixed(2));
        });

      });

        var sommeRevendication = function() {
            $('#table-revendication tbody tr').each(function() {
                var somme = 0;
                $(this).find('.input_sum_value').each(function() {
                    if($(this).val()) {
                        somme += parseFloat($(this).val());
                    } else {
                    	if (parseFloat($(this).text())) {
                        somme += parseFloat($(this).text());
                    	}
                    }
                })
                if (!isNaN(somme)) {
	                if ($(this).find('.input_sum_total').is( "input" )) {
	                	$(this).find('.input_sum_total').val(somme.toFixed(2));
	                } else {
	                    $(this).find('.input_sum_total').text(somme.toFixed(2));
	                }
                }
            });

        }

        $('#table-revendication .input_sum_value').on('change', function() {
            sommeRevendication();
        });

    }

    /* =================================================================================== */
    /* FUNCTIONS CALL */
    /* =================================================================================== */
    _doc.ready(function()
    {
        $.initExploitation();
        $.initPrelevement();
        $.initBtnValidation();
        $.initFocusAndErrorToRevendicationField();
        $.initEventErrorRevendicationField();
        $.initCalculAuto();
        $.initRevendicationFadeRow();
        $.initRevendicationEventsFadeInOut();
        $.initControleExterne();

        $.initRecapEventsAccordion();
        $.initValidationDeclaration();

    });

})(jQuery);
<|endoftext|>


<commit_before>var _ = require('underscore')._;

var api = function(dbot) {
    var escapeRegexen = function(str) {
        return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    };

    var api = {
        'resolveUser': function(server, nick, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = nick;

            if(!useLowerCase) {
                if(!_.include(knownUsers.users, nick) && _.has(knownUsers.aliases, nick)) {
                    user = knownUsers.aliases[nick];
                }
            } else {
                // this is retarded
                user = user.toLowerCase();
                var toMatch = new RegExp("^" + escapeRegexen(user) + "$", "i");

                var resolvedUser = _.find(knownUsers.users, function(nick) {
                    return nick.match(toMatch) !== null;
                }, this);

                if(!resolvedUser) {
                    resolvedUser = _.find(knownUsers.aliases, function(nick, alias) {
                        if(alias.match(toMatch) !== null) return nick;
                    }, this);
                    if(!_.isUndefined(resolvedUser)) user = resolvedUser;
                }
                else{
                    user = resolvedUser;
                }
            }
            return user;
        },

        'getServerUsers': function(server) {
            return dbot.db.knownUsers[server].users;
        },

        'getAllUsers': function() {
            return _.reduce(dbot.db.knownUsers, function(memo, function(server, name) {
                memo[name] = server.users;
            }, {}, this));
        },

        'isKnownUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return (_.include(knownUsers.users, nick) || _.has(knownUsers.aliases, nick));
        },

        'isPrimaryUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.include(knownUsers.users, nick);
        },

        'getAliases': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.chain(knownUsers.aliases)
                .keys()
                .filter(function(user) {
                    return knownUsers.aliases[user] == nick;
                }, this)
                .value();
        },

        'isOnline': function(server, user, channel, useLowerCase) {
            var user = this.api.resolveUser(server, user, useLowerCase);
            var possiNicks = [user].concat(this.api.getAliases(server, user));
            var onlineNicks = dbot.instance.connections[server].channels[channel].nicks;

            return _.any(onlineNicks, function(nick) {
                nick = nick.name;
                return _.include(possiNicks, nick);
            }, this);
        },

        'isChannelUser': function(server, user, channel, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = this.api.resolveUser(server, user, useLowerCase);

            if(!_.has(knownUsers.channelUsers, channel)) {
                return false;
            }
            return _.include(knownUsers.channelUsers[channel], user);
        }
    };

    return api;
};

exports.fetch = function(dbot) {
    return api(dbot);
};
<commit_msg>another whoops<commit_after>var _ = require('underscore')._;

var api = function(dbot) {
    var escapeRegexen = function(str) {
        return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    };

    var api = {
        'resolveUser': function(server, nick, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = nick;

            if(!useLowerCase) {
                if(!_.include(knownUsers.users, nick) && _.has(knownUsers.aliases, nick)) {
                    user = knownUsers.aliases[nick];
                }
            } else {
                // this is retarded
                user = user.toLowerCase();
                var toMatch = new RegExp("^" + escapeRegexen(user) + "$", "i");

                var resolvedUser = _.find(knownUsers.users, function(nick) {
                    return nick.match(toMatch) !== null;
                }, this);

                if(!resolvedUser) {
                    resolvedUser = _.find(knownUsers.aliases, function(nick, alias) {
                        if(alias.match(toMatch) !== null) return nick;
                    }, this);
                    if(!_.isUndefined(resolvedUser)) user = resolvedUser;
                }
                else{
                    user = resolvedUser;
                }
            }
            return user;
        },

        'getServerUsers': function(server) {
            return dbot.db.knownUsers[server].users;
        },

        'getAllUsers': function() {
            return _.reduce(dbot.db.knownUsers, function(memo, server, name) {
                memo[name] = server.users;
            }, {}, this));
        },

        'isKnownUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return (_.include(knownUsers.users, nick) || _.has(knownUsers.aliases, nick));
        },

        'isPrimaryUser': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.include(knownUsers.users, nick);
        },

        'getAliases': function(server, nick) {
            var knownUsers = this.getServerUsers(server);
            return _.chain(knownUsers.aliases)
                .keys()
                .filter(function(user) {
                    return knownUsers.aliases[user] == nick;
                }, this)
                .value();
        },

        'isOnline': function(server, user, channel, useLowerCase) {
            var user = this.api.resolveUser(server, user, useLowerCase);
            var possiNicks = [user].concat(this.api.getAliases(server, user));
            var onlineNicks = dbot.instance.connections[server].channels[channel].nicks;

            return _.any(onlineNicks, function(nick) {
                nick = nick.name;
                return _.include(possiNicks, nick);
            }, this);
        },

        'isChannelUser': function(server, user, channel, useLowerCase) {
            var knownUsers = this.getServerUsers(server);
            var user = this.api.resolveUser(server, user, useLowerCase);

            if(!_.has(knownUsers.channelUsers, channel)) {
                return false;
            }
            return _.include(knownUsers.channelUsers[channel], user);
        }
    };

    return api;
};

exports.fetch = function(dbot) {
    return api(dbot);
};
<|endoftext|>


<commit_before>'use strict';
var name = '小明1234';
var age = 20;
var s = 'Hello';

s=name.substring(0,1);

//Array
var arr1 = [1,2,3,4,94,32,324,24,12];
var arr = [[1, 2, 3], [400, 500, 600], '-'];
// alert(arr[1].length);

//Object
var xiaoming = {
    name: '小明',
    birth: 1990,
    'school-name': 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};
delete xiaoming.name;
// alert('names' in xiaoming);

// var height = parseFloat(prompt('请输入身高(m):'));
// var weight = parseFloat(prompt('请输入体重(kg):'));
// alert(height);

//loop for-in
var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var keys in o) {
    // alert(keys); // 'name', 'age', 'city'
}

var arr2 = ['Bart', 'Lisa', 'Adam'];
for(var key in arr2){
  // alert(key);             //the key
  // alert("Hello "+ arr2[key]);   the value
}

//Map and Set were add in ES6
//Map  key-value
var m = new Map([[95, "test"], ['Bob', 75], ['Tracy', 85]]);
// alert(m.get(95));

//Set
var s = new Set([1, 2, 3, 3]);
// alert(s); // Set {1, 2, 3, "3"}

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x of a) {
    // alert(x); // '0', '1', '2', 'name'
}

//Function
//匿名函数
// function abs(x) {
//     if (x >= 0) {
//         return x;
//     } else {
//         return -x;
//     }
// }
//将函数定义为对象
var abs1 = function (x) {
  if (typeof x !== 'number') {
        throw 'Not a number！！';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
};
// alert(abs1(1)); //多余参数没有关系

//arguments
function abs2() {
    return arguments.length;
}
// alert(abs2(1,2,3));

//rest ES6
function sum(...rest) {
  if (typeof rest[0] !== 'number') {
        throw 'Not a number！！';
    }
    var sum = 0;
    for (var i = 0; i<rest.length; i++) {
              sum += rest[i];
            }
    console.log(sum);
}
sum(1, 2, 3, 4, 5 ,123);
sum(1);

//圆的面积
function area_of_circle(r, pi) {
  if(r !== undefined && pi !== undefined){
  return r*r*pi;
  }
  else if (r !== undefined){
  return r*r*3.14;
  }
  return 0;
}
// 测试:
if (area_of_circle(2) === 12.56 && area_of_circle(2, 3.1416) === 12.5664) {
    // alert('测试通过');
} else {
    // alert('测试失败');
}

//Nested 从自身函数定义开始，从“内”向“外”查找
function foo1() {
    var x = 1;
    function bar() {
        var x = 'A';
        alert('x in bar() = ' + x); // 'A'
    }
    alert('x in foo() = ' + x); // 1
    bar();
}
// foo1();

//在函数内部首先申明所有变量
function foo2() {
    var y; // 提升变量y的申明
    var x = 'Hello, ' + y;
    alert(x);
    y = 'Bob';
}
// foo2();

// var course = 'Learn JavaScript';
// window.alert(course); // 'Learn JavaScript'
// alert(window.course); // 'Learn JavaScript'

function foo3() {
    var sum = 0;
    for (var i=0; i<100; i++) {
        sum += i;
    }
    i += 1; // SyntaxError
    console.log(i);
}
// foo3();

//method
var xiaoming2 = {
    name: '小明',
    birth: 1990,
    age: function () {
        var y = new Date().getFullYear();
        return y - this.birth;
    }
};

// alert(xiaoming2.age); // function xiaoming2.age()
// alert(xiaoming2.age());

//this
var xiaoming3 = {
    name: '小明',
    birth: 1990,
    age: function () {
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y - this.birth;
        }
        return getAgeFromBirth();
    }
};

// xiaoming3.age(); // Uncaught TypeError: Cannot read property 'birth' of undefined

var xiaoming4 = {
    name: '小明',
    birth: 1990,
    age: function () {
        var that = this; // 在方法内部一开始就捕获this
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y - that.birth; // 用that而不是this
        }
        return getAgeFromBirth();
    }
};

console.log(xiaoming4.age());

function getAge() {
    var y = new Date().getFullYear();
    return y - this.birth;
}

var xiaoming5 = {
    name: '小明',
    birth: 1990,
    age: getAge
};
console.log(xiaoming5.age());
console.log(getAge.apply(xiaoming, []));

//Higher-order function
var f = Math.abs;
function add(x, y, f) {
    return f(x) + f(y);
}
console.log(add(-5, 6, Math.abs));

//map && reduce
var arr3 = [1, 3, 5, 7, 9];
var k = arr3.reduce(function (x, y) {
    return x + y;
});
console.log(k);

function string2int(s) {
  var arr = s.split('');
  return arr;
var sum = arr.reduce(function (x, y) {
    return x * 10 + y;
});
return sum;
}
console.log(string2int('12345'));
<commit_msg>1.add some practice;<commit_after>'use strict';
var name = '小明1234';
var age = 20;
var s = 'Hello';

s=name.substring(0,1);

//Array
var arr1 = [1,2,3,4,94,32,324,24,12];
var arr = [[1, 2, 3], [400, 500, 600], '-'];
// alert(arr[1].length);

//Object
var xiaoming = {
    name: '小明',
    birth: 1990,
    'school-name': 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};
delete xiaoming.name;
// alert('names' in xiaoming);

// var height = parseFloat(prompt('请输入身高(m):'));
// var weight = parseFloat(prompt('请输入体重(kg):'));
// alert(height);

//loop for-in
var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var keys in o) {
    // alert(keys); // 'name', 'age', 'city'
}

var arr2 = ['Bart', 'Lisa', 'Adam'];
for(var key in arr2){
  // alert(key);             //the key
  // alert("Hello "+ arr2[key]);   the value
}

//Map and Set were add in ES6
//Map  key-value
var m = new Map([[95, "test"], ['Bob', 75], ['Tracy', 85]]);
// alert(m.get(95));

//Set
var s = new Set([1, 2, 3, 3]);
// alert(s); // Set {1, 2, 3, "3"}

var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x of a) {
    // alert(x); // '0', '1', '2', 'name'
}

//Function
//匿名函数
// function abs(x) {
//     if (x >= 0) {
//         return x;
//     } else {
//         return -x;
//     }
// }
//将函数定义为对象
var abs1 = function (x) {
  if (typeof x !== 'number') {
        throw 'Not a number！！';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
};
// alert(abs1(1)); //多余参数没有关系

//arguments
function abs2() {
    return arguments.length;
}
// alert(abs2(1,2,3));

//rest ES6
function sum(...rest) {
  if (typeof rest[0] !== 'number') {
        throw 'Not a number！！';
    }
    var sum = 0;
    for (var i = 0; i<rest.length; i++) {
              sum += rest[i];
            }
    console.log(sum);
}
sum(1, 2, 3, 4, 5 ,123);
sum(1);

//圆的面积
function area_of_circle(r, pi) {
  if(r !== undefined && pi !== undefined){
  return r*r*pi;
  }
  else if (r !== undefined){
  return r*r*3.14;
  }
  return 0;
}
// 测试:
if (area_of_circle(2) === 12.56 && area_of_circle(2, 3.1416) === 12.5664) {
    // alert('测试通过');
} else {
    // alert('测试失败');
}

//Nested 从自身函数定义开始，从“内”向“外”查找
function foo1() {
    var x = 1;
    function bar() {
        var x = 'A';
        alert('x in bar() = ' + x); // 'A'
    }
    alert('x in foo() = ' + x); // 1
    bar();
}
// foo1();

//在函数内部首先申明所有变量
function foo2() {
    var y; // 提升变量y的申明
    var x = 'Hello, ' + y;
    alert(x);
    y = 'Bob';
}
// foo2();

// var course = 'Learn JavaScript';
// window.alert(course); // 'Learn JavaScript'
// alert(window.course); // 'Learn JavaScript'

function foo3() {
    var sum = 0;
    for (var i=0; i<100; i++) {
        sum += i;
    }
    i += 1; // SyntaxError
    console.log(i);
}
// foo3();

//method
var xiaoming2 = {
    name: '小明',
    birth: 1990,
    age: function () {
        var y = new Date().getFullYear();
        return y - this.birth;
    }
};

// alert(xiaoming2.age); // function xiaoming2.age()
// alert(xiaoming2.age());

//this
var xiaoming3 = {
    name: '小明',
    birth: 1990,
    age: function () {
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y - this.birth;
        }
        return getAgeFromBirth();
    }
};

// xiaoming3.age(); // Uncaught TypeError: Cannot read property 'birth' of undefined

var xiaoming4 = {
    name: '小明',
    birth: 1990,
    age: function () {
        var that = this; // 在方法内部一开始就捕获this
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y - that.birth; // 用that而不是this
        }
        return getAgeFromBirth();
    }
};

console.log(xiaoming4.age());

function getAge() {
    var y = new Date().getFullYear();
    return y - this.birth;
}

var xiaoming5 = {
    name: '小明',
    birth: 1990,
    age: getAge
};
console.log(xiaoming5.age());
console.log(getAge.apply(xiaoming, []));

//Higher-order function
var f = Math.abs;
function add(x, y, f) {
    return f(x) + f(y);
}
console.log(add(-5, 6, Math.abs));

//map && reduce
function pow(x){
  return x*x;
}
var arr4 = [1,2,3,4,5,6,7,8,9];
console.log(arr4.map(pow));

var arr3 = [1, 3, 5, 7, 9];
var k = arr3.reduce(function (x, y) {
    return x + y;
});
console.log(k);

//filter
var arr5 = [1, 2, 4, 5, 6, 9, 10, 15];
var r = arr5.filter(function (x) {
    return x % 2 !== 0;
});
console.log(r);

var arr6 = ['A', '', 'B', null, undefined, 'C', ' s  sd '];
var r = arr6.filter(function (s) {
    return s; // 注意：IE9以下的版本没有trim()方法
});
console.log(r);

//去重
var
    r,
    arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];
    r = arr.filter(function (element, index, self) {
    return self.indexOf(element) === index;
});
console.log(r.toString());

//筛选素数
function get_primes(arr) {
  return arr.filter(function (element) {
if(element === 1){
    return false;
}
for(var i = 2; i<element; i++){
if(element%i === 0){
return false;
}
}
return true;
});
}
var
    x,
    r,
    arr = [];
for (x = 1; x < 100; x++) {
    arr.push(x);
}
r = get_primes(arr);
if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
    console.log(r.toString());
} else {
    alert('测试失败: ' + r.toString());
}

//sort
var arr6 = ['Google', 'apple', 'Microsoft'];
arr6.sort(function (s1, s2) {
    var x1 = s1.toUpperCase();
    var x2 = s2.toUpperCase();
    if (x1 < x2) {
        return -1;
    }
    if (x1 > x2) {
        return 1;
    }
    return 0;
}); // ['apple', 'Google', 'Microsoft']
console.log(arr6.sort());

//闭包 todo（不是很理解）
// var n=999;
// 　　function f1(){
// 　　　　alert(n);
// 　　}
// 　　f1(); // 999
//
// function f1(){
// 　　　　var n=999;
// 　　}
// 　　alert(n); // error

// function f1(){
// 　　　　var n=999;
// 　　　　var nAdd=function(){n+=1}
// 　　　　function f2(){
// 　　　　　　alert(n);
// 　　　　}
// 　　　　return f2;
// 　　}
// 　　var result=f1();
// 　　result(); // 999
// 　　result.nAdd();
// 　　result(); // 1000

//generator
function* fib(max) {
    var
        t,
        a = 0,
        b = 1,
        n = 1;
    while (n < max) {
        yield a;
        t = a + b;
        a = b;
        b = t;
        n ++;
    }
    return a;
}
fib(5);
<|endoftext|>


<commit_before>
/*
This file is an implementation of a two way linked list used to record game input.
*/

var inputHead;
var inputTail;
var inputCurrent;
var inputLength;
var lock;//prevents addition and removal of elements from linked list while true
/*
Initializes the stack
*/
function initInput()
{
    inputHead = null;
    inputTail = null;
    inputCurrent = null;
    inputLength = 0;
    lock = false;
}

function setLock(locked)
{
    lock = locked;
}

function Node(data)
{
    this.data = data;
    this.next = null;
    this.prev = null;
}

/*
Adds an input to the linked list
data: data being added
*/
function addInput(node)
{
    if(lock)
        return;
    node.next = null;
    if(inputHead == null)
    {
        inputHead = node;
        inputTail = node;
        inputLength = 1;
        return;
    }
    inputTail.next = node;
    node.prev = inputTail;
    inputTail = node;
    inputLength++;
}

function initIterator()
{
    inputCurrent = inputHead;
}

/*
Returns the next input in the linked list
*/
function nextInput()
{
    var res = inputCurrent;
    if(res == null)
        return null;
    inputCurrent = inputCurrent.next;
    return res;
}

/*
Removes the last input in the linked list
*/
function removeInput()
{
    if(inputLength == 0)
        return null;
    var res = inputTail;
    if(inputLength == 1)
    {
        inputHead = null;
        inputTail = null;
        return res;
    }
    else
        inputTail = inputTail.prev;
    inputTail.next = null;
    res.prev = null;
    inputLength--;
    return res;
}

/*
Returns the length of the linked list
*/
function lengthInput()
{
    return inputLength;
}

/*
Deconstructs the linked list and appends it to the starting data JSON.
*/
function gameString(startdata)
{
    initIterator();
    var content = startdata.slice(0, -1) + ', "input":[  ';
    var curElement = nextInput();
    while(curElement != null)
    {
        content += '"' + curElement.data + '", ';
        curElement = nextInput();
    }
    content = content.slice(0, -2) + ']}';
    return content;
}

/*
Appends a linked list of input from a string of game data.
*/
function loadGameData(gamedata)
{
    Android.test("loading data... " + gamedata);

    var splitdata = gamedata.toString().split(",");
    Android.test("split finished.");
    var len = splitdata.length;
    Android.test("length: " + len);
    for(i = 0; i < len; i++)
    {
        Android.test(i+" "+splitdata[i]);
        addInput(new Node(splitdata[i]));
    }
}

function getGameDataPackage()
{
    Android.test("creating package...");
    return gameString(startingJSON);
}

<commit_msg>Update InputList2.9.js<commit_after>
/*
This file is an implementation of a two way linked list used to record game input.
*/

var inputHead;
var inputTail;
var inputCurrent;
var inputLength;
var lock;//prevents addition and removal of elements from linked list while true
/*
Initializes the stack
*/
function initInput()
{
    inputHead = null;
    inputTail = null;
    inputCurrent = null;
    inputLength = 0;
    lock = false;
}

/*
Locks the list from data being input or removed.
*/
function setLock(locked)
{
    lock = locked;
}

function Node(data)
{
    this.data = data;
    this.next = null;
    this.prev = null;
}

/*
Adds an input to the linked list
data: data being added
*/
function addInput(node)
{
    if(lock)
        return;
    node.next = null;
    if(inputHead == null)
    {
        inputHead = node;
        inputTail = node;
        inputLength = 1;
        return;
    }
    inputTail.next = node;
    node.prev = inputTail;
    inputTail = node;
    inputLength++;
}

/*
Initializes the iterator
*/
function initIterator()
{
    inputCurrent = inputHead;
}

/*
Returns the next input in the linked list
*/
function nextInput()
{
    var res = inputCurrent;
    if(res == null)
        return null;
    inputCurrent = inputCurrent.next;
    return res;
}

/*
Removes the last input in the linked list
*/
function removeInput()
{
    if(inputLength == 0)
        return null;
    var res = inputTail;
    if(inputLength == 1)
    {
        inputHead = null;
        inputTail = null;
        return res;
    }
    else
        inputTail = inputTail.prev;
    inputTail.next = null;
    res.prev = null;
    inputLength--;
    return res;
}

/*
Returns the length of the linked list
*/
function lengthInput()
{
    return inputLength;
}

/*
Deconstructs the linked list and appends it to the starting data JSON.
*/
function gameString(startdata)
{
    initIterator();
    var content = startdata.slice(0, -1) + ', "input":[  ';
    var curElement = nextInput();
    while(curElement != null)
    {
        content += '"' + curElement.data + '", ';
        curElement = nextInput();
    }
    content = content.slice(0, -2) + ']}';
    return content;
}

/*
Appends a linked list of input from a string of game data.
*/
function loadGameData(gamedata)
{
    Android.test("loading data... " + gamedata);

    var splitdata = gamedata.toString().split(",");
    Android.test("split finished.");
    var len = splitdata.length;
    Android.test("length: " + len);
    for(i = 0; i < len; i++)
    {
        Android.test(i+" "+splitdata[i]);
        addInput(new Node(splitdata[i]));
    }
}

/*
Creates a package of game data.
*/
function getGameDataPackage()
{
    Android.test("creating package...");
    return gameString(startingJSON);
}

<|endoftext|>


<commit_before>//--------------------------------------------------------------------------//
//                                                                          //
//                         J S - B V - S A M P L I N G                      //
//                                                                          //
//                                                                          //
// 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.          //
// License information here                                                 //
//                                                                          //
// Author: Jon Anthony (2014)                                               //
//                                                                          //
//--------------------------------------------------------------------------//
//

// General JS sort predicate (this should really go in some general
// util pkg).
function _spred (l, r) {
    return ((l < r) ? -1 : ((l > r) ? 1 : 0));
}

// An estimator of coverage depth of corresponding data file (for the
// index reader - bam or vcf) which uses bytes in region segments as
// the indicator.  Returns the estimations as an object of 'segment
// information' maps, where each key is a reference id and each such
// map is:
//
// {relBinNum: (segment-bin-num - start16kbBinid)
//  pos:       (relBinNum * 16KB)
//  depth:     total-byte-count}
//
function estimateCoverageDepth (indexReader, cb) {
    var rdrThis = indexReader;

    if (rdrThis.estimates) {
        if (cb) {cb.call(rdrThis, rdrThis.estimates)};
        return rdrThis.estimates;
    } else {
        var indexWreads =
            rdrthis.idxContent.indexseq.reduce(
                function(V, x, i, _){
                    if (x.n_bin != 0 || x.n_intv != 0)
                        V.push([x, i]);
                    return V;
                }, []);

        rdrThis.estimates =
            indexWreads.reduce(
                function(RD, I) {
                    var ref = I[1];
                    var withLeafBins = I[0].binseq.filter(
                        function(o){
                            return (o.bin >= start16kbBinid &&
                                    o.bin <= end16kbBinid);});

                    refsegs =
                        withLeafBins.reduce(
                            function(segs, o){
                                var b = o.bin;
                                var relBinNum = (b - start16kbBinid);
                                var position =  (relBinNum * _16KB);
                                var readDepth =
                                    o.chunkseq.reduce(
                                        function(bc, chunk) {
                                            var b = chunk.cnk_beg.valueOf();
                                            var e = chunk.cnk_end.valueOf();
                                            return bc + (rshift16(e) -
                                                         rshift16(b));
                                        }, 0);
                                segs.push(
                                    {relBinNum: relBinNum,
                                     pos: position, depth: readDepth});
                                return segs;
                            }, []);
                    return RD[ref] = refsegs;
                }, {});
        return estimateCoverageDepth(indexReader, cb);
    };
}

// Mapping function over the estimate read coverage segments of
// reference REFID.  See estimateCoverageDepth for more on segments.
// Requires that estimateCoverageDepth has been run; if not will
// implicitly run it.  FN is a function of a segment information map.
// For the sq of segment information maps for REFID [segmap...],
// returns the sq [fn(seqmap)...].  If keepNils is true, returns fn
// results which are nil (undefined), otherwise, returns only non nil
// results.
function mapSegCoverage (indexReader, refid, fn, keepNils) {
    var info = function (i) {
        var e = indexReader.estimates[refid][i];
        return (e) ? e : {relBinNum: i, pos: i * 16384, depth: 0}
    };

    var res = [];
    for (var i = 0; i < (end16kbBinid - start16kbBinid); i++) {
        var user_res = fn.call(indexReader, info(i))
        if (keepNils) {
            res.push(user_res);
        } else if (user_res) {
            res.push(user_res);
        }
    };
    return res;
}

// For a sq of reference objects REFS (as obtained from file header
// information), and option set OPTIONS (a map of parameter options),
// obtains a set of region samples for each reference in refs.  The
// resulting set is intended to be a 'representative sample' of the
// base file.
//
// Tuning parameters in options are binSize, the max size covered by a
// bin; binNumber, the max number of bins to consider for a ref;
// start, the starting position of the sequence associated with a ref
// for a sampling.  Defaults are binSize = 40000 bases, binNumber =
// 20, start = 1.
//
// Returns a map {regions: [reginfo...], regstr: json-string-for-regions}
//
// where reginfo = {name: ref.name, start: int, end: int} and regions
// is sorted ascendingly by name by numerical start
//
//
function samplingRegions (refs, options) {
    var bsize = options.binSize || 40000;
    var bcnt  = options.binNumber || 20;
    var start = options.start || 1;
    var regions =
        refs.reduce(
            function(regs, ref) {
                var len = ref.l_ref - start;
                if (len > 0 && len < (bcnt * bsize)) {
                    regs.push({name: ref.name, start: start, end: ref.l_ref});
                } else if (len > 0) {
                    // There are cases where it is too painful to
                    // write functional code in js...
                    for (var i = 0; i < bcnt; i++) {
                        var nstart = start + Math.floor(Math.random() * len);
                        regs.push(
                            {name: ref.name,
                             start: nstart,
                             end: nstart + bsize});
                    };
                };
                return regs;
            }, []);

    regions = regions.sort(function(l,r){
        if (l.name ==  r.name) {
            return parseInt(l.start) - parseInt(r.start)
        } else {
            return _spred(l.name, r.name);
        }});

    return {regions: regions,
            regstr: JSON.stringify(regions.map(
                function(r){
                    // This is broken - SERVERs should change names if needed!
                    return {start: r.start, end: r.l_ref, chr: r.name}}))};
}

// Convert ref objects to old format.  Servers should be upgraded to
// use the actual bai index names, but this will provide interim
// support.  Takes a sq REFS of reference objs, each of format {name:
// string, l_ref: int, l_name: int} and converts to sq of objs of
// format {name: string, end: int}
function new2oldRefs (refs) {
    return refs.map(function(ref) {return {name: ref.name, end: ref.l_ref}});
}

// Obtain a bamstats-alive url encoding for a region sampling of REFS
// a sq of reference objects as obtained from file header information.
// Performs a samplingRegions operation to obtain the region
// information and then generates a corresponding url for the
// bamstats-alive server.  OPTIONS is as for samplingRegions.
// bsaliveURL is the base http address for a bamstats-alive server.
function bamStatsAliveSamplingURL (refs, options, bsaliveURL) {
    var regionInfo = samplingRegions(refs, options);
    var regions = regionInfo.regions;
    var regStr = regionInfo.regStr;
    return encodeURI(
        bsaliveURL +
            '?cmd=-u 3000 -r \'' + regStr + '\' ' +
            encodeURIComponent(getBamRegionsUrl(regions)));
}<commit_msg>fix bug in sampling<commit_after>//--------------------------------------------------------------------------//
//                                                                          //
//                         J S - B V - S A M P L I N G                      //
//                                                                          //
//                                                                          //
// 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.          //
// License information here                                                 //
//                                                                          //
// Author: Jon Anthony (2014)                                               //
//                                                                          //
//--------------------------------------------------------------------------//
//

// General JS sort predicate (this should really go in some general
// util pkg).
function _spred (l, r) {
    return ((l < r) ? -1 : ((l > r) ? 1 : 0));
}

// An estimator of coverage depth of corresponding data file (for the
// index reader - bam or vcf) which uses bytes in region segments as
// the indicator.  Returns the estimations as an object of 'segment
// information' maps, where each key is a reference id and each such
// map is:
//
// {relBinNum: (segment-bin-num - start16kbBinid)
//  pos:       (relBinNum * 16KB)
//  depth:     total-byte-count}
//
function estimateCoverageDepth (indexReader, cb) {
    var rdrThis = indexReader;

    if (rdrThis.estimates) {
        if (cb) {cb.call(rdrThis, rdrThis.estimates)};
        return rdrThis.estimates;
    } else {
        var indexWreads =
            rdrThis.idxContent.indexseq.reduce(
                function(V, x, i, _){
                    if (x.n_bin != 0 || x.n_intv != 0)
                        V.push([x, i]);
                    return V;
                }, []);

        rdrThis.estimates =
            indexWreads.reduce(
                function(RD, I) {
                    var ref = I[1];
                    var withLeafBins = I[0].binseq.filter(
                        function(o){
                            return (o.bin >= start16kbBinid &&
                                    o.bin <= end16kbBinid);});

                    refsegs =
                        withLeafBins.reduce(
                            function(segs, o){
                                var b = o.bin;
                                var relBinNum = (b - start16kbBinid);
                                var position =  (relBinNum * _16KB);
                                var readDepth =
                                    o.chunkseq.reduce(
                                        function(bc, chunk) {
                                            var b = chunk.cnk_beg.valueOf();
                                            var e = chunk.cnk_end.valueOf();
                                            return bc + (rshift16(e) -
                                                         rshift16(b));
                                        }, 0);
                                segs.push(
                                    {relBinNum: relBinNum,
                                     pos: position, depth: readDepth});
                                return segs;
                            }, []);
                    RD[ref] = refsegs;
                    return RD;
                }, {});
        return estimateCoverageDepth(indexReader, cb);
    };
}

// Mapping function over the estimate read coverage segments of
// reference REFID.  See estimateCoverageDepth for more on segments.
// Requires that estimateCoverageDepth has been run; if not will
// implicitly run it.  FN is a function of a segment information map.
// For the sq of segment information maps for REFID [segmap...],
// returns the sq [fn(seqmap)...].  If keepNils is true, returns fn
// results which are nil (undefined), otherwise, returns only non nil
// results.
function mapSegCoverage (indexReader, refid, fn, keepNils) {
    var info = function (i) {
        var e = indexReader.estimates[refid][i];
        return (e) ? e : {relBinNum: i, pos: i * 16384, depth: 0}
    };

    var res = [];
    for (var i = 0; i < (end16kbBinid - start16kbBinid); i++) {
        var user_res = fn.call(indexReader, info(i))
        if (keepNils) {
            res.push(user_res);
        } else if (user_res) {
            res.push(user_res);
        }
    };
    return res;
}

// For a sq of reference objects REFS (as obtained from file header
// information), and option set OPTIONS (a map of parameter options),
// obtains a set of region samples for each reference in refs.  The
// resulting set is intended to be a 'representative sample' of the
// base file.
//
// Tuning parameters in options are binSize, the max size covered by a
// bin; binNumber, the max number of bins to consider for a ref;
// start, the starting position of the sequence associated with a ref
// for a sampling.  Defaults are binSize = 40000 bases, binNumber =
// 20, start = 1.
//
// Returns a map {regions: [reginfo...], regstr: json-string-for-regions}
//
// where reginfo = {name: ref.name, start: int, end: int} and regions
// is sorted ascendingly by name by numerical start
//
//
function samplingRegions (refs, options) {
    var bsize = options.binSize || 40000;
    var bcnt  = options.binNumber || 20;
    var start = options.start || 1;
    var regions =
        refs.reduce(
            function(regs, ref) {
                var len = ref.l_ref - start;
                if (len > 0 && len < (bcnt * bsize)) {
                    regs.push({name: ref.name, start: start, end: ref.l_ref});
                } else if (len > 0) {
                    // There are cases where it is too painful to
                    // write functional code in js...
                    for (var i = 0; i < bcnt; i++) {
                        var nstart = start + Math.floor(Math.random() * len);
                        regs.push(
                            {name: ref.name,
                             start: nstart,
                             end: nstart + bsize});
                    };
                };
                return regs;
            }, []);

    regions = regions.sort(function(l,r){
        if (l.name ==  r.name) {
            return parseInt(l.start) - parseInt(r.start)
        } else {
            return _spred(l.name, r.name);
        }});

    return {regions: regions,
            regstr: JSON.stringify(regions.map(
                function(r){
                    // This is broken - SERVERs should change names if needed!
                    return {start: r.start, end: r.l_ref, chr: r.name}}))};
}

// Convert ref objects to old format.  Servers should be upgraded to
// use the actual bai index names, but this will provide interim
// support.  Takes a sq REFS of reference objs, each of format {name:
// string, l_ref: int, l_name: int} and converts to sq of objs of
// format {name: string, end: int}
function new2oldRefs (refs) {
    return refs.map(function(ref) {return {name: ref.name, end: ref.l_ref}});
}

// Obtain a bamstats-alive url encoding for a region sampling of REFS
// a sq of reference objects as obtained from file header information.
// Performs a samplingRegions operation to obtain the region
// information and then generates a corresponding url for the
// bamstats-alive server.  OPTIONS is as for samplingRegions.
// bsaliveURL is the base http address for a bamstats-alive server.
function bamStatsAliveSamplingURL (refs, options, bsaliveURL) {
    var regionInfo = samplingRegions(refs, options);
    var regions = regionInfo.regions;
    var regStr = regionInfo.regStr;
    return encodeURI(
        bsaliveURL +
            '?cmd=-u 3000 -r \'' + regStr + '\' ' +
            encodeURIComponent(getBamRegionsUrl(regions)));
}<|endoftext|>


<commit_before>module.exports = {
  name: 'Store YouTube Info',
  section: 'Audio Control',

  subtitle (data) {
    const info = ['Video ID', 'Video URL', 'Video Title', 'Video Description', 'Video Channel ID', 'Video Channel URL', 'Video Channel Name', 'Video Thumbnail URL', 'Video Duration', 'Video Publish Data', 'Video Views', 'Video is live?']
    return `YouTube ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    let dataType = 'Unknown Type'
    switch (parseInt(data.info)) {
      case 0: // Video ID
      case 2: // Video Title
      case 3: // Video Description
      case 5: // Video Channel ID
      case 4: // Video Channel Name
      case 12: // Video Duration
      case 21: // Video Publish Date
        dataType = 'Text'
        break
      case 1: // Video URL
      case 20: // Video Channel URL
        dataType = 'URL'
        break
      case 6: // Video Thumbnail URL
        dataType = 'Image URL'
        break
      case 19: // Video is live?
        dataType = 'Boolean'
        break
      case 13: // Video Views
        dataType = 'Number'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['video', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

    Video to Search:

    <textarea id="video" rows="2" placeholder="Video to search for goes here" style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

    Source Info:

    <select id="info" class="round">
      <option value="0">Video ID</option>
      <option value="1">Video URL</option>
      <option value="2">Video Title</option>
      <option value="3">Video Description</option>
      <option value="4">Video Channel Name</option>
      <option value="5">Video Channel ID</option>
      <option value="20">Video Channel URL</option>
      <option value="6">Video Thumbnail URL</option>
      <option value="12">Video Duration</option>
      <option value="21">Video Publish Date</option>
      <option value="13">Video Views</option>
      <option value="19">Video is Live?</option>
    </select>

      Store In:

      <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
        ${data.variables[0]}
      </select>

      Variable Name:

      <input id="varName" class="round" type="text">

`
  },

  init () {
    const { glob, document } = this

    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  async action (cache) {
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const _this = this
    const video = this.evalMessage(data.video, cache)
    const Mods = this.getMods()
    const TimeFormat = Mods.require('hh-mm-ss')
    const ytsr = Mods.require('ytsr')
    let result

    if (!video) return console.log('Please specify a video to get video informations.')

    ytsr(video, function (err, searchResults) {
      if (err) return console.error(err)
      const video = searchResults.item[0]

      switch (info) {
        case 0: // Video ID
          result = video.link.replace('https://www.youtube.com/watch?v=', '')
          break
        case 1: // Video URL
          result = video.link
          break
        case 2: // Video Title
          result = video.title.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 3: // Video Description
          result = video.description.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 4: // Video Channel Name
          result = video.author.name
          break
        case 5: // Video Channel ID
          result = video.author.ref.replace('https://www.youtube.com/channel/', '')
          break
        case 6: // Thumbnail URL (Default)
          result = video.thumbnail
          break
        case 12: // Video Duration
          result = TimeFormat.toS(video.duration)
          break
        case 13: // Video Views
          result = video.views
          break
        case 19: // is live?
          result = video.live
          break
        case 20: // Video Channel URL
          result = video.author.ref
          break
        case 21: // Video Publish Date
          result = video.uploaded_at
          break
        default:
          break
      }

      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<commit_msg>Fix error (#471)<commit_after>module.exports = {
  name: 'Store YouTube Info',
  section: 'Audio Control',

  subtitle (data) {
    const info = ['Video ID', 'Video URL', 'Video Title', 'Video Description', 'Video Channel ID', 'Video Channel URL', 'Video Channel Name', 'Video Thumbnail URL', 'Video Duration', 'Video Publish Data', 'Video Views', 'Video is live?']
    return `YouTube ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    let dataType = 'Unknown Type'
    switch (parseInt(data.info)) {
      case 0: // Video ID
      case 2: // Video Title
      case 3: // Video Description
      case 5: // Video Channel ID
      case 4: // Video Channel Name
      case 12: // Video Duration
      case 21: // Video Publish Date
        dataType = 'Text'
        break
      case 1: // Video URL
      case 20: // Video Channel URL
        dataType = 'URL'
        break
      case 6: // Video Thumbnail URL
        dataType = 'Image URL'
        break
      case 19: // Video is live?
        dataType = 'Boolean'
        break
      case 13: // Video Views
        dataType = 'Number'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['video', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

    Video to Search:

    <textarea id="video" rows="2" placeholder="Video to search for goes here" style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

    Source Info:

    <select id="info" class="round">
      <option value="0">Video ID</option>
      <option value="1">Video URL</option>
      <option value="2">Video Title</option>
      <option value="3">Video Description</option>
      <option value="4">Video Channel Name</option>
      <option value="5">Video Channel ID</option>
      <option value="20">Video Channel URL</option>
      <option value="6">Video Thumbnail URL</option>
      <option value="12">Video Duration</option>
      <option value="21">Video Publish Date</option>
      <option value="13">Video Views</option>
      <option value="19">Video is Live?</option>
    </select>

      Store In:

      <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
        ${data.variables[0]}
      </select>

      Variable Name:

      <input id="varName" class="round" type="text">

`
  },

  init () {
    const { glob, document } = this

    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  async action (cache) {
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const _this = this
    const video = this.evalMessage(data.video, cache)
    const Mods = this.getMods()
    const TimeFormat = Mods.require('hh-mm-ss')
    const ytsr = Mods.require('ytsr')
    let result

    if (!video) return console.log('Please specify a video to get video informations.')

    ytsr(video, function (err, searchResults) {
      if (err) return console.error(err)
      const video = searchResults.items[0]

      switch (info) {
        case 0: // Video ID
          result = video.link.replace('https://www.youtube.com/watch?v=', '')
          break
        case 1: // Video URL
          result = video.link
          break
        case 2: // Video Title
          result = video.title.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 3: // Video Description
          result = video.description.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 4: // Video Channel Name
          result = video.author.name
          break
        case 5: // Video Channel ID
          result = video.author.ref.replace('https://www.youtube.com/channel/', '')
          break
        case 6: // Thumbnail URL (Default)
          result = video.thumbnail
          break
        case 12: // Video Duration
          result = TimeFormat.toS(video.duration)
          break
        case 13: // Video Views
          result = video.views
          break
        case 19: // is live?
          result = video.live
          break
        case 20: // Video Channel URL
          result = video.author.ref
          break
        case 21: // Video Publish Date
          result = video.uploaded_at
          break
        default:
          break
      }

      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<|endoftext|>


<commit_before>'use strict';

import './build/styles/index.css';
<commit_msg>fix(web): use es5 import for idk styles<commit_after>'use strict';

require('./build/styles/index.css');
<|endoftext|>


<commit_before>
var Context = require('node_should/context').Context;
var assert = require('assert');
require('../common');

// Configuration

(function contextIsInstantiable() {
  var c = new Context();
})();

(function contextIsComposite() {
  var c = new Context();
  c.addChild(new Context());
  assert.equal(1, c.numChildren);
})();

(function contextAddSetupHandlerFailsWithNullHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addSetupHandler();
  }, /must not be null/);
})();

(function contextAcceptsSetupHandler() {
  var c = new Context();
  c.addSetupHandler(function() {});
})();

(function contextAddTeardownHandlerFailsWithNullHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addTeardownHandler();
  }, /must not be null/);
})();

(function contextAcceptsTeardownHandlers() {
  var c = new Context();
  c.addTeardownHandler(function() {});
})();

(function contextUsesEmptyStringAsDefaultLabel() {
  var c = new Context();
  assert.equal('', c.getLabel());
})();

(function contextFailsWithNullTestHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addTestHandler();
  }, /must not be null/);
})();

(function contextAcceptsTestHandler() {
  var c = new Context();
  c.addTestHandler(function() {});
})();

(function contextAcceptsLabel() {
  var c = new Context('root');
  assert.equal('root', c.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context('SomeClass');
  var child1 = new Context('with child');
  root.addChild(child1);

  assert.equal('SomeClass with child', child1.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context('SomeClass');
  var child1 = new Context();
  root.addChild(child1);

  assert.equal('SomeClass', child1.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context();
  var child1 = new Context('SomeClass');
  root.addChild(child1);

  assert.equal('SomeClass', child1.getLabel());
})();

// Execution

(function contextFailsToExecuteIfNoTests() {
  var c = new Context();
  assert.throws(function() {
    c.execute();
  }, /no tests/);

})();

(function contextRunsSetupsThenTestsThenTeardowns() {
  var executed = [];
  var c = new Context('SomeClass');
  c.addSetupHandler(function() {
    executed.push('setup');
  });
  c.addTestHandler(function() {
    executed.push('test');
  });
  c.addTeardownHandler(function() {
    executed.push('teardown');
  });
  c.execute();

  var expected = ['setup', 'test', 'teardown'];
  assert.equal(expected.length, executed.length);
  assert.equal(expected[0], executed[0]);
  assert.equal(expected[1], executed[1]);
  assert.equal(expected[2], executed[2]);
})();

(function contextRunsHandlersInSharedScope() {
  var c = new Context('SomeClass');
  c.addSetupHandler(function() {
    this.foo = 'bar';
  });
  c.addTestHandler(function() {
    assert.equal(this.foo, 'bar');
  });
  c.execute();
})();

(function setupsCalledForEachTestMethod() {
  var executed = [];
  var c = new Context('SomeClass');
  c.addSetupHandler(function() { executed.push('setup1'); });
  c.addSetupHandler(function() { executed.push('setup2'); });
  c.addTestHandler(function() { executed.push('test1') });
  c.addTestHandler(function() { executed.push('test2') });
  c.addTestHandler(function() { executed.push('test3') });
  c.addTestHandler(function() { executed.push('test4') });
  c.addTeardownHandler(function() { executed.push('teardown1'); });
  c.addTeardownHandler(function() { executed.push('teardown2'); });
  c.execute();

  assert.equal(20, executed.length);
})();

(function testMethodsCalledWithDifferentScope() {
  var firstScope = null;
  var secondScope = null;
  var c = new Context();
  c.addTestHandler(function() { firstScope = this });
  c.addTestHandler(function() { secondScope = this });
  c.execute();
  assert.notStrictEqual(firstScope, secondScope);
})();

(function contextRunsSetupAsynchronouslyIfRequested() {
  var executed = [];
  var c = new Context();
  c.addSetupHandler(function() {
    var asyncHandler = this.async(function() {
      executed.push('asyncsetup');
    });
    setTimeout(asyncHandler, 0);
  });
  c.addTestHandler(function() {
    executed.push('test');
  });
  c.execute(function() {
    assert.equal(2, executed.length);
    assert.equal('asyncsetup', executed[0]);
    assert.equal('test', executed[1]);
  });
})();

(function contextRunsTestAsynchronously() {
  var executed = [];
  var c = new Context();
  c.addSetupHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asyncsetup');
    }), 0);
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asynctest1');
    }), 0);
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asynctest2');
    }), 0);
  });
  c.addTeardownHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asyncteardown');
    }), 0);
  });

  c.execute(function() {
    assert.equal(6, executed.length);
  });
})();

(function contextCapturesAssertionExceptions() {
  var failure = null;
  var c = new Context();
  c.addListener('failure', function(f) {
    failure = f;
  });

  c.addTestHandler(function() {
    assert.ok(false, 'should be false');
  });

  c.execute();
  assert.ok(failure);
})();

(function contextCapturesAssertionErrors() {
  var failure = null;
  var c = new Context();
  c.addListener('failure', function(f) {
    failure = f;
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      assert.ok(false, 'should be false');
    }), 0);
  });
  c.execute(function() {
    assert.ok(failure);
  });
})();

(function contextHandlesMultipleAsyncsInSameCall() {
  var executed = [];
  var c = new Context();
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('one');
    }), 0);
    setTimeout(this.async(function() {
      executed.push('two');
    }), 0);
    setTimeout(this.async(function() {
      executed.push('three');
    }), 0);
  });

  c.execute(function() {
    assert.equal(3, executed.length);
    assert.equal(executed[0], 'one');
    assert.equal(executed[1], 'two');
    assert.equal(executed[2], 'three');
  });
})();

// Failure Messages

(function contextDisplaysHelpfulTestMessages() {
  var c = new Context('SomeClass');
  c.addTestHandler('accept argument', function() {
    assert.ok(false);
  });
  c.addListener('failure', function(e) {
    assert.match(/SomeClass should accept argument/, e.message);
  });
  c.execute();
})();

(function contextLabelShowsEvenIfNoTestLable() {
  var c = new Context('SomeClass');
  c.addTestHandler(function() {
    assert.ok(false);
  });
  c.addListener('failure', function(e) {
    assert.match(/SomeClass/, e.stack);
  });
  c.execute();
})();

<commit_msg>Added message to failures<commit_after>
var Context = require('node_should/context').Context;
var assert = require('assert');
require('../common');

// Configuration

(function contextIsInstantiable() {
  var c = new Context();
})();

(function contextIsComposite() {
  var c = new Context();
  c.addChild(new Context());
  assert.equal(1, c.numChildren);
})();

(function contextAddSetupHandlerFailsWithNullHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addSetupHandler();
  }, /must not be null/);
})();

(function contextAcceptsSetupHandler() {
  var c = new Context();
  c.addSetupHandler(function() {});
})();

(function contextAddTeardownHandlerFailsWithNullHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addTeardownHandler();
  }, /must not be null/);
})();

(function contextAcceptsTeardownHandlers() {
  var c = new Context();
  c.addTeardownHandler(function() {});
})();

(function contextUsesEmptyStringAsDefaultLabel() {
  var c = new Context();
  assert.equal('', c.getLabel());
})();

(function contextFailsWithNullTestHandler() {
  var c = new Context();
  assert.throws(function() {
    c.addTestHandler();
  }, /must not be null/);
})();

(function contextAcceptsTestHandler() {
  var c = new Context();
  c.addTestHandler(function() {});
})();

(function contextAcceptsLabel() {
  var c = new Context('root');
  assert.equal('root', c.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context('SomeClass');
  var child1 = new Context('with child');
  root.addChild(child1);

  assert.equal('SomeClass with child', child1.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context('SomeClass');
  var child1 = new Context();
  root.addChild(child1);

  assert.equal('SomeClass', child1.getLabel());
})();

(function contextBuildsLabelFromComposite() {
  var root = new Context();
  var child1 = new Context('SomeClass');
  root.addChild(child1);

  assert.equal('SomeClass', child1.getLabel());
})();

// Execution

(function contextFailsToExecuteIfNoTests() {
  var c = new Context();
  assert.throws(function() {
    c.execute();
  }, /no tests/);

})();

(function contextRunsSetupsThenTestsThenTeardowns() {
  var executed = [];
  var c = new Context('SomeClass');
  c.addSetupHandler(function() {
    executed.push('setup');
  });
  c.addTestHandler(function() {
    executed.push('test');
  });
  c.addTeardownHandler(function() {
    executed.push('teardown');
  });
  c.execute();

  var expected = ['setup', 'test', 'teardown'];
  assert.equal(expected.length, executed.length);
  assert.equal(expected[0], executed[0]);
  assert.equal(expected[1], executed[1]);
  assert.equal(expected[2], executed[2]);
})();

(function contextRunsHandlersInSharedScope() {
  var c = new Context('SomeClass');
  c.addSetupHandler(function() {
    this.foo = 'bar';
  });
  c.addTestHandler(function() {
    assert.equal(this.foo, 'bar');
  });
  c.execute();
})();

(function setupsCalledForEachTestMethod() {
  var executed = [];
  var c = new Context('SomeClass');
  c.addSetupHandler(function() { executed.push('setup1'); });
  c.addSetupHandler(function() { executed.push('setup2'); });
  c.addTestHandler(function() { executed.push('test1') });
  c.addTestHandler(function() { executed.push('test2') });
  c.addTestHandler(function() { executed.push('test3') });
  c.addTestHandler(function() { executed.push('test4') });
  c.addTeardownHandler(function() { executed.push('teardown1'); });
  c.addTeardownHandler(function() { executed.push('teardown2'); });
  c.execute();

  assert.equal(20, executed.length);
})();

(function testMethodsCalledWithDifferentScope() {
  var firstScope = null;
  var secondScope = null;
  var c = new Context();
  c.addTestHandler(function() { firstScope = this });
  c.addTestHandler(function() { secondScope = this });
  c.execute();
  assert.notStrictEqual(firstScope, secondScope);
})();

(function contextRunsSetupAsynchronouslyIfRequested() {
  var executed = [];
  var c = new Context();
  c.addSetupHandler(function() {
    var asyncHandler = this.async(function() {
      executed.push('asyncsetup');
    });
    setTimeout(asyncHandler, 0);
  });
  c.addTestHandler(function() {
    executed.push('test');
  });
  c.execute(function() {
    assert.equal(2, executed.length);
    assert.equal('asyncsetup', executed[0]);
    assert.equal('test', executed[1]);
  });
})();

(function contextRunsTestAsynchronously() {
  var executed = [];
  var c = new Context();
  c.addSetupHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asyncsetup');
    }), 0);
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asynctest1');
    }), 0);
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asynctest2');
    }), 0);
  });
  c.addTeardownHandler(function() {
    setTimeout(this.async(function() {
      executed.push('asyncteardown');
    }), 0);
  });

  c.execute(function() {
    assert.equal(6, executed.length);
  });
})();

(function contextCapturesAssertionExceptions() {
  var failure = null;
  var c = new Context();
  c.addListener('failure', function(f) {
    failure = f;
  });

  c.addTestHandler(function() {
    assert.ok(false, 'should be false');
  });

  c.execute();
  assert.ok(failure);
})();

(function contextCapturesAssertionErrors() {
  var failure = null;
  var c = new Context();
  c.addListener('failure', function(f) {
    failure = f;
  });
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      assert.ok(false, 'should be false');
    }), 0);
  });
  c.execute(function() {
    assert.ok(failure);
  });
})();

(function contextCapturesRuntimeErrors() {
  var error = null;
  var c = new Context('SomeClass');
  c.addListener('error', function(e) {
    error = e;
  });
  c.addTestHandler(function() {
    throw 'unkown application error';
  });
  c.execute();
})();

(function contextHandlesMultipleAsyncsInSameCall() {
  var executed = [];
  var c = new Context();
  c.addTestHandler(function() {
    setTimeout(this.async(function() {
      executed.push('one');
    }), 0);
    setTimeout(this.async(function() {
      executed.push('two');
    }), 0);
    setTimeout(this.async(function() {
      executed.push('three');
    }), 0);
  });

  c.execute(function() {
    assert.equal(3, executed.length);
    assert.equal(executed[0], 'one');
    assert.equal(executed[1], 'two');
    assert.equal(executed[2], 'three');
  });
})();

// Failure Messages

(function contextDisplaysHelpfulTestMessages() {
  var c = new Context('SomeClass');
  c.addTestHandler('accept argument', function() {
    assert.ok(false);
  });
  c.addListener('failure', function(e) {
    assert.match(/SomeClass should accept argument/, e.message);
  });
  c.execute();
})();

(function contextLabelShowsEvenIfNoTestLable() {
  var c = new Context('SomeClass');
  c.addTestHandler(function() {
    assert.ok(false);
  });
  c.addListener('failure', function(e) {
    assert.match(/SomeClass/, e.stack);
  });
  c.execute();
})();

<|endoftext|>