<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function () {
    var URL = 'http://localhost:8080/controlEscolar/index.php/';
    var IVA_GLOBAL = 16;
    var Cuenta;
    var IDEstudiante;
    var IDTutor;
    var FRECPAGO;

//PARA REALIZAR LA SUMA Y GUARDADO DEL PAGO DE LOS SERVICIOS
    $('.PAGARSERV').click(function () {

        var MODO = $(this).attr('data-mood');
        var IDExp = $(this).attr('data-ID');
        var IDUser = $(this).attr('data-User');
        var descuento = $(this).attr('data-Descuento');
        var FrecPago = $(this).attr('data-FrecPago');
        FRECPAGO = FrecPago;
        $('#descuento').attr('data-por-desc', descuento);
        $('#Parcialidad').text('Parcialidad \u0020' + FrecPago + ' de pagó.');

        ServicioContratado(IDExp, IDUser, descuento, FrecPago);

        if (MODO == 'create') {
            $('#PSguardar').attr('data-save-ID', IDExp);
        }
    });

    $('#PSguardar').click(function () {
        var IDExp = $(this).attr('data-save-ID');
        var servicios = "";

        var reinscripcion = new Reinscripcion(URL, IDExp);
        reinscripcion.init();
        $('#listado_servicios input[type=checkbox]').each(function () {
            if (this.checked) {
                servicios += $(this).val() + ',';
            }
        });
        reinscripcion.setServicios(servicios.slice(0, -1));
        CRUD_Reinscripcion('create', reinscripcion);

    });

    function CRUD_Reinscripcion(MODO, reinscripcion) {

        var correcto = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Exito! El Pagó se realizo.
";
        var error_enc = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Error!";
        var error_pie = "
";

        var descuento = $('#descuento').text();
        var total = $('#total_a_apagar').text();
        var subtotal = total - IVA(total);

        var request = $.ajax({
            url: URL + 'ajax/pago_servicios/' + MODO,
            method: 'POST',
            data: {IDExp: reinscripcion.instancia,
                Egrupo: reinscripcion.grupo,
                REservicio: reinscripcion.servicios,
                Descuento: descuento,
                SubTotal: subtotal,
                Total: total,
                DescBaja: reinscripcion.observaciones},
            dataType: 'html'
        });

        request.done(function (msg) {
            //alert(msg);
            if (msg === 'OK') {
                $('#resp-reinsc').html(correcto);
                $('#PSsalir').show();
                $('#PSrecibo').show();
                $('#PScancelar').hide();
                $('#PSguardar').hide();
            } else {
                $('#resp-reinsc').html(msg);
            }

        });

        request.fail(function (jqXHR, textStatus) {
            alert('FALLO AL GUARDAR EL PAGO: ' + jqXHR);
        });
    }

    $('#PSsalir').click(function () {
        location.reload();
    });

//FUNCIONES PARA DETERMINAR Y DEFINIR EL TIPO DE FRECUENCIA CON LA QUE SE REALIZARAN
//LOS PAGOS DE LOS SERVICIOS
    $('#frecpago').change(function () {
        var modo = $(this).val();

        $('#FP_diasemanal').hide();
        $('#FP_diahabil').hide();

        switch (modo) {
            case 'SEMANAL':
                $('#FP_diasemanal').show();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').hide();
                break;
            case 'QUINCENAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').show();
                break;
            case 'MENSUAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').show();
                $('#desc_quincenal').hide();
                break;
        }
    });

    $('.FORMAPAGO').click(function () {
        $('#FPcancelar').show();
        $('#FPguardar').show();
        $('#FPsalir').hide();
        Cuenta = $(this).attr('data-Cuenta');
        IDEstudiante = $(this).attr('data-IDEstudiante');
        IDTutor = $(this).attr('data-IDTutor');
        var FrecPago = $(this).attr('data-FrecPago');
        var Dia = $(this).attr('data-Dia');
        var IDExp = $(this).attr('data-ID');
        $('#FP-IDExp').val(IDExp);

        //LIMPIAR COMBOS DE FORMA DE PAGO
        $('#resp-FP').hide();
        $('#frecpago').val($('#frecpago > option:first').val());
        $('#diasemanal').val($('#diasemanal > option:first').val());
        $('#diahabil').val($('#diahabil > option:first').val());
        $('#FP_diasemanal').hide();
        $('#FP_diahabil').hide();
        $('#desc_quincenal').hide();

        switch (FrecPago) {
            case 'SEMANAL':
                $('#FP_diasemanal').show();
                $('#FP_diahabil').hide();
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#diasemanal > option[value="' + Dia + '"]').prop('selected', true);
                $('#desc_quincenal').hide();
                break;
            case 'QUINCENAL':
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').show();
                break;
            case 'MENSUAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').show();
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#diahabil > option[value="' + Dia + '"]').prop('selected', true);
                $('#desc_quincenal').hide();
                break;
        }
    });

    $('#FPguardar').click(function () {
        var FrecPago = $('#frecpago').val();
        var Dia = $('#diasemanal').val();
        var IDExp = $('#FP-IDExp').val();

        switch (FrecPago) {
            case 'SEMANAL':
                Dia = $('#diasemanal').val();
                break;
            case 'QUINCENAL':
                Dia = "15";
                break;
            case 'MENSUAL':
                Dia = $('#diahabil').val();
                ;
                break;
        }

        $.get(URL + "cobranza/GeneraFechaPago/" + FrecPago + '/' + Dia, function (data) {
            $("#fecha_limite_pago_" + IDExp).text(data);
        });

        guarda_forma_pago(Cuenta, IDEstudiante, IDTutor, FrecPago, Dia);
    });

    function guarda_forma_pago(Cuenta, IDEstudiante, IDTutor, FrecPago, Dia) {

        var correcto = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Exito! La Forma de Pago se guardo.
";
        var error_enc = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Error!";
        var error_pie = "
";

        var request = $.ajax({
            url: URL + 'ajax/forma_pago/',
            method: 'POST',
            data: {Cuenta: Cuenta,
                IDEstudiante: IDEstudiante,
                IDTutor: IDTutor,
                FrecPago: FrecPago,
                Dia: Dia},
            dataType: 'html'
        });

        request.done(function (msg) {
            if (msg === 'OK') {
                $('#resp-FP').show();
                $('#resp-FP').html(correcto);
                $('#FPcancelar').hide();
                $('#FPguardar').hide();
                $('#FPsalir').show();
            } else {
                $('#resp-FP').html(msg);
            }
        });

        request.fail(function (jqXHR, textStatus) {
            alert('Fallo al guardar la Forma de Pago: ' + jqXHR);
        });
    }

//FUNCION PARA CALCULAR EL COSTO DE LA COLEGIATURA
    $('input[type=checkbox]').click(function () {

        var total_colegiatura = 0.00;

        $('#listado_servicios input[type=checkbox]').each(function () {
            if (this.checked) {
                var precio_servicio = parseFloat($(this).attr('data-price'));
                var label = $(this).attr('id');
                var precio_parcialidad = 0.00;

                switch (FRECPAGO) {
                    case 'SEMANAL':
                        precio_parcialidad = precio_servicio / 4;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'QUINCENAL':
                        precio_parcialidad = precio_servicio / 2;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'MENSUAL':
                        total_colegiatura = total_colegiatura + precio_servicio;
                        $("#PriceText-" + label).text(precio_servicio);
                        break;
                }
            }
        });

        var tmp = $("#descuento").attr('data-por-desc');
        var descontando = (total_colegiatura * tmp) / 100;
        total_colegiatura -= descontando;

        var subtotal = (total_colegiatura) - IVA(total_colegiatura);
        $("#descuento").text('-' + descontando);
        $("#total_a_apagar").text(total_colegiatura);
        $('#subtotal').text(subtotal);
        $('#IVA').text(IVA(total_colegiatura));
    });

    $('#FPsalir').click(function () {
        location.reload();
    });

    function ServicioContratado(IDExp, IDUser, descuento, FrecPago) {
        var total_colegiatura = 0.00;
        $('#listado_servicios input[type=checkbox]').each(function () {
            if (esServicoContratado(IDExp, IDUser, $(this).val()) === 'OK') {

                var precio_servicio = parseFloat($(this).attr('data-price'));
                var label = $(this).attr('id');
                var precio_parcialidad = 0.00;

                switch (FrecPago) {
                    case 'SEMANAL':
                        precio_parcialidad = precio_servicio / 4;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'QUINCENAL':
                        precio_parcialidad = precio_servicio / 2;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'MENSUAL':
                        total_colegiatura = total_colegiatura + precio_servicio;
                        $("#PriceText-" + label).text(precio_servicio);
                        break;
                }

                $(this).prop('checked', true);
                $(this).prop('disabled', true);
            } else {
                $(this).prop('checked', false);
                $(this).prop('disabled', false);
            }

        });

        var descontando = (total_colegiatura * descuento) / 100;
        total_colegiatura -= descontando;
        var subtotal = (total_colegiatura - descontando) - IVA(total_colegiatura);

        $("#descuento").text('-' + descontando);
        $("#total_a_apagar").text(total_colegiatura);
        $('#subtotal').text(subtotal);
        $('#IVA').text(IVA(total_colegiatura));
    }

    function esServicoContratado(IDExp, IDUser, ID) {
        var resp;
        var request = $.ajax({
            url: URL + 'ajax/esServicoContratado/' + ID,
            method: 'POST',
            data: {IDExp: IDExp, IDUser: IDUser, ID: ID},
            dataType: 'html',
            async: false
        });

        request.done(function (msg) {
//            alert(msg)
            resp = msg;
        });

        request.fail(function (jqXHR, textStatus) {
            alert('Fallo al guardar el pago: ' + textStatus);
        });
        return resp;
    }

    function IVA(total) {
        var total_con_iva = (total * IVA_GLOBAL) / 100;
        return total_con_iva;
    }
});<commit_msg>Modulo de detalles de Pago visualizacion<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function () {
    var URL = 'http://localhost:8080/controlEscolar/index.php/';
    var IVA_GLOBAL = 16;
    var Cuenta;
    var IDEstudiante;
    var IDTutor;
    var FRECPAGO;

//PARA REALIZAR LA SUMA Y GUARDADO DEL PAGO DE LOS SERVICIOS
    $('.PAGARSERV').click(function () {

        var MODO = $(this).attr('data-mood');
        var IDExp = $(this).attr('data-ID');
        var IDUser = $(this).attr('data-User');
        var descuento = $(this).attr('data-Descuento');
        var FrecPago = $(this).attr('data-FrecPago');
        FRECPAGO = FrecPago;
        $('#descuento').attr('data-por-desc', descuento);
        $('#Parcialidad').text('Parcialidad \u0020' + FrecPago + ' de pagó.');

        ServicioContratado(IDExp, IDUser, descuento, FrecPago);

        if (MODO == 'create') {
            $('#PSguardar').attr('data-save-ID', IDExp);
        }
    });

    $('#PSguardar').click(function () {
        var IDExp = $(this).attr('data-save-ID');
        var servicios = "";

        var reinscripcion = new Reinscripcion(URL, IDExp);
        reinscripcion.init();
        $('#listado_servicios input[type=checkbox]').each(function () {
            if (this.checked) {
                servicios += $(this).val() + ',';
            }
        });
        reinscripcion.setServicios(servicios.slice(0, -1));
        CRUD_Reinscripcion('create', reinscripcion);

    });

    function CRUD_Reinscripcion(MODO, reinscripcion) {

        var correcto = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Exito! El Pagó se realizo.
";
        var error_enc = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Error!";
        var error_pie = "
";

        var descuento = $('#descuento').text();
        var total = $('#total_a_apagar').text();
        var subtotal = total - IVA(total);

        var request = $.ajax({
            url: URL + 'ajax/pago_servicios/' + MODO,
            method: 'POST',
            data: {IDExp: reinscripcion.instancia,
                Egrupo: reinscripcion.grupo,
                REservicio: reinscripcion.servicios,
                Descuento: descuento,
                SubTotal: subtotal,
                Total: total,
                DescBaja: reinscripcion.observaciones},
            dataType: 'html'
        });

        request.done(function (msg) {
            //alert(msg);
            if (msg === 'OK') {
                $('#resp-reinsc').html(correcto);
                $('#PSsalir').show();
                $('#PSrecibo').show();
                $('#PScancelar').hide();
                $('#PSguardar').hide();
            } else {
                $('#resp-reinsc').html(msg);
            }

        });

        request.fail(function (jqXHR, textStatus) {
            alert('FALLO AL GUARDAR EL PAGO: ' + jqXHR);
        });
    }

    $('#PSsalir').click(function () {
        location.reload();
    });

//FUNCIONES PARA DETERMINAR Y DEFINIR EL TIPO DE FRECUENCIA CON LA QUE SE REALIZARAN
//LOS PAGOS DE LOS SERVICIOS
    $('#frecpago').change(function () {
        var modo = $(this).val();

        $('#FP_diasemanal').hide();
        $('#FP_diahabil').hide();

        switch (modo) {
            case 'SEMANAL':
                $('#FP_diasemanal').show();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').hide();
                break;
            case 'QUINCENAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').show();
                break;
            case 'MENSUAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').show();
                $('#desc_quincenal').hide();
                break;
        }
    });

    $('.FORMAPAGO').click(function () {
        $('#FPcancelar').show();
        $('#FPguardar').show();
        $('#FPsalir').hide();
        Cuenta = $(this).attr('data-Cuenta');
        IDEstudiante = $(this).attr('data-IDEstudiante');
        IDTutor = $(this).attr('data-IDTutor');
        var FrecPago = $(this).attr('data-FrecPago');
        var Dia = $(this).attr('data-Dia');
        var IDExp = $(this).attr('data-ID');
        $('#FP-IDExp').val(IDExp);

        //LIMPIAR COMBOS DE FORMA DE PAGO
        $('#resp-FP').hide();
        $('#frecpago').val($('#frecpago > option:first').val());
        $('#diasemanal').val($('#diasemanal > option:first').val());
        $('#diahabil').val($('#diahabil > option:first').val());
        $('#FP_diasemanal').hide();
        $('#FP_diahabil').hide();
        $('#desc_quincenal').hide();

        switch (FrecPago) {
            case 'SEMANAL':
                $('#FP_diasemanal').show();
                $('#FP_diahabil').hide();
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#diasemanal > option[value="' + Dia + '"]').prop('selected', true);
                $('#desc_quincenal').hide();
                break;
            case 'QUINCENAL':
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').hide();
                $('#desc_quincenal').show();
                break;
            case 'MENSUAL':
                $('#FP_diasemanal').hide();
                $('#FP_diahabil').show();
                $('#frecpago > option[value="' + FrecPago + '"]').prop('selected', true);
                $('#diahabil > option[value="' + Dia + '"]').prop('selected', true);
                $('#desc_quincenal').hide();
                break;
        }
    });

    $('#FPguardar').click(function () {
        var FrecPago = $('#frecpago').val();
        var Dia = $('#diasemanal').val();
        var IDExp = $('#FP-IDExp').val();

        switch (FrecPago) {
            case 'SEMANAL':
                Dia = $('#diasemanal').val();
                break;
            case 'QUINCENAL':
                Dia = "15";
                break;
            case 'MENSUAL':
                Dia = $('#diahabil').val();
                ;
                break;
        }

        $.get(URL + "cobranza/GeneraFechaPago/" + FrecPago + '/' + Dia, function (data) {
            $("#fecha_limite_pago_" + IDExp).text(data);
        });

        guarda_forma_pago(Cuenta, IDEstudiante, IDTutor, FrecPago, Dia);
    });

    function guarda_forma_pago(Cuenta, IDEstudiante, IDTutor, FrecPago, Dia) {

        var correcto = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Exito! La Forma de Pago se guardo.
";
        var error_enc = "
<button type='button' class='close' data-dismiss='alert' aria-label='Close'>×</button>Error!";
        var error_pie = "
";

        var request = $.ajax({
            url: URL + 'ajax/forma_pago/',
            method: 'POST',
            data: {Cuenta: Cuenta,
                IDEstudiante: IDEstudiante,
                IDTutor: IDTutor,
                FrecPago: FrecPago,
                Dia: Dia},
            dataType: 'html'
        });

        request.done(function (msg) {
            if (msg === 'OK') {
                $('#resp-FP').show();
                $('#resp-FP').html(correcto);
                $('#FPcancelar').hide();
                $('#FPguardar').hide();
                $('#FPsalir').show();
            } else {
                $('#resp-FP').html(msg);
            }
        });

        request.fail(function (jqXHR, textStatus) {
            alert('Fallo al guardar la Forma de Pago: ' + jqXHR);
        });
    }

//FUNCION PARA CALCULAR EL COSTO DE LA COLEGIATURA
    $('input[type=checkbox]').click(function () {

        var total_colegiatura = 0.00;

        $('#listado_servicios input[type=checkbox]').each(function () {
            if (this.checked) {
                var precio_servicio = parseFloat($(this).attr('data-price'));
                var label = $(this).attr('id');
                var precio_parcialidad = 0.00;

                switch (FRECPAGO) {
                    case 'SEMANAL':
                        precio_parcialidad = precio_servicio / 4;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'QUINCENAL':
                        precio_parcialidad = precio_servicio / 2;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'MENSUAL':
                        total_colegiatura = total_colegiatura + precio_servicio;
                        $("#PriceText-" + label).text(precio_servicio);
                        break;
                }
            }
        });

        var tmp = $("#descuento").attr('data-por-desc');
        var descontando = (total_colegiatura * tmp) / 100;
        total_colegiatura -= descontando;

        var subtotal = (total_colegiatura) - IVA(total_colegiatura);
        $("#descuento").text('-' + descontando);
        $("#total_a_apagar").text(total_colegiatura);
        $('#subtotal').text(subtotal);
        $('#IVA').text(IVA(total_colegiatura));
    });

    $('#FPsalir').click(function () {
        location.reload();
    });

    function ServicioContratado(IDExp, IDUser, descuento, FrecPago) {
        var total_colegiatura = 0.00;
        $('#listado_servicios input[type=checkbox]').each(function () {
            if (esServicoContratado(IDExp, IDUser, $(this).val()) === 'OK') {

                var precio_servicio = parseFloat($(this).attr('data-price'));
                var label = $(this).attr('id');
                var precio_parcialidad = 0.00;

                switch (FrecPago) {
                    case 'SEMANAL':
                        precio_parcialidad = precio_servicio / 4;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'QUINCENAL':
                        precio_parcialidad = precio_servicio / 2;
                        total_colegiatura = total_colegiatura + precio_parcialidad;
                        $("#PriceText-" + label).text(precio_parcialidad);
                        break;
                    case 'MENSUAL':
                        total_colegiatura = total_colegiatura + precio_servicio;
                        $("#PriceText-" + label).text(precio_servicio);
                        break;
                }

                $(this).prop('checked', true);
                $(this).prop('disabled', true);
            } else {
                $(this).prop('checked', false);
                $(this).prop('disabled', false);
            }

        });

        var descontando = (total_colegiatura * descuento) / 100;
        total_colegiatura -= descontando;
        var subtotal = (total_colegiatura - descontando) - IVA(total_colegiatura);

        $("#descuento").text('-' + descontando);
        $("#total_a_apagar").text(total_colegiatura);
        $('#subtotal').text(subtotal);
        $('#IVA').text(IVA(total_colegiatura));
    }

    function esServicoContratado(IDExp, IDUser, ID) {
        var resp;
        var request = $.ajax({
            url: URL + 'ajax/esServicoContratado/' + ID,
            method: 'POST',
            data: {IDExp: IDExp, IDUser: IDUser, ID: ID},
            dataType: 'html',
            async: false
        });

        request.done(function (msg) {
//            alert(msg)
            resp = msg;
        });

        request.fail(function (jqXHR, textStatus) {
            alert('Fallo al guardar el pago: ' + textStatus);
        });
        return resp;
    }

    function IVA(total) {
        var total_con_iva = (total * IVA_GLOBAL) / 100;
        return total_con_iva;
    }

    /***************************************************************************
     * FUNCIONES PARA VER LOS DETALLES DE LOS PAGOS REALIZADOS                 *
     ***************************************************************************/

    $('.DETALLEPAGO').click(function () {
        var IDExp = $(this).attr('data-IDExp');
        var IDPago = $(this).attr('data-IDPago');
        var html = "";
        $("#lista_detalles > tbody").append("");

        $.getJSON(URL + 'ajax/detallesPago/' + IDExp + '/' + IDPago, function (datalles) {
            $.each(datalles, function (key, value) {
                html += "
";
                html += "" + value.IDPagSer + "	";
//                html += "" + value.FecPago + "	";
                html += "" + value.Descripcion + "	";
                html += "" + value.Nombre + "	";
                html += "" + value.Descuento + "	";
                html += "" + value.Recargo + "	";
                html += "" + value.SubTotal + "	";
                html += "" + value.Total + "	";
                html += "
";
            });
            $("#lista_detalles > tbody").append(html);
        });
    });

});<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Blocks.variables');

goog.require('Blockly.Blocks');

Blockly.Blocks.variables.HUE = 330//'#af5180'//330;

// ************************************************************************
// THIS SECTION IS INSERTED INTO BLOCKLY BY BLOCKLYDUINO.
//  Blockly.Blocks['variables_declare'] = {
//  // Variable setter.
//   init: function() {
//     this.setColour(Blockly.Blocks.variables.HUE);
//     this.appendValueInput('VALUE', null)
//         .appendField(Blockly.MIXLY_DECLARE)
//         .appendField(new Blockly.FieldTextInput(''), 'VAR')
//         //.appendField(Blockly.MIXLY_AS)
//         //.appendField(new Blockly.FieldDropdown([[Blockly.MIXLY_MICROBIT_JS_TYPE_NUMBER, 'number'], [Blockly.MIXLY_MICROBIT_JS_TYPE_STRING, 'string'], [Blockly.MIXLY_MICROBIT_JS_TYPE_BOOLEAN, 'boolean']]), 'TYPE')
// 	    .appendField(Blockly.MIXLY_VALUE);
//     this.setPreviousStatement(true);
//     this.setNextStatement(true);
//     this.setTooltip(Blockly.MIXLY_TOOLTIP_VARIABLES_DECLARE);
//   },
//   getVars: function() {
//     return [this.getFieldValue('VAR')];
//   },
//   renameVar: function(oldName, newName) {
//     if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
//       this.setTitleValue(newName, 'VAR');
//     }
//   }
// };
// ************************************************************************

Blockly.Blocks['variables_get'] = {
  init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
    this.appendDummyInput()
        .appendField(new Blockly.FieldTextInput(''), 'VAR')
    this.setOutput(true);
    this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP);
  },
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  }/*,
  onchange: function() {
	  var varName = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'),Blockly.Variables.NAME_TYPE);
	  if(Blockly.Arduino.definitions_['var_declare'+varName]){
		  this.setWarningText(null);
	  }else{
		  this.setWarningText(Blockly.MIXLY_WARNING_NOT_DECLARE);
	  }
  }*/
};

// Blockly.Blocks['variables_set'] = {
//   init: function() {
//     this.setColour(Blockly.Blocks.variables.HUE);
//     this.appendValueInput('VALUE')
//         .appendField(new Blockly.FieldTextInput(''), 'VAR')
// 		.appendField(Blockly.LANG_VARIABLES_SET_TITLE);
//     this.setPreviousStatement(true);
//     this.setNextStatement(true);
//     this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP);
//   },
//   getVars: function() {
//     return [this.getFieldValue('VAR')];
//   },
//   renameVar: function(oldName, newName) {
//     if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
//       this.setFieldValue(newName, 'VAR');
//     }
//   }/*,
//   onchange: function() {
// 	  var varName = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'),Blockly.Variables.NAME_TYPE);
// 	  if(Blockly.Arduino.definitions_['var_declare'+varName]){
// 		  this.setWarningText(null);
// 	  }else{
// 		  this.setWarningText(Blockly.MIXLY_WARNING_NOT_DECLARE);
// 	  }
//   }*/
// };
Blockly.Blocks['variables_set'] = {
   init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
    this.appendValueInput('VALUE')
        .appendField(new Blockly.FieldTextInput(''), 'VAR')
		.appendField(Blockly.LANG_VARIABLES_SET_TITLE);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP);
  },
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  }
};
/**
  * Block for basic data type change.
  * @this Blockly.Block
  */
Blockly.Blocks['variables_change'] = {
    init: function () {
        this.setColour(Blockly.Blocks.variables.HUE);
        var DATATYPES =
         [
          [Blockly.MIXLY_MICROBIT_TYPE_INT, "int"],
          [Blockly.MIXLY_MICROBIT_TYPE_FLOAT, "float"],
          [Blockly.MIXLY_MICROBIT_TYPE_STRING, "str"],
          [Blockly.MIXLY_MICROBIT_TYPE_LIST, "list"],
          [Blockly.MIXLY_MICROBIT_TYPE_TUPLE, "tuple"],
          [Blockly.MIXLY_MICROBIT_TYPE_DICT,"dict"],
          [Blockly.MIXLY_MICROBIT_TYPE_SETS,"set"]
          ];

        this.appendValueInput('MYVALUE')
             .appendField(new Blockly.FieldDropdown(DATATYPES), 'OP');
        // Assign 'this' to a variable for use in the tooltip closure below.
        this.setOutput(true);

    }
};

Blockly.Blocks['variables_global'] = {
  init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.MIXLY_PYTHON_GLOBAL);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.TEXT_PRINT_INLINE_TOOLTIP);
  }
};

    <commit_msg>add global<commit_after>'use strict';

goog.provide('Blockly.Blocks.variables');

goog.require('Blockly.Blocks');

Blockly.Blocks.variables.HUE = 330//'#af5180'//330;

// ************************************************************************
// THIS SECTION IS INSERTED INTO BLOCKLY BY BLOCKLYDUINO.
//  Blockly.Blocks['variables_declare'] = {
//  // Variable setter.
//   init: function() {
//     this.setColour(Blockly.Blocks.variables.HUE);
//     this.appendValueInput('VALUE', null)
//         .appendField(Blockly.MIXLY_DECLARE)
//         .appendField(new Blockly.FieldTextInput(''), 'VAR')
//         //.appendField(Blockly.MIXLY_AS)
//         //.appendField(new Blockly.FieldDropdown([[Blockly.MIXLY_MICROBIT_JS_TYPE_NUMBER, 'number'], [Blockly.MIXLY_MICROBIT_JS_TYPE_STRING, 'string'], [Blockly.MIXLY_MICROBIT_JS_TYPE_BOOLEAN, 'boolean']]), 'TYPE')
// 	    .appendField(Blockly.MIXLY_VALUE);
//     this.setPreviousStatement(true);
//     this.setNextStatement(true);
//     this.setTooltip(Blockly.MIXLY_TOOLTIP_VARIABLES_DECLARE);
//   },
//   getVars: function() {
//     return [this.getFieldValue('VAR')];
//   },
//   renameVar: function(oldName, newName) {
//     if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
//       this.setTitleValue(newName, 'VAR');
//     }
//   }
// };
// ************************************************************************

Blockly.Blocks['variables_get'] = {
  init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
    this.appendDummyInput()
        .appendField(new Blockly.FieldTextInput(''), 'VAR')
    this.setOutput(true);
    this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP);
  },
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  }/*,
  onchange: function() {
	  var varName = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'),Blockly.Variables.NAME_TYPE);
	  if(Blockly.Arduino.definitions_['var_declare'+varName]){
		  this.setWarningText(null);
	  }else{
		  this.setWarningText(Blockly.MIXLY_WARNING_NOT_DECLARE);
	  }
  }*/
};

// Blockly.Blocks['variables_set'] = {
//   init: function() {
//     this.setColour(Blockly.Blocks.variables.HUE);
//     this.appendValueInput('VALUE')
//         .appendField(new Blockly.FieldTextInput(''), 'VAR')
// 		.appendField(Blockly.LANG_VARIABLES_SET_TITLE);
//     this.setPreviousStatement(true);
//     this.setNextStatement(true);
//     this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP);
//   },
//   getVars: function() {
//     return [this.getFieldValue('VAR')];
//   },
//   renameVar: function(oldName, newName) {
//     if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
//       this.setFieldValue(newName, 'VAR');
//     }
//   }/*,
//   onchange: function() {
// 	  var varName = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'),Blockly.Variables.NAME_TYPE);
// 	  if(Blockly.Arduino.definitions_['var_declare'+varName]){
// 		  this.setWarningText(null);
// 	  }else{
// 		  this.setWarningText(Blockly.MIXLY_WARNING_NOT_DECLARE);
// 	  }
//   }*/
// };
Blockly.Blocks['variables_set'] = {
   init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
    this.appendValueInput('VALUE')
        .appendField(new Blockly.FieldTextInput(''), 'VAR')
		.appendField(Blockly.LANG_VARIABLES_SET_TITLE);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setTooltip(Blockly.Msg.VARIABLES_SET_TOOLTIP);
  },
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  }
};
/**
  * Block for basic data type change.
  * @this Blockly.Block
  */
Blockly.Blocks['variables_change'] = {
    init: function () {
        this.setColour(Blockly.Blocks.variables.HUE);
        var DATATYPES =
         [
          [Blockly.MIXLY_MICROBIT_TYPE_INT, "int"],
          [Blockly.MIXLY_MICROBIT_TYPE_FLOAT, "float"],
          [Blockly.MIXLY_MICROBIT_TYPE_STRING, "str"],
          [Blockly.MIXLY_MICROBIT_TYPE_LIST, "list"],
          [Blockly.MIXLY_MICROBIT_TYPE_TUPLE, "tuple"],
          [Blockly.MIXLY_MICROBIT_TYPE_DICT,"dict"],
          [Blockly.MIXLY_MICROBIT_TYPE_SETS,"set"]
          ];

        this.appendValueInput('MYVALUE')
             .appendField(new Blockly.FieldDropdown(DATATYPES), 'OP');
        // Assign 'this' to a variable for use in the tooltip closure below.
        this.setOutput(true);

    }
};

Blockly.Blocks['variables_global'] = {
  init: function() {
    this.setColour(Blockly.Blocks.variables.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.MIXLY_PYTHON_GLOBAL)
        .setCheck("var");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.TEXT_PRINT_INLINE_TOOLTIP);
  }
};

    <|endoftext|>


<commit_before>// Source : https://oj.leetcode.com/problems/two-sum/
// Author : Dean Shi
// Date   : 2015-05-30

/**********************************************************************************
 *
 * Given an array of integers, find two numbers such that they add up to a specific target number.
 *
 * The function twoSum should return indices of the two numbers such that they add up to the target,
 * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
 * are not zero-based.
 *
 * You may assume that each input would have exactly one solution.
 *
 * Input: numbers={2, 7, 11, 15}, target=9
 * Output: index1=1, index2=2
 *
 *
 **********************************************************************************/

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var hash = {};
    var result = [];

    for (var i = 0, l = nums.length; i < l; ++i) {
        var n = nums[i];

        // find the second one
        if (hash[n] > 0) {
            result.push(hash[n], i + 1);
            break;
        } else {
            // store the index
            hash[target - n] = i + 1;
        }
    }
    return result;
};

var testCase = [2, 7, 11, 15];
var result = twoSum(testCase, 9);

console.log(result.toString() === '1,2'); // true
<commit_msg>Update TwoSum.js<commit_after>// Source : https://oj.leetcode.com/problems/two-sum/
// Author : Dean Shi
// Date   : 2015-05-30

/**********************************************************************************
 *
 * Given an array of integers, find two numbers such that they add up to a specific target number.
 *
 * The function twoSum should return indices of the two numbers such that they add up to the target,
 * where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
 * are not zero-based.
 *
 * You may assume that each input would have exactly one solution.
 *
 * Input: numbers={2, 7, 11, 15}, target=9
 * Output: index1=1, index2=2
 *
 *
 **********************************************************************************/

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const hash = {};
    for (let n, i = 0, l = nums.length; i < l; ++i) {
        n = nums[i];

        if (hash[n] >= 0) {
            return [hash[n], i]
        }
        hash[target - n] = i
    }
};

var testCase = [2, 7, 11, 15];
var result = twoSum(testCase, 9);

console.log(result.toString() === '1,2'); // true
<|endoftext|>


<commit_before>var request = require('xhr')
var React = require('react')

module.exports = React.createClass({
  getInitialState: function () {
    return { confirmation: false } },

  delete: function () {
    this.props.remove_payment(this.props.id)
    this.setState({ confirmation: false }) },

  attempt_delete: function () {
    this.setState({ confirmation: true }) },

  which_delete: function () {
    return this.state.confirmation ? this.delete : this.attempt_delete },

  which_text: function () {
    return this.state.confirmation ? 'Confirm' : 'X' },

   render: function () {
    return (<button
      className={'small-button ' + (this.state.confirmation ? 'red' : '') }
      onClick={this.which_delete()}>{this.which_text()}</button>)}})

<commit_msg>Refactor deletion_entry.js<commit_after>var React = require('react')

module.exports = React.createClass({
  getInitialState: function () {
    return { confirmation: false }
  },

  delete: function () {
    this.props.remove_payment(this.props.id)
    this.setState({ confirmation: false })
  },

  attempt_delete: function () {
    this.setState({ confirmation: true })
  },

  which_delete: function () {
    return this.state.confirmation ? this.delete : this.attempt_delete
  },

  which_text: function () {
    return this.state.confirmation ? 'Confirm' : 'X'
  },

  render: function () {
    return (
      <button
        className={'small-button ' + (this.state.confirmation ? 'red' : '') }
        onClick={this.which_delete()}
      >
        {this.which_text()}
      </button>
    )
  }
})
<|endoftext|>


<commit_before>// Copyright (C) 2016 Goom Inc. All rights reserved.

import React, { PropTypes } from 'react';

import ShippingPolicyCountry from './ShippingPolicyCountry';

export default React.createClass({
  contextTypes: {
    router: PropTypes.object,
  },
  render() {
    return (

          사입비 및 배송비 책정기준

사입비는 어떻게 책정되나요?

            [총 구매 상품] + [부가세(10%)]의 3.3%에 해당하는 금액이 사입비로 책정됩니다.

배송비는 어떻게 책정되나요?

국내 택배 배송

                상품은 택배발송 되며 배송비는 3,300원(부가세 포함)입니다.

                국내 전지역(도서산간 포함) 중량/부피 상관없이 동일한 배송비가 선 결제됩니다.

해외 택배 배송

                도매사이트의 특성 상, 사입 전 구매상품의 중량을 확인할 수 없기 때문에 총 상품금액의 일정 %를 배송비로 미리 선결제 받고 있으며 발송 전 정확한 중량이 확인되면 실 배송비가 책정됩니다.

                책정된 실 배송비가 선결제하신 배송비보다 적을 경우, 차액은 주문 시 결제수단으로 자동 환불 처리해 드리고 있습니다.

해외 국가별 배송비 책정 기준

            <ShippingPolicyCountry />

    );
  },
});
<commit_msg>m - shipping policy from cms data<commit_after><|endoftext|>


<commit_before>var registry = registry || {};

(function (server, registry) {
    var log = new Log();

    var Resource = Packages.org.wso2.carbon.registry.core.Resource;

    var Collection = Packages.org.wso2.carbon.registry.core.Collection;

    var Comment = Packages.org.wso2.carbon.registry.core.Comment;

    var StaticConfiguration = Packages.org.wso2.carbon.registry.core.config.StaticConfiguration;

    var content = function (registry, resource, paging) {
        if (resource instanceof Collection) {
            // #1 : this always sort children by name, so sorting cannot be done for the chunk
            return function (pagination) {
                pagination = pagination || paging;
                return children(registry, resource, pagination);
            };
        }
        if (resource instanceof Comment) {
            return String(resource.getText());
        }
        var stream = resource.getContentStream();
        if (stream) {
            return new Stream(stream);
        }
        return String(resource.content);
    };

    var commentsQuery = function (registry, resource, paging) {
        var query, sort, limit, sorter,
            paged = true,
            database = registry.database;
        if (registry.versioning.comments) {
            query = 'SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC ' +
                'WHERE C.REG_ID=RC.REG_COMMENT_ID AND RC.REG_VERSION=' + resource.versionNumber + ' ' +
                'AND C.REG_TENANT_ID=' + registry.tenant + ' AND RC.REG_TENANT_ID=' + registry.tenant;
        } else {
            if (resource instanceof Collection) {
                query = 'SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC ' +
                    'WHERE C.REG_ID=RC.REG_COMMENT_ID AND RC.REG_PATH_ID=' + resource.id + ' ' +
                    'AND RC.REG_RESOURCE_NAME IS NULL AND C.REG_TENANT_ID=' + registry.tenant + ' ' +
                    'AND RC.REG_TENANT_ID=' + registry.tenant;
            } else {
                query = 'SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC ' +
                    'WHERE C.REG_ID=RC.REG_COMMENT_ID AND RC.REG_PATH_ID=' + resource.id + ' ' +
                    'AND RC.REG_RESOURCE_NAME = ' + resource.name + ' AND C.REG_TENANT_ID=' + registry.tenant + ' ' +
                    'AND RC.REG_TENANT_ID=' + registry.tenant;
            }
        }
        switch (paging.sort) {
            case 'recent' :
            default:
                sort = ' ORDER BY C.REG_COMMENTED_TIME DESC';
                sorter = function (l, r) {
                    return l.created.time < r.created.time;
                };
        }
        switch (database.name) {
            case 'MySQL':
                limit = ' LIMIT ' + paging.count + ' OFFSET ' + paging.start;
                break;
            default :
                paged = false;
                limit = '';
        }
        query += sort + limit;
        return {
            query: query,
            sorter: sorter,
            paged: paged
        };
    };

    var childrenQuery = function (registry, resource, paging) {
        var query, sort, sorter, limit,
            paged = true,
            pathId = resource.pathID,
            database = registry.database;
        query = 'SELECT R.REG_PATH_ID, R.REG_NAME, R.REG_CREATED_TIME AS REG_CREATED_TIME ' +
            'FROM REG_RESOURCE R WHERE ' +
            'R.REG_PATH_ID=' + pathId + ' AND ' +
            'R.REG_TENANT_ID=' + registry.tenant + ' ' +
            'UNION ' +
            'SELECT P.REG_PATH_ID, R.REG_NAME, R.REG_CREATED_TIME AS REG_CREATED_TIME ' +
            'FROM REG_PATH P, REG_RESOURCE R WHERE ' +
            'P.REG_PATH_PARENT_ID=' + pathId + ' AND ' +
            'P.REG_TENANT_ID=' + registry.tenant + ' AND ' +
            'R.REG_PATH_ID=P.REG_PATH_ID AND ' +
            'R.REG_NAME IS NULL AND ' +
            'R.REG_TENANT_ID=' + registry.tenant;

        paging = merge({
            start: 0,
            count: 25,
            sort: 'recent'
        }, paging);
        switch (paging.sort) {
            case 'recent' :
            default:
                sort = ' ORDER BY REG_CREATED_TIME DESC';
                sorter = function (l, r) {
                    return l.created.time < r.created.time;
                };
        }
        switch (database.name) {
            case 'MySQL':
                limit = ' LIMIT ' + paging.count + ' OFFSET ' + paging.start;
                break;
            default :
                paged = false;
                limit = '';
        }
        query += sort + limit;
        return {
            query: query,
            sorter: sorter,
            paged: paged
        };
    };

    var children = function (registry, resource, paging) {
        var o, pathz, length, i, res,
            pathId = resource.pathID,
            resources = [],
            paths = [];
        o = childrenQuery(registry, resource, paging);
        pathz = registry.query({
            query: o.query,
            resultType: 'Resource'
        });
        length = pathz.length;
        for (i = 0; i < length; i++) {
            res = registry.registry.get(pathz[i]);
            if (pathId == res.pathID && !res.name) {
                continue;
            }
            resources.push({
                path: String(res.path),
                created: {
                    time: res.createdTime.time
                }
            });
        }
        //we have to manually sort this due to the bug in registry.getChildren() (#1 above)
        resources.sort(o.sorter);
        length = resources.length;
        for (i = 0; i < length; i++) {
            paths.push(resources[i].path);
        }
        return o.paged ? paths : paths.slice(paging.start, paging.start + paging.count);
    };

    var resource = function (registry, resource) {
        var path = String(resource.path),
            o = {
                created: {
                    author: String(resource.authorUserName),
                    time: resource.createdTime.time
                },
                content: content(registry, resource, {
                    start: 0,
                    count: 10
                }),
                id: String(resource.id),
                version: resource.versionNumber
            };
        if (resource instanceof Comment) {
            return o;
        }
        if (resource instanceof Collection) {
            o.collection = (resource instanceof Collection);
        }
        o.uuid = String(resource.UUID);
        o.path = String(path);
        o.name = String(resource.name) || resolveName(path);
        o.description = String(resource.description);
        o.updated = {
            author: String(resource.lastUpdaterUserName),
            time: resource.lastModified.time
        };
        o.mediaType = String(resource.mediaType);
        o.properties = function () {
            return properties(resource);
        };
        o.aspects = function () {
            return aspects(resource);
        };
        return o;
    };

    var properties = function (resource) {
        var prop,
            properties = resource.properties,
            props = properties.keySet().toArray(),
            length = props.length,
            o = {};
        for (var i = 0; i < length; i++) {
            prop = props[i];
            o[prop] = resource.getPropertyValues(prop).toArray();
        }
        return o;
    };

    var aspects = function (resource) {
        var aspects = resource.getAspects();
        return aspects ? aspects.toArray() : [];
    };

    var resolveName = function (path) {
        path = path.charAt(path.length - 1) === '/' ? path.substring(0, path.length - 1) : path;
        return path.substring(path.lastIndexOf('/') + 1);
    };

    var merge = function (def, options) {
        if (options) {
            for (var op in def) {
                if (def.hasOwnProperty(op)) {
                    def[op] = options[op] || def[op];
                }
            }
        }
        return def;
    };

    var Registry = function (serv, auth) {
        var registryService = server.osgiService('org.wso2.carbon.registry.core.service.RegistryService');
        if (auth.username) {
            this.tenant = server.tenantId({
                domain: auth.domain,
                username: auth.username
            });
            this.registry = registryService.getRegistry(auth.username, auth.password, this.tenant);
            this.username = auth.username;
            this.versioning = {
                comments: StaticConfiguration.isVersioningComments()
            };
            var db = this.registry.getRegistryContext().getDataAccessManager().getDataSource()
                .getConnection().getMetaData();
            this.database = {
                name: String(db.getDatabaseProductName()),
                version: {
                    major: db.getDatabaseMajorVersion(),
                    minor: db.getDatabaseMinorVersion()
                }
            };
        } else {
            throw new Error('Unsupported authentication mechanism : ' + stringify(auth.username));
        }
        this.server = serv;
    };

    registry.Registry = Registry;

    Registry.prototype.put = function (path, resource) {
        var res;
        if (resource.collection) {
            res = this.registry.newCollection();
        } else {
            res = this.registry.newResource();
            res.content = resource.content || null;
            res.mediaType = resource.mediaType || null;
        }
        res.name = resource.name;
        res.description = resource.description || null;
        res.UUID = resource.uuid || null;

        var values, length, i, ArrayList,
            properties = resource.properties;
        if (properties) {
            ArrayList = java.util.ArrayList;
            for (var name in properties) {
                var list = new ArrayList();
                if (properties.hasOwnProperty(name)) {
                    values = properties[name];
                    values = values instanceof Array ? values : [values];
                    length = values.length;
                    for (i = 0; i < length; i++) {
                        list.add(values[i]);
                    }
                    res.setProperty(name, list);
                }
            }
        }

        var aspects = resource.aspects;
        if (aspects) {
            length = aspects.length;
            for (i = 0; i < length; i++) {
                res.addAspect(aspects[i]);
            }
        }

        this.registry.put(path, res);
    };

    Registry.prototype.remove = function (path) {
        this.registry.delete(path);
    };

    Registry.prototype.move = function (src, dest) {
        this.registry.move(src, dest);
    };

    Registry.prototype.rename = function (current, newer) {
        this.registry.rename(current, newer);
    };

    Registry.prototype.copy = function (src, dest) {
        this.registry.rename(src, dest);
    };

    Registry.prototype.restore = function (path) {
        this.registry.restoreVersion(path);
    };

    Registry.prototype.get = function (path) {
        if (!this.exists(path)) {
            return null;
        }
        var res = this.registry.get(path);
        return resource(this, res);
    };

    Registry.prototype.exists = function (path) {
        return this.registry.resourceExists(path);
    };

    Registry.prototype.content = function (path, paging) {
        if (!this.exists(path)) {
            return null;
        }
        var resource = this.registry.get(path);
        paging = merge({
            start: 0,
            count: 10,
            sort: 'recent'
        }, paging);
        return content(this, resource, paging);
    };

    Registry.prototype.tags = function (path) {
        var tag, tags, i, length, count, tz,
            tagz = [];
        if (path) {
            tags = this.registry.getTags(path);
            length = tags.length;
            for (i = 0; i < length; i++) {
                tagz.push(String(tags[i].tagName));
            }
            return tagz;
        }

        tz = {};
        tags = this.query({
            name: 'tags',
            query: 'SELECT RT.REG_TAG_ID FROM REG_RESOURCE_TAG RT ORDER BY RT.REG_TAG_ID',
            resultType: 'Tags'
        });
        length = tags.length;
        for (i = 0; i < length; i++) {
            tag = tags[i].split(';')[1].split(':')[1];
            count = tz[tag];
            count = count ? count + 1 : 1;
            tz[tag] = count;
        }
        for (tag in tz) {
            if (tz.hasOwnProperty(tag)) {
                tagz.push({
                    name: String(tag),
                    count: tz[tag]
                });
            }
        }
        return tagz;
    };

    Registry.prototype.tag = function (path, tags) {
        var i, length;
        tags = tags instanceof Array ? tags : [tags];
        length = tags.length;
        for (i = 0; i < length; i++) {
            this.registry.applyTag(path, tags[i]);
        }
    };

    Registry.prototype.untag = function (path, tags) {
        var i, length;
        tags = tags instanceof Array ? tags : [tags];
        length = tags.length;
        for (i = 0; i < length; i++) {
            this.registry.removeTag(path, tags[i]);
        }
    };

    Registry.prototype.associate = function (src, dest, type) {
        this.registry.addAssociation(src, dest, type);
    };

    Registry.prototype.dissociate = function (src, dest, type) {
        this.registry.removeAssociation(src, dest, type);
    };

    Registry.prototype.associations = function (path, type) {
        var i, asso,
            assos = type ? this.registry.getAssociations(path, type) : this.registry.getAllAssociations(path),
            length = assos.length(),
            associations = [];
        for (i = 0; i < length; i++) {
            asso = assos[i];
            associations.push({
                type: String(asso.associationType),
                src: String(asso.sourcePath),
                dest: String(asso.destinationPath)
            });
        }
        return associations;
    };

    Registry.prototype.addProperty = function (path, name, value) {
        var resource = this.registry.get(path);
        resource.addProperty(name, value);
    };

    Registry.prototype.removeProperty = function (path, name, value) {
        var resource = this.registry.get(path);
        (value ? resource.removePropertyValue(name, value) : resource.removeProperty(name));
    };

    Registry.prototype.properties = function (path) {
        var resource = this.registry.get(path);
        return properties(resource);
    };

    Registry.prototype.version = function (path) {
        this.registry.createVersion(path);
    };

    Registry.prototype.versions = function (path) {
        return this.registry.getVersions(path);
    };

    Registry.prototype.unversion = function (path, snapshot) {
        this.registry.removeVersionHistory(path, snapshot);
    };

    Registry.prototype.comment = function (path, comment) {
        this.registry.addComment(path, new Comment(comment));
    };

    /*    Registry.prototype.comments = function (path, paging) {
     var i, comment, length,
     comments = this.registry.getComments(path),
     commentz = [];
     paging = paging || { start: 0, count: 10 };
     length = paging.start + paging.count;
     length = length > comments.length ? comments.length : length;
     for (i = paging.start; i < length; i++) {
     comment = comments[i];
     commentz.push({
     content: comment.getText(),
     created: {
     author: comment.getUser(),
     time: comment.getCreatedTime().getTime()
     },
     path: comment.getCommentPath()
     });
     }
     return commentz;
     };*/

    Registry.prototype.comments = function (path, paging) {
        var o, ids, i, length,
            comments = [],
            resource = this.registry.get(path);
        paging = merge({
            start: 0,
            count: 25,
            sort: 'recent'
        }, paging);

        comments = this.registry.getComments(path);

        o = commentsQuery(this, resource, paging);
        ids = this.query({
            query: o.query,
            resultType: 'Comments'
        });
        length = ids.length;
        for (i = 0; i < length; i++) {
            comments.push(this.get(ids[i]));
        }
        //we have to manually sort this due to the bug in registry.getChildren() (#1 above)
        comments.sort(o.sorter);
        return o.paged ? comments : comments.slice(paging.start, paging.start + paging.count);
    };

    var sort = function(resources) {
        var i = 0,
            length = resources.length;
        for(i = 0; i < length; i++) {

        }
    };

    Registry.prototype.uncomment = function (path) {
        this.registry.removeComment(path);
    };

    Registry.prototype.rate = function (path, rating) {
        this.registry.rateResource(path, rating);
    };

    Registry.prototype.unrate = function (path) {
        this.registry.rateResource(path, 0);
    };

    Registry.prototype.rating = function (path, username) {
        var rating = {
            average: this.registry.getAverageRating(path)
        };
        if (username) {
            rating.user = this.registry.getRating(path, username);
        }
        return rating;
    };

    Registry.prototype.link = function (path, target) {
        return this.registry.createLink(path, target);
    };

    Registry.prototype.unlink = function (path) {
        return this.registry.removeLink(path);
    };

    Registry.prototype.search = function (query, paging) {
        var res = this.registry.searchContent(query);
        paging = merge({
            start: 0,
            count: 10,
            sort: 'recent'
        }, paging);
        return res ? content(this, res, paging) : [];
    };

    Registry.prototype.query = function (options) {
        var res,
            query = options.query,
            uuid = require('uuid'),
            name = options.name || uuid.generate(),
            cache = options.cache || true,
            Collections = java.util.Collections,
            path = '/_system/config/repository/components/org.wso2.carbon.registry/queries/' + name;
        if (!this.exists(path) || !cache) {
            this.put(path, {
                content: query,
                mediaType: 'application/vnd.sql.query',
                properties: {
                    resultType: options.resultType
                }
            });
        }
        res = this.registry.executeQuery(path, Collections.emptyMap());
        if (!cache) {
            this.remove(path);
        }
        return res.getChildren();
    };

}(server, registry));<commit_msg>refactoring paging logic of carbon.registry.Registry<commit_after>var registry = registry || {};

(function (server, registry) {
    var log = new Log();

    var Resource = Packages.org.wso2.carbon.registry.core.Resource;

    var Collection = Packages.org.wso2.carbon.registry.core.Collection;

    var Comment = Packages.org.wso2.carbon.registry.core.Comment;

    var StaticConfiguration = Packages.org.wso2.carbon.registry.core.config.StaticConfiguration;

    var content = function (registry, resource, paging) {
        if (resource instanceof Collection) {
            // #1 : this always sort children by name, so sorting cannot be done for the chunk
            return function (pagination) {
                pagination = pagination || paging;
                return children(registry, resource, pagination);
            };
        }
        if (resource instanceof Comment) {
            return String(resource.getText());
        }
        var stream = resource.getContentStream();
        if (stream) {
            return new Stream(stream);
        }
        return String(resource.content);
    };

    var resourceSorter = function (key) {
        var nameAsc = function (l, r) {
            var lname, rname;
            if (l instanceof Collection) {
                lname = l.getName();
                lname = lname.substring(lname.lastIndexOf('/') + 1);
            } else {
                lname = l.name;
            }
            if (r instanceof Collection) {
                rname = r.getName();
                rname = rname.substring(rname.lastIndexOf('/') + 1);
            } else {
                rname = r.name;
            }
            return lname === rname ? 0 : (lname > rname ? 1 : -1);
        };
        switch (key) {
            case 'time-created-asc' :
                return function (l, r) {
                    return l.getCreatedTime().getTime() - r.getCreatedTime().getTime();
                };
            case 'time-created-des' :
                return function (l, r) {
                    return r.getCreatedTime().getTime() - l.getCreatedTime().getTime();
                };
            case 'name-asc' :
                return nameAsc;
            case 'name-des' :
                return function (l, r) {
                    return -nameAsc(l, r);
                };
            default:
                return resourceSorter('time-created-des');
        }
    };

    var children = function (registry, resource, paging) {
        var length, i, resources,
            paths = [];
        resources = registry.content(resource.path);
        //we have to manually sort this due to the bug in registry.getChildren() (#1 above)
        resources.sort(resourceSorter(paging.sort));
        resources = resources.slice(paging.start, paging.start + paging.count);
        length = resource.length;
        for (i = 0; i < length; i++) {
            paths.push(resources[i].path);
        }
        return paths;
    };

    var resource = function (registry, resource) {
        var path = String(resource.path),
            o = {
                created: {
                    author: String(resource.authorUserName),
                    time: resource.createdTime.time
                },
                content: content(registry, resource, {
                    start: 0,
                    count: 10
                }),
                id: String(resource.id),
                version: resource.versionNumber
            };
        if (resource instanceof Comment) {
            return o;
        }
        if (resource instanceof Collection) {
            o.collection = (resource instanceof Collection);
        }
        o.uuid = String(resource.UUID);
        o.path = String(path);
        o.name = String(resource.name) || resolveName(path);
        o.description = String(resource.description);
        o.updated = {
            author: String(resource.lastUpdaterUserName),
            time: resource.lastModified.time
        };
        o.mediaType = String(resource.mediaType);
        o.properties = function () {
            return properties(resource);
        };
        o.aspects = function () {
            return aspects(resource);
        };
        return o;
    };

    var properties = function (resource) {
        var prop,
            properties = resource.properties,
            props = properties.keySet().toArray(),
            length = props.length,
            o = {};
        for (var i = 0; i < length; i++) {
            prop = props[i];
            o[prop] = resource.getPropertyValues(prop).toArray();
        }
        return o;
    };

    var aspects = function (resource) {
        var aspects = resource.getAspects();
        return aspects ? aspects.toArray() : [];
    };

    var resolveName = function (path) {
        path = path.charAt(path.length - 1) === '/' ? path.substring(0, path.length - 1) : path;
        return path.substring(path.lastIndexOf('/') + 1);
    };

    var merge = function (def, options) {
        if (options) {
            for (var op in def) {
                if (def.hasOwnProperty(op)) {
                    def[op] = options[op] || def[op];
                }
            }
        }
        return def;
    };

    var Registry = function (serv, auth) {
        var registryService = server.osgiService('org.wso2.carbon.registry.core.service.RegistryService');
        if (auth.username) {
            this.tenant = server.tenantId({
                domain: auth.domain,
                username: auth.username
            });
            this.registry = registryService.getRegistry(auth.username, auth.password, this.tenant);
            this.username = auth.username;
            this.versioning = {
                comments: StaticConfiguration.isVersioningComments()
            };
            var db = this.registry.getRegistryContext().getDataAccessManager().getDataSource()
                .getConnection().getMetaData();
            this.database = {
                name: String(db.getDatabaseProductName()),
                version: {
                    major: db.getDatabaseMajorVersion(),
                    minor: db.getDatabaseMinorVersion()
                }
            };
        } else {
            throw new Error('Unsupported authentication mechanism : ' + stringify(auth.username));
        }
        this.server = serv;
    };

    registry.Registry = Registry;

    Registry.prototype.put = function (path, resource) {
        var res;
        if (resource.collection) {
            res = this.registry.newCollection();
        } else {
            res = this.registry.newResource();
            res.content = resource.content || null;
            res.mediaType = resource.mediaType || null;
        }
        res.name = resource.name;
        res.description = resource.description || null;
        res.UUID = resource.uuid || null;

        var values, length, i, ArrayList,
            properties = resource.properties;
        if (properties) {
            ArrayList = java.util.ArrayList;
            for (var name in properties) {
                var list = new ArrayList();
                if (properties.hasOwnProperty(name)) {
                    values = properties[name];
                    values = values instanceof Array ? values : [values];
                    length = values.length;
                    for (i = 0; i < length; i++) {
                        list.add(values[i]);
                    }
                    res.setProperty(name, list);
                }
            }
        }

        var aspects = resource.aspects;
        if (aspects) {
            length = aspects.length;
            for (i = 0; i < length; i++) {
                res.addAspect(aspects[i]);
            }
        }

        this.registry.put(path, res);
    };

    Registry.prototype.remove = function (path) {
        this.registry.delete(path);
    };

    Registry.prototype.move = function (src, dest) {
        this.registry.move(src, dest);
    };

    Registry.prototype.rename = function (current, newer) {
        this.registry.rename(current, newer);
    };

    Registry.prototype.copy = function (src, dest) {
        this.registry.rename(src, dest);
    };

    Registry.prototype.restore = function (path) {
        this.registry.restoreVersion(path);
    };

    Registry.prototype.get = function (path) {
        if (!this.exists(path)) {
            return null;
        }
        var res = this.registry.get(path);
        return resource(this, res);
    };

    Registry.prototype.exists = function (path) {
        return this.registry.resourceExists(path);
    };

    Registry.prototype.content = function (path, paging) {
        if (!this.exists(path)) {
            return null;
        }
        var resource = this.registry.get(path);
        paging = merge({
            start: 0,
            count: 10,
            sort: 'recent'
        }, paging);
        return content(this, resource, paging);
    };

    Registry.prototype.tags = function (path) {
        var tag, tags, i, length, count, tz,
            tagz = [];
        if (path) {
            tags = this.registry.getTags(path);
            length = tags.length;
            for (i = 0; i < length; i++) {
                tagz.push(String(tags[i].tagName));
            }
            return tagz;
        }

        tz = {};
        tags = this.query({
            name: 'tags',
            query: 'SELECT RT.REG_TAG_ID FROM REG_RESOURCE_TAG RT ORDER BY RT.REG_TAG_ID',
            resultType: 'Tags'
        });
        length = tags.length;
        for (i = 0; i < length; i++) {
            tag = tags[i].split(';')[1].split(':')[1];
            count = tz[tag];
            count = count ? count + 1 : 1;
            tz[tag] = count;
        }
        for (tag in tz) {
            if (tz.hasOwnProperty(tag)) {
                tagz.push({
                    name: String(tag),
                    count: tz[tag]
                });
            }
        }
        return tagz;
    };

    Registry.prototype.tag = function (path, tags) {
        var i, length;
        tags = tags instanceof Array ? tags : [tags];
        length = tags.length;
        for (i = 0; i < length; i++) {
            this.registry.applyTag(path, tags[i]);
        }
    };

    Registry.prototype.untag = function (path, tags) {
        var i, length;
        tags = tags instanceof Array ? tags : [tags];
        length = tags.length;
        for (i = 0; i < length; i++) {
            this.registry.removeTag(path, tags[i]);
        }
    };

    Registry.prototype.associate = function (src, dest, type) {
        this.registry.addAssociation(src, dest, type);
    };

    Registry.prototype.dissociate = function (src, dest, type) {
        this.registry.removeAssociation(src, dest, type);
    };

    Registry.prototype.associations = function (path, type) {
        var i, asso,
            assos = type ? this.registry.getAssociations(path, type) : this.registry.getAllAssociations(path),
            length = assos.length(),
            associations = [];
        for (i = 0; i < length; i++) {
            asso = assos[i];
            associations.push({
                type: String(asso.associationType),
                src: String(asso.sourcePath),
                dest: String(asso.destinationPath)
            });
        }
        return associations;
    };

    Registry.prototype.addProperty = function (path, name, value) {
        var resource = this.registry.get(path);
        resource.addProperty(name, value);
    };

    Registry.prototype.removeProperty = function (path, name, value) {
        var resource = this.registry.get(path);
        (value ? resource.removePropertyValue(name, value) : resource.removeProperty(name));
    };

    Registry.prototype.properties = function (path) {
        var resource = this.registry.get(path);
        return properties(resource);
    };

    Registry.prototype.version = function (path) {
        this.registry.createVersion(path);
    };

    Registry.prototype.versions = function (path) {
        return this.registry.getVersions(path);
    };

    Registry.prototype.unversion = function (path, snapshot) {
        this.registry.removeVersionHistory(path, snapshot);
    };

    Registry.prototype.comment = function (path, comment) {
        this.registry.addComment(path, new Comment(comment));
    };

    Registry.prototype.comments = function (path, paging) {
        var i, length, comments, comment, key,
            commentz = [];
        paging = merge({
            start: 0,
            count: 25,
            sort: 'recent'
        }, paging);

        comments = this.registry.getComments(path);
        //we have to manually sort this due to the bug in registry.getChildren() (#1 above)
        key = paging.sort;
        key = (key === 'time-created-des' || key === 'time-created-asc') ? key : 'time-created-des';
        comments = comments.sort(resourceSorter(key));
        comments = comments.slice(paging.start, paging.start + paging.count);
        length = comments.length;
        for (i = 0; i < length; i++) {
            comment = comments[i];
            commentz.push({
                content: comment.getText(),
                created: {
                    author: comment.getUser(),
                    time: comment.getCreatedTime().getTime()
                },
                path: comment.getCommentPath()
            });
        }
        return commentz;
    };

    Registry.prototype.uncomment = function (path) {
        this.registry.removeComment(path);
    };

    Registry.prototype.rate = function (path, rating) {
        this.registry.rateResource(path, rating);
    };

    Registry.prototype.unrate = function (path) {
        this.registry.rateResource(path, 0);
    };

    Registry.prototype.rating = function (path, username) {
        var rating = {
            average: this.registry.getAverageRating(path)
        };
        if (username) {
            rating.user = this.registry.getRating(path, username);
        }
        return rating;
    };

    Registry.prototype.link = function (path, target) {
        return this.registry.createLink(path, target);
    };

    Registry.prototype.unlink = function (path) {
        return this.registry.removeLink(path);
    };

    Registry.prototype.search = function (query, paging) {
        var res = this.registry.searchContent(query);
        paging = merge({
            start: 0,
            count: 10,
            sort: 'recent'
        }, paging);
        return res ? content(this, res, paging) : [];
    };

    Registry.prototype.query = function (options) {
        var res,
            query = options.query,
            uuid = require('uuid'),
            name = options.name || uuid.generate(),
            cache = options.cache || true,
            Collections = java.util.Collections,
            path = '/_system/config/repository/components/org.wso2.carbon.registry/queries/' + name;
        if (!this.exists(path) || !cache) {
            this.put(path, {
                content: query,
                mediaType: 'application/vnd.sql.query',
                properties: {
                    resultType: options.resultType
                }
            });
        }
        res = this.registry.executeQuery(path, Collections.emptyMap());
        if (!cache) {
            this.remove(path);
        }
        return res.getChildren();
    };

}(server, registry));<|endoftext|>


<commit_before>import React from 'react'
import {CSSTransition, TransitionGroup} from 'react-transition-group'
import PropTypes from 'prop-types'
import styles from './animate.module.css'

export class AnimateEnter extends React.Component {
    render() {
        const name = this.props.name in styles ? styles[this.props.name] : this.props.name
        const duration = this.props.duration || 1000
        const delay = this.props.delay || 0
        const timeout = duration + delay
        const className = `animation_${name}_${randomString()}`
        return (

                <CSSTransition
                    in={true}
                    appear={true}
                    exit={false}
                    timeout={timeout}
                    classNames={className}>
                    {this.props.children}
                </CSSTransition>

        )
    }

    static fadeInUp = 'fadeInUp'
    static fadeInDown = 'fadeInDown'
    static fadeInLeft = 'fadeInLeft'
    static fadeInRight = 'fadeInRight'
}

AnimateEnter.propTypes = {
    name: PropTypes.string.isRequired,
    duration: PropTypes.number,
    delay: PropTypes.number,
}

export const AnimateReplacement = ({currentKey, timeout = 500, classNames, children, ...props}) =>
    <TransitionGroup {...props}>
        <CSSTransition
            key={currentKey}
            timeout={timeout}
            classNames={classNames}
            {...props}>
            {children}
        </CSSTransition>
    </TransitionGroup>

AnimateReplacement.propTypes = {
    currentKey: PropTypes.any.isRequired,
    timeout: PropTypes.number,
    classNames: PropTypes.any.isRequired
}

function randomString() {
    return Math.random().toString(36).substring(2, 15)
        + Math.random().toString(36).substring(2, 15)
}<commit_msg>Minor refactoring<commit_after>import React from 'react'
import {CSSTransition, TransitionGroup} from 'react-transition-group'
import PropTypes from 'prop-types'
import styles from './animate.module.css'

export class AnimateEnter extends React.Component {
    render() {
        const name = this.props.name in styles ? styles[this.props.name] : this.props.name
        const duration = this.props.duration || 1000
        const delay = this.props.delay || 0
        const timeout = duration + delay
        const className = `animation_${name}_${randomString()}`
        return (

                <CSSTransition
                    in={true}
                    appear={true}
                    exit={false}
                    timeout={timeout}
                    classNames={className}>
                    {this.props.children}
                </CSSTransition>

        )
    }

    static fadeInUp = 'fadeInUp'
    static fadeInDown = 'fadeInDown'
    static fadeInLeft = 'fadeInLeft'
    static fadeInRight = 'fadeInRight'
}

AnimateEnter.propTypes = {
    name: PropTypes.string.isRequired,
    duration: PropTypes.number,
    delay: PropTypes.number,
}

export const AnimateReplacement = ({currentKey, timeout = 500, classNames, children, ...props}) =>
    <TransitionGroup {...props}>
        <CSSTransition
            key={currentKey}
            timeout={timeout}
            classNames={classNames}
            {...props}>
            {children}
        </CSSTransition>
    </TransitionGroup>

AnimateReplacement.propTypes = {
    currentKey: PropTypes.any.isRequired,
    timeout: PropTypes.number,
    classNames: PropTypes.any.isRequired
}

function randomString() {
    return Math.random().toString(36).substring(2, 15)
        + Math.random().toString(36).substring(2, 15)
}<|endoftext|>


<commit_before>define([
    'jquery',
    '/api/config',
    '/common/hyperscript.js',
    '/common/common-feedback.js',
    '/common/common-interface.js',
    '/common/common-hash.js',
    '/common/textFit.min.js',
    '/customize/messages.js',
    '/customize/application_config.js',
    '/common/outer/local-store.js',
    '/customize/pages.js'
], function ($, Config, h, Feedback, UI, Hash, TextFit, Msg, AppConfig, LocalStore, Pages) {
    var urlArgs = Config.requireConf.urlArgs;

    var isAvailableType = function (x) {
        if (!Array.isArray(AppConfig.availablePadTypes)) { return true; }
        return AppConfig.availablePadTypes.indexOf(x) !== -1;
    };

    var checkRegisteredType = function (x) {
        // Return true if we're registered or if the app is not registeredOnly
        if (LocalStore.isLoggedIn()) { return true; }
        if (!Array.isArray(AppConfig.registeredOnlyTypes)) { return true; }
        return AppConfig.registeredOnlyTypes.indexOf(x) === -1;
    };

    return function () {
        var icons = [
                [ 'pad', Msg.type.pad],
                [ 'code', Msg.type.code],
                [ 'slide', Msg.type.slide],
                [ 'sheet', Msg.type.sheet],
                [ 'poll', Msg.type.poll],
                [ 'kanban', Msg.type.kanban],
                [ 'whiteboard', Msg.type.whiteboard],
                [ 'drive', Msg.type.drive]
            ].filter(function (x) {
                return isAvailableType(x[0]);
            })
            .map(function (x) {
                var s = 'div.bs-callout.cp-callout-' + x[0];
                var isEnabled = checkRegisteredType(x[0]);
                //if (i > 2) { s += '.cp-more.cp-hidden'; }
                var icon = AppConfig.applicationsIcon[x[0]];
                var font = icon.indexOf('cptools') === 0 ? 'cptools' : 'fa';
                var href = '/'+ x[0] +'/';
                var attr = isEnabled ? { href: href } : {
                    onclick: function () {
                        var loginURL = Hash.hashToHref('', 'login');
                        var url = Hash.getNewPadURL(loginURL, { href: href });
                        window.location.href = url;
                    }
                };
                if (!isEnabled) {
                    s += '.cp-app-disabled';
                    attr.title = Msg.mustLogin;
                }
                return h('a', [
                    attr,
                    h(s, [
                        h('i.' + font + '.' + icon, {'aria-hidden': 'true'}),
                        h('div.pad-button-text', [ x[1] ])
                    ])
                ]);
            });

        icons.forEach(function (a) {
            setTimeout(function () {
                TextFit($(a).find('.pad-button-text')[0], {minFontSize: 13, maxFontSize: 18});
            });
        });
        UI.addTooltips();

        var blocks = [
            h('div.row.cp-page-section', [
                h('div.col-sm-6',
                    h('img.img-fluid.cp-img-invert', {
                        src:'/customize/images/shredder.png',
                        alt:'',
                        'aria-hidden': 'true'
                    })
                ),
                h('div.col-sm-6', [
                    h('h2', Msg.home_privacy_title),
                    h('p', Msg.home_privacy_text)
                ])
            ]),
            h('div.row.cp-page-section',
                h('div.col-sm-12', [
                    h('h2', Msg.home_host_title),
                    h('p'), Msg.home_host
                ])
            ),
            h('div.row.cp-page-section', [
                h('div.col-sm-6', [
                    h('h2', Msg.home_opensource_title),
                    Pages.setHTML(h('p'), Msg.home_opensource),
                    h('img.small-logo.cp-img-invert', {
                        src: '/customize/images/logo_AGPLv3.svg',
                        alt: 'APGL3 License Logo'
                    })
                ]),
                h('div.col-sm-6', [
                    h('h2', Msg.home_support_title),
                    Pages.setHTML(h('span'), Msg.home_support),
                    Pages.crowdfundingButton(function () {
                        Feedback.send('HOME_SUPPORT_CRYPTPAD');
                    }),
                ])
            ])
        ];

        return [
            h('div#cp-main', [
                Pages.infopageTopbar(),
                h('div.container.cp-container', [
                    h('div.row.cp-home-hero', [
                        h('div.cp-title.col-md-7', [
                            h('img', {
                                src: '/customize/CryptPad_logo.svg?' + urlArgs,
                                'aria-hidden': 'true',
                                alt: ''
                            }),
                            h('h1', 'CryptPad'),
                            UI.setHTML(h('span.tag-line'), Msg.main_catch_phrase)
                        ]),
                        h('div.col-md-5.cp-app-grid', [
                            icons,
                        ])
                    ]),
                    blocks
                ]),
                Pages.infopageFooter(),
            ]),
        ];
    };
});

<commit_msg>Add a subscribe button to the home page if supported<commit_after>define([
    'jquery',
    '/api/config',
    '/common/hyperscript.js',
    '/common/common-feedback.js',
    '/common/common-interface.js',
    '/common/common-hash.js',
    '/common/textFit.min.js',
    '/customize/messages.js',
    '/customize/application_config.js',
    '/common/outer/local-store.js',
    '/customize/pages.js'
], function ($, Config, h, Feedback, UI, Hash, TextFit, Msg, AppConfig, LocalStore, Pages) {
    var urlArgs = Config.requireConf.urlArgs;

    var isAvailableType = function (x) {
        if (!Array.isArray(AppConfig.availablePadTypes)) { return true; }
        return AppConfig.availablePadTypes.indexOf(x) !== -1;
    };

    var checkRegisteredType = function (x) {
        // Return true if we're registered or if the app is not registeredOnly
        if (LocalStore.isLoggedIn()) { return true; }
        if (!Array.isArray(AppConfig.registeredOnlyTypes)) { return true; }
        return AppConfig.registeredOnlyTypes.indexOf(x) === -1;
    };

    return function () {
        var icons = [
                [ 'pad', Msg.type.pad],
                [ 'code', Msg.type.code],
                [ 'slide', Msg.type.slide],
                [ 'sheet', Msg.type.sheet],
                [ 'poll', Msg.type.poll],
                [ 'kanban', Msg.type.kanban],
                [ 'whiteboard', Msg.type.whiteboard],
                [ 'drive', Msg.type.drive]
            ].filter(function (x) {
                return isAvailableType(x[0]);
            })
            .map(function (x) {
                var s = 'div.bs-callout.cp-callout-' + x[0];
                var isEnabled = checkRegisteredType(x[0]);
                //if (i > 2) { s += '.cp-more.cp-hidden'; }
                var icon = AppConfig.applicationsIcon[x[0]];
                var font = icon.indexOf('cptools') === 0 ? 'cptools' : 'fa';
                var href = '/'+ x[0] +'/';
                var attr = isEnabled ? { href: href } : {
                    onclick: function () {
                        var loginURL = Hash.hashToHref('', 'login');
                        var url = Hash.getNewPadURL(loginURL, { href: href });
                        window.location.href = url;
                    }
                };
                if (!isEnabled) {
                    s += '.cp-app-disabled';
                    attr.title = Msg.mustLogin;
                }
                return h('a', [
                    attr,
                    h(s, [
                        h('i.' + font + '.' + icon, {'aria-hidden': 'true'}),
                        h('div.pad-button-text', [ x[1] ])
                    ])
                ]);
            });

        icons.forEach(function (a) {
            setTimeout(function () {
                TextFit($(a).find('.pad-button-text')[0], {minFontSize: 13, maxFontSize: 18});
            });
        });
        UI.addTooltips();

        var subscribeButton;
        /* Display a subscribe button if they are enabled and the button's translation key exists */
        if (Config.allowSubscriptions && Msg.subscribe_button) {
            subscribeButton = Pages.subscribeButton(function () {
                Feedback.send('HOME_SUBSCRIBE_CRYPTPAD');
            });
        }

        var blocks = [
            h('div.row.cp-page-section', [
                h('div.col-sm-6',
                    h('img.img-fluid.cp-img-invert', {
                        src:'/customize/images/shredder.png',
                        alt:'',
                        'aria-hidden': 'true'
                    })
                ),
                h('div.col-sm-6', [
                    h('h2', Msg.home_privacy_title),
                    h('p', Msg.home_privacy_text)
                ])
            ]),
            h('div.row.cp-page-section',
                h('div.col-sm-12', [
                    h('h2', Msg.home_host_title),
                    h('p'), Msg.home_host
                ])
            ),
            h('div.row.cp-page-section', [
                h('div.col-sm-6', [
                    h('h2', Msg.home_opensource_title),
                    Pages.setHTML(h('p'), Msg.home_opensource),
                    h('img.small-logo.cp-img-invert', {
                        src: '/customize/images/logo_AGPLv3.svg',
                        alt: 'APGL3 License Logo'
                    })
                ]),
                h('div.col-sm-6', [
                    h('h2', Msg.home_support_title),
                    Pages.setHTML(h('span'), Msg.home_support),
                    subscribeButton,
                    Pages.crowdfundingButton(function () {
                        Feedback.send('HOME_SUPPORT_CRYPTPAD');
                    }),
                ])
            ])
        ];

        return [
            h('div#cp-main', [
                Pages.infopageTopbar(),
                h('div.container.cp-container', [
                    h('div.row.cp-home-hero', [
                        h('div.cp-title.col-md-7', [
                            h('img', {
                                src: '/customize/CryptPad_logo.svg?' + urlArgs,
                                'aria-hidden': 'true',
                                alt: ''
                            }),
                            h('h1', 'CryptPad'),
                            UI.setHTML(h('span.tag-line'), Msg.main_catch_phrase)
                        ]),
                        h('div.col-md-5.cp-app-grid', [
                            icons,
                        ])
                    ]),
                    blocks
                ]),
                Pages.infopageFooter(),
            ]),
        ];
    };
});

<|endoftext|>


<commit_before>
// The textbook is stored in brackets.currentTextbook

function newTextbook() {
	var newTextbook 		= {};
	newTextbook.title 		= "Title";
	newTextbook.author 		= "Author";
	newTextbook.elements 	= [];
	return newTextbook;
}

function addPDFRectangleClip(source,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addPDFHorizontalClip(source,startY,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfHorizontal";
	newElement.source 	= source;
	newElement.startY 	= startY;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addYouTubeVid(source,startTime) {
	var newElement 		= {};
	newElement.type 	= "youtube";
	newElement.source 	= source;
	newElement.startTime 	= startTime;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addText(text) {
	var newElement 		= {};
	newElement.type 	= "text";
	newElement.text 	= text;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addWiki(source) {
	var newElement 		= {};
	newElement.type 	= "wiki";
	newElement.source 	= source;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

// If within range, delete. Else skip
function deleteElement(clipNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (clipNumber >= 0 && clipNumber<numberOfElements) {
		var newElements = [];
		for (var el = 0; el < clipNumber; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		for (var el = clipNumber+1; el < numberOfElements; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		brackets.currentTextbook.elements = newElements;
	}
}

// Move element at index oldPosition in between element at index newPosition and the element at index (newPosition+1)
function moveElement(oldPosition,newPosition) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (oldPosition >= 0 && oldPosition<numberOfElements
		newPosition >= 0 && newPosition<numberOfElements) {
		// If no change then return
		if (oldPosition == newPosition) {return;}
		// Copy everything that's not going to be changed
		var newElements = [];
		var firstChange = Math.min(oldPosition,newPosition);
		for (var el = 0; el < firstChange; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		// If move up the page
		if (oldPosition > newPosition) {
			newElements.append(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition; el < oldPosition; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			for (var el = oldPosition+1; el < numberOfElements; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
		// If move down the page
		else {
			for (var el = oldPosition+1; el <= newPosition; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			newElements.append(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition+1; el < numberOfElements; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
	};
}

function addComment(elementNumber,comment,author) {
	brackets.currentTextbook.elements.comments.append({
		"author"  = author,
		"comment" = comment
	});
}

function deleteComment(elementNumber,commentNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		var numberOfComments = brackets.currentTextbook.elements[elementNumber].comments.length;
		if (commentNumber >= 0 && commentNumber<numberOfComments) {
			var newComments = [];
			for (var comm = 0; comm < commentNumber; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			for (var comm = commentNumber+1; comm < numberOfElements; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			brackets.currentTextbook.elements[elementNumber].comments = newComments;
		}
	}
}
<commit_msg>make addComment safe<commit_after>
// The textbook is stored in brackets.currentTextbook

function newTextbook() {
	var newTextbook 		= {};
	newTextbook.title 		= "Title";
	newTextbook.author 		= "Author";
	newTextbook.elements 	= [];
	return newTextbook;
}

function addPDFRectangleClip(source,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addPDFHorizontalClip(source,startY,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfHorizontal";
	newElement.source 	= source;
	newElement.startY 	= startY;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addYouTubeVid(source,startTime) {
	var newElement 		= {};
	newElement.type 	= "youtube";
	newElement.source 	= source;
	newElement.startTime 	= startTime;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addText(text) {
	var newElement 		= {};
	newElement.type 	= "text";
	newElement.text 	= text;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

function addWiki(source) {
	var newElement 		= {};
	newElement.type 	= "wiki";
	newElement.source 	= source;
	newElement.comments = [];
	brackets.currentTextbook.elements.add(newElement);
}

// If within range, delete. Else skip
function deleteElement(clipNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (clipNumber >= 0 && clipNumber<numberOfElements) {
		var newElements = [];
		for (var el = 0; el < clipNumber; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		for (var el = clipNumber+1; el < numberOfElements; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		brackets.currentTextbook.elements = newElements;
	}
}

// Move element at index oldPosition in between element at index newPosition and the element at index (newPosition+1)
function moveElement(oldPosition,newPosition) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (oldPosition >= 0 && oldPosition<numberOfElements
		newPosition >= 0 && newPosition<numberOfElements) {
		// If no change then return
		if (oldPosition == newPosition) {return;}
		// Copy everything that's not going to be changed
		var newElements = [];
		var firstChange = Math.min(oldPosition,newPosition);
		for (var el = 0; el < firstChange; el++) {
			newElements.append(brackets.currentTextbook.elements[el]);
		}
		// If move up the page
		if (oldPosition > newPosition) {
			newElements.append(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition; el < oldPosition; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			for (var el = oldPosition+1; el < numberOfElements; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
		// If move down the page
		else {
			for (var el = oldPosition+1; el <= newPosition; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			newElements.append(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition+1; el < numberOfElements; el++) {
				newElements.append(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
	};
}

function addComment(elementNumber,comment,author) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		brackets.currentTextbook.elements[elementNumber].comments.append({
			"author"  = author,
			"comment" = comment
		});
	}
}

function deleteComment(elementNumber,commentNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		var numberOfComments = brackets.currentTextbook.elements[elementNumber].comments.length;
		if (commentNumber >= 0 && commentNumber<numberOfComments) {
			var newComments = [];
			for (var comm = 0; comm < commentNumber; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			for (var comm = commentNumber+1; comm < numberOfElements; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			brackets.currentTextbook.elements[elementNumber].comments = newComments;
		}
	}
}
<|endoftext|>