<commit_before>const SelectMatcher    = require('@binary-com/binary-style').select2Matcher;
const moment           = require('moment');
const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const Header           = require('../../../../base/header');
const BinarySocket     = require('../../../../base/socket');
const FormManager      = require('../../../../common/form_manager');
const CommonFunctions  = require('../../../../../_common/common_functions');
const Geocoder         = require('../../../../../_common/geocoder');
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const getPropertyValue = require('../../../../../_common/utility').getPropertyValue;

const PersonalDetails = (() => {
    const form_id           = '#frmPersonalDetails';
    const real_acc_elements = '.RealAcc';

    let is_for_new_account = false;

    let editable_fields,
        is_virtual,
        residence,
        get_settings_data;

    const init = () => {
        editable_fields   = {};
        get_settings_data = {};
        is_virtual        = Client.get('is_virtual');
        residence         = Client.get('residence');
    };

    const showHideTaxMessage = () => {
        const $tax_info_declaration = $('#tax_information_declaration');
        const $tax_information_info = $('#tax_information_info');

        if (Client.shouldCompleteTax()) {
            $('#tax_information_note_toggle').off('click').on('click', (e) => {
                e.stopPropagation();
                $('#tax_information_note_toggle').toggleClass('open');
                $('#tax_information_note').slideToggle();
            });
        } else {
            $tax_information_info.setVisibility(0); // hide tax info
            $tax_info_declaration.setVisibility(0); // hide tax info declaration
        }
    };

    const showHideMissingDetails = () => {
        const validations = getValidations();
        const has_missing_field = validations.find((validation) => /req/.test(validation.validations) && $(validation.selector).val() === '');
        $('#missing_details_notice').setVisibility(!!has_missing_field);
    };

    const getDetailsResponse = (data, residence_list = State.getResponse('residence_list')) => {
        const get_settings         = $.extend({}, data);
        get_settings.date_of_birth = 'date_of_birth' in get_settings ? moment.utc(new Date(get_settings.date_of_birth * 1000)).format('YYYY-MM-DD') : '';
        const accounts             = Client.getAllLoginids();
        // for subaccounts, back-end sends loginid of the master account as name
        const hide_name            = accounts.some(loginid => new RegExp(loginid, 'i').test(get_settings.first_name)) || is_virtual;
        if (!hide_name) {
            get_settings.name = `${(get_settings.salutation || '')} ${(get_settings.first_name || '')} ${(get_settings.last_name || '')}`;
        }

        if (get_settings.place_of_birth) {
            get_settings.place_of_birth =
                (residence_list.find(obj => obj.value === get_settings.place_of_birth) || {}).text ||
                get_settings.place_of_birth;
        }

        if (get_settings.citizen) {
            get_settings.citizen =
                (residence_list.find(obj => obj.value === get_settings.citizen) || {}).text ||
                get_settings.citizen;
        }

        displayGetSettingsData(get_settings);

        if (is_virtual) {
            $(real_acc_elements).remove();
        } else {
            $(real_acc_elements).setVisibility(1);
            showHideTaxMessage();
        }
        $(form_id).setVisibility(1);
        $('#loading').remove();
        FormManager.init(form_id, getValidations());
        FormManager.handleSubmit({
            form_selector       : form_id,
            obj_request         : { set_settings: 1 },
            fnc_response_handler: setDetailsResponse,
            fnc_additional_check: additionalCheck,
            enable_button       : true,
        });
        if (!is_virtual) {
            Geocoder.validate(form_id);
        }
        showHideMissingDetails();
    };

    const show_label_if_any_value = ['account_opening_reason', 'citizen', 'place_of_birth'];

    const displayGetSettingsData = (get_settings, populate = true) => {
        let el_id,
            el_key,
            has_label,
            should_show_label,
            should_update_value;
        Object.keys(get_settings).forEach((key) => {
            has_label           = show_label_if_any_value.indexOf(key) !== -1;
            should_show_label   = has_label && get_settings[key];               // if we have a value for any of these fields, show them as label
            el_id               = `${should_show_label ? 'lbl_' : ''}${key}`;
            el_key              = CommonFunctions.getElementById(el_id);
            if (el_key) {
                editable_fields[key] = get_settings[key];
                if (populate) {
                    should_update_value = /select|text/i.test(el_key.type);
                    if (has_label) {
                        CommonFunctions.getElementById(`row_${el_id}`).setVisibility(1);
                    }
                    if (el_key.type === 'checkbox') {
                        el_key.checked = !!get_settings[key];
                    } else if (!should_update_value) { // for all non (checkbox|select|text) elements
                        const localized_text = (document.querySelector(`#${key} option[value="${get_settings[key]}"]`) || {}).innerText || get_settings[key];
                        CommonFunctions.elementInnerHtml(el_key, localized_text || '-');
                    }
                    if (should_update_value || should_show_label) {
                        // if should show label, set the value of the non-label so that it doesn't count as missing information
                        $(should_show_label ? `#${key}` : el_key)
                            .val(get_settings[key] ? get_settings[key].split(',') : '')
                            .trigger('change');
                    }
                }
            }
        });
        if (get_settings.country) {
            $('#residence').replaceWith($('<label/>').append($('<strong/>', { id: 'country' })));
            $('#country').text(get_settings.country);
        }
    };

    const additionalCheck = (data) => {
        if (!isChanged(data)) {
            showFormMessage(localize('You did not change anything.'), false);
            return false;
        }
        return true;
    };

    const isChanged = (data) => {
        const compare_data = $.extend({}, data);
        return Object.keys(compare_data).some(key => (
            key !== 'set_settings' && editable_fields[key] !== compare_data[key]
        ));
    };

    const getValidations = () => {
        let validations;
        if (is_virtual) {
            validations = [
                { selector: '#email_consent' },
                { selector: '#residence', validations: ['req'] },
            ];
        } else {
            const is_financial      = Client.isAccountOfType('financial');
            const is_gaming         = Client.isAccountOfType('gaming');
            const mt_acct_type      = localStorage.getItem('personal_details_redirect');
            const is_for_mt_citizen = !!mt_acct_type;                                                   // all mt account opening requires citizen
            const is_for_mt_tax     = /real/.test(mt_acct_type) && mt_acct_type.split('_').length > 2;  // demo and volatility mt accounts do not require tax info
            const is_tax_req        = is_financial || (is_for_mt_tax && +State.getResponse('landing_company.config.tax_details_required') === 1);

            validations = [
                { selector: '#address_line_1',         validations: ['req', 'address'] },
                { selector: '#address_line_2',         validations: ['address'] },
                { selector: '#address_city',           validations: ['req', 'letter_symbol'] },
                { selector: '#address_state',          validations: $('#address_state').prop('nodeName') === 'SELECT' ? '' : ['letter_symbol'] },
                { selector: '#address_postcode',       validations: [Client.get('residence') === 'gb' ? 'req' : '', 'postcode', ['length', { min: 0, max: 20 }]] },
                { selector: '#email_consent' },
                { selector: '#phone',                  validations: ['req', 'phone', ['length', { min: 6, max: 35, value: () => $('#phone').val().replace(/^\+/, '')  }]] },
                { selector: '#place_of_birth',         validations: ['req'] },
                { selector: '#account_opening_reason', validations: ['req'] },

                { selector: '#tax_residence',  validations: (is_tax_req) ? ['req'] : '' },
                { selector: '#citizen',        validations: (is_financial || is_gaming || is_for_mt_citizen) ? ['req'] : '' },
                { selector: '#chk_tax_id',     validations: is_financial ? [['req', { hide_asterisk: true, message: localize('Please confirm that all the information above is true and complete.') }]] : '', exclude_request: 1 },
            ];

            const tax_id_validation  = { selector: '#tax_identification_number', validations: ['tax_id', ['length', { min: 0, max: 20 }]] };
            if (is_tax_req) {
                tax_id_validation.validations[1][1].min = 1;
                tax_id_validation.validations.unshift('req');
            }
            validations.push(tax_id_validation);
        }
        return validations;
    };

    const setDetailsResponse = (response) => {
        // allow user to resubmit the form on error.
        const is_error = response.set_settings !== 1;
        if (!is_error) {
            const redirect_url = localStorage.getItem('personal_details_redirect');
            // to update tax information message for financial clients
            BinarySocket.send({ get_account_status: 1 }, { forced: true }).then((response_status) => {
                showHideTaxMessage();
                Header.displayAccountStatus();
                if (redirect_url && +response_status.get_account_status.prompt_client_to_authenticate && Client.isAccountOfType('financial')) {
                    $('#msg_authenticate').setVisibility(1);
                }
            });
            // to update the State with latest get_settings data
            BinarySocket.send({ get_settings: 1 }, { forced: true }).then((data) => {
                if (is_virtual && response.echo_req.residence) {
                    window.location.reload(); // reload page if we are setting residence
                    return;
                }
                // update notification shown for set residence etc
                Header.displayAccountStatus();
                if (is_for_new_account) {
                    is_for_new_account = false;
                    BinaryPjax.loadPreviousUrl();
                    return;
                }
                const get_settings    = data.get_settings;
                const has_required_mt = (/real_vanuatu_(standard|advanced)/.test(redirect_url) ?
                    (get_settings.tax_residence && get_settings.tax_identification_number && get_settings.citizen)
                    :
                    get_settings.citizen // only check Citizen if user selects mt volatility account
                );
                if (redirect_url && has_required_mt) {
                    localStorage.removeItem('personal_details_redirect');
                    $.scrollTo($('h1#heading'), 500, { offset: -10 });
                    $(form_id).setVisibility(0);
                    $('#missing_details_notice').setVisibility(0);
                    $('.rowCustomerSupport').setVisibility(0);
                    $('#msg_main').setVisibility(1);
                    return;
                }
                getDetailsResponse(get_settings);
            });
        }
        showFormMessage(is_error ?
            (getPropertyValue(response, ['error', 'message']) || localize('Sorry, an error occurred while processing your account.')) :
            localize('Your settings have been updated successfully.'), !is_error);
    };

    const showFormMessage = (localized_text, is_success) => {
        const $ul = $('<ul/>', { class: 'checked' }).append($('<li/>', { text: localized_text }));
        $('#formMessage')
            .attr('class', is_success ? 'success-msg' : 'errorfield')
            .html(is_success ? $ul : localized_text)
            .css('display', 'block')
            .delay(5000)
            .fadeOut(1000);
    };

    const populateResidence = (response) => (
        new Promise((resolve) => {
            const residence_list = response.residence_list;
            if (residence_list.length > 0) {
                const $options               = $('<div/>');
                const $options_with_disabled = $('<div/>');
                residence_list.forEach((res) => {
                    $options.append(CommonFunctions.makeOption({ text: res.text, value: res.value }));
                    $options_with_disabled.append(CommonFunctions.makeOption({
                        text       : res.text,
                        value      : res.value,
                        is_disabled: res.disabled,
                    }));
                });

                if (residence) {
                    const $tax_residence = $('#tax_residence');
                    $tax_residence.html($options_with_disabled.html()).promise().done(() => {
                        setTimeout(() => {
                            $tax_residence.select2()
                                .val(get_settings_data.tax_residence ? get_settings_data.tax_residence.split(',') : '')
                                .trigger('change')
                                .setVisibility(1);
                        }, 500);
                    });

                    if (!get_settings_data.place_of_birth) {
                        $options.prepend($('<option/>', { value: '', text: localize('Please select') }));
                        $('#place_of_birth')
                            .html($options.html())
                            .val(residence);
                    }

                    if (!get_settings_data.citizen) {
                        $options.prepend($('<option/>', { value: '', text: localize('Please select') }));
                        $('#citizen')
                            .html($options.html())
                            .val(residence);
                    }
                } else {
                    $('#country').parent().replaceWith($('<select/>', { id: 'residence', single: 'single' }));
                    const $residence = $('#residence');
                    $options_with_disabled.prepend($('<option/>', { text: localize('Please select a country'), value: '' }));
                    $residence.html($options_with_disabled.html());
                    $residence.select2({
                        matcher(params, data) {
                            return SelectMatcher(params, data);
                        },
                    });
                }
            }
            resolve();
        })
    );

    const populateStates = (response) => (
        new Promise((resolve) => {
            const states = response.states_list;

            const address_state = '#address_state';
            let $field          = $(address_state);

            $field.empty();

            if (states && states.length > 0) {
                $field.append($('<option/>', { value: '', text: localize('Please select') }));
                states.forEach((state) => {
                    $field.append($('<option/>', { value: state.value, text: state.text }));
                });
            } else {
                $field.replaceWith($('<input/>', { id: address_state.replace('#', ''), name: 'address_state', type: 'text', maxlength: '35', 'data-lpignore': true }));
                $field = $(address_state);
            }
            $field.val(get_settings_data.address_state);

            if (states && states.length > 0) {
                $('#address_state').select2({
                    matcher(params, data) {
                        return SelectMatcher(params, data);
                    },
                });
            }
            $field.val(get_settings_data.address_state);

            resolve();
        })
    );

    const onLoad = () => {
        BinarySocket.wait('get_account_status', 'get_settings').then(() => {
            init();
            get_settings_data = State.getResponse('get_settings');

            if (is_virtual) {
                getDetailsResponse(get_settings_data);
            }

            if (!is_virtual || !residence) {
                BinarySocket.send({ residence_list: 1 }).then(response => {
                    populateResidence(response).then(() => {
                        if (residence) {
                            BinarySocket.send({ states_list: residence }).then(response_state => {
                                populateStates(response_state).then(() => {
                                    getDetailsResponse(get_settings_data, response.residence_list);
                                });
                            });
                        } else {
                            getDetailsResponse(get_settings_data, response.residence_list);
                        }
                        $('#place_of_birth, #citizen').select2({
                            matcher(params, data) {
                                return SelectMatcher(params, data);
                            },
                        });
                    });
                });
            }
        });
    };

    const onUnload = () => {
        is_for_new_account = false;
        localStorage.removeItem('personal_details_redirect');
    };

    return {
        onLoad,
        onUnload,

        setIsForNewAccount: (bool) => { is_for_new_account = bool; },
    };
})();

module.exports = PersonalDetails;
<commit_msg>add check for tax_details_required<commit_after>const SelectMatcher    = require('@binary-com/binary-style').select2Matcher;
const moment           = require('moment');
const BinaryPjax       = require('../../../../base/binary_pjax');
const Client           = require('../../../../base/client');
const Header           = require('../../../../base/header');
const BinarySocket     = require('../../../../base/socket');
const FormManager      = require('../../../../common/form_manager');
const CommonFunctions  = require('../../../../../_common/common_functions');
const Geocoder         = require('../../../../../_common/geocoder');
const localize         = require('../../../../../_common/localize').localize;
const State            = require('../../../../../_common/storage').State;
const getPropertyValue = require('../../../../../_common/utility').getPropertyValue;

const PersonalDetails = (() => {
    const form_id           = '#frmPersonalDetails';
    const real_acc_elements = '.RealAcc';

    let is_for_new_account = false;

    let editable_fields,
        is_virtual,
        residence,
        get_settings_data;

    const init = () => {
        editable_fields   = {};
        get_settings_data = {};
        is_virtual        = Client.get('is_virtual');
        residence         = Client.get('residence');
    };

    const showHideTaxMessage = () => {
        const $tax_info_declaration = $('#tax_information_declaration');
        const $tax_information_info = $('#tax_information_info');

        if (Client.shouldCompleteTax()) {
            $('#tax_information_note_toggle').off('click').on('click', (e) => {
                e.stopPropagation();
                $('#tax_information_note_toggle').toggleClass('open');
                $('#tax_information_note').slideToggle();
            });
        } else {
            $tax_information_info.setVisibility(0); // hide tax info
            $tax_info_declaration.setVisibility(0); // hide tax info declaration
        }
    };

    const showHideMissingDetails = () => {
        const validations = getValidations();
        const has_missing_field = validations.find((validation) => /req/.test(validation.validations) && $(validation.selector).val() === '');
        $('#missing_details_notice').setVisibility(!!has_missing_field);
    };

    const getDetailsResponse = (data, residence_list = State.getResponse('residence_list')) => {
        const get_settings         = $.extend({}, data);
        get_settings.date_of_birth = 'date_of_birth' in get_settings ? moment.utc(new Date(get_settings.date_of_birth * 1000)).format('YYYY-MM-DD') : '';
        const accounts             = Client.getAllLoginids();
        // for subaccounts, back-end sends loginid of the master account as name
        const hide_name            = accounts.some(loginid => new RegExp(loginid, 'i').test(get_settings.first_name)) || is_virtual;
        if (!hide_name) {
            get_settings.name = `${(get_settings.salutation || '')} ${(get_settings.first_name || '')} ${(get_settings.last_name || '')}`;
        }

        if (get_settings.place_of_birth) {
            get_settings.place_of_birth =
                (residence_list.find(obj => obj.value === get_settings.place_of_birth) || {}).text ||
                get_settings.place_of_birth;
        }

        if (get_settings.citizen) {
            get_settings.citizen =
                (residence_list.find(obj => obj.value === get_settings.citizen) || {}).text ||
                get_settings.citizen;
        }

        displayGetSettingsData(get_settings);

        if (is_virtual) {
            $(real_acc_elements).remove();
        } else {
            $(real_acc_elements).setVisibility(1);
            showHideTaxMessage();
        }
        $(form_id).setVisibility(1);
        $('#loading').remove();
        FormManager.init(form_id, getValidations());
        FormManager.handleSubmit({
            form_selector       : form_id,
            obj_request         : { set_settings: 1 },
            fnc_response_handler: setDetailsResponse,
            fnc_additional_check: additionalCheck,
            enable_button       : true,
        });
        if (!is_virtual) {
            Geocoder.validate(form_id);
        }
        showHideMissingDetails();
    };

    const show_label_if_any_value = ['account_opening_reason', 'citizen', 'place_of_birth'];

    const displayGetSettingsData = (get_settings, populate = true) => {
        let el_id,
            el_key,
            has_label,
            should_show_label,
            should_update_value;
        Object.keys(get_settings).forEach((key) => {
            has_label           = show_label_if_any_value.indexOf(key) !== -1;
            should_show_label   = has_label && get_settings[key];               // if we have a value for any of these fields, show them as label
            el_id               = `${should_show_label ? 'lbl_' : ''}${key}`;
            el_key              = CommonFunctions.getElementById(el_id);
            if (el_key) {
                editable_fields[key] = get_settings[key];
                if (populate) {
                    should_update_value = /select|text/i.test(el_key.type);
                    if (has_label) {
                        CommonFunctions.getElementById(`row_${el_id}`).setVisibility(1);
                    }
                    if (el_key.type === 'checkbox') {
                        el_key.checked = !!get_settings[key];
                    } else if (!should_update_value) { // for all non (checkbox|select|text) elements
                        const localized_text = (document.querySelector(`#${key} option[value="${get_settings[key]}"]`) || {}).innerText || get_settings[key];
                        CommonFunctions.elementInnerHtml(el_key, localized_text || '-');
                    }
                    if (should_update_value || should_show_label) {
                        // if should show label, set the value of the non-label so that it doesn't count as missing information
                        $(should_show_label ? `#${key}` : el_key)
                            .val(get_settings[key] ? get_settings[key].split(',') : '')
                            .trigger('change');
                    }
                }
            }
        });
        if (get_settings.country) {
            $('#residence').replaceWith($('<label/>').append($('<strong/>', { id: 'country' })));
            $('#country').text(get_settings.country);
        }
    };

    const additionalCheck = (data) => {
        if (!isChanged(data)) {
            showFormMessage(localize('You did not change anything.'), false);
            return false;
        }
        return true;
    };

    const isChanged = (data) => {
        const compare_data = $.extend({}, data);
        return Object.keys(compare_data).some(key => (
            key !== 'set_settings' && editable_fields[key] !== compare_data[key]
        ));
    };

    const getValidations = () => {
        let validations;
        if (is_virtual) {
            validations = [
                { selector: '#email_consent' },
                { selector: '#residence', validations: ['req'] },
            ];
        } else {
            const is_financial      = Client.isAccountOfType('financial');
            const is_gaming         = Client.isAccountOfType('gaming');
            const mt_acct_type      = localStorage.getItem('personal_details_redirect');
            const is_for_mt_citizen = !!mt_acct_type;                                                   // all mt account opening requires citizen
            const is_for_mt_tax     = /real/.test(mt_acct_type) && mt_acct_type.split('_').length > 2;  // demo and volatility mt accounts do not require tax info
            const is_tax_req        = is_financial || (is_for_mt_tax && +State.getResponse('landing_company.config.tax_details_required') === 1);

            validations = [
                { selector: '#address_line_1',         validations: ['req', 'address'] },
                { selector: '#address_line_2',         validations: ['address'] },
                { selector: '#address_city',           validations: ['req', 'letter_symbol'] },
                { selector: '#address_state',          validations: $('#address_state').prop('nodeName') === 'SELECT' ? '' : ['letter_symbol'] },
                { selector: '#address_postcode',       validations: [Client.get('residence') === 'gb' ? 'req' : '', 'postcode', ['length', { min: 0, max: 20 }]] },
                { selector: '#email_consent' },
                { selector: '#phone',                  validations: ['req', 'phone', ['length', { min: 6, max: 35, value: () => $('#phone').val().replace(/^\+/, '')  }]] },
                { selector: '#place_of_birth',         validations: ['req'] },
                { selector: '#account_opening_reason', validations: ['req'] },

                { selector: '#tax_residence',  validations: (is_tax_req) ? ['req'] : '' },
                { selector: '#citizen',        validations: (is_financial || is_gaming || is_for_mt_citizen) ? ['req'] : '' },
                { selector: '#chk_tax_id',     validations: is_financial ? [['req', { hide_asterisk: true, message: localize('Please confirm that all the information above is true and complete.') }]] : '', exclude_request: 1 },
            ];

            const tax_id_validation  = { selector: '#tax_identification_number', validations: ['tax_id', ['length', { min: 0, max: 20 }]] };
            if (is_tax_req) {
                tax_id_validation.validations[1][1].min = 1;
                tax_id_validation.validations.unshift('req');
            }
            validations.push(tax_id_validation);
        }
        return validations;
    };

    const setDetailsResponse = (response) => {
        // allow user to resubmit the form on error.
        const is_error = response.set_settings !== 1;
        if (!is_error) {
            const redirect_url = localStorage.getItem('personal_details_redirect');
            // to update tax information message for financial clients
            BinarySocket.send({ get_account_status: 1 }, { forced: true }).then((response_status) => {
                showHideTaxMessage();
                Header.displayAccountStatus();
                if (redirect_url && +response_status.get_account_status.prompt_client_to_authenticate && Client.isAccountOfType('financial')) {
                    $('#msg_authenticate').setVisibility(1);
                }
            });
            // to update the State with latest get_settings data
            BinarySocket.send({ get_settings: 1 }, { forced: true }).then((data) => {
                if (is_virtual && response.echo_req.residence) {
                    window.location.reload(); // reload page if we are setting residence
                    return;
                }
                // update notification shown for set residence etc
                Header.displayAccountStatus();
                if (is_for_new_account) {
                    is_for_new_account = false;
                    BinaryPjax.loadPreviousUrl();
                    return;
                }
                const get_settings        = data.get_settings;
                const is_tax_req          = +State.getResponse('landing_company.config.tax_details_required') === 1;
                const is_for_mt_financial = /real_vanuatu_(standard|advanced)/.test(redirect_url);
                const has_required_mt = ((is_for_mt_financial && is_tax_req) ?
                    (get_settings.tax_residence && get_settings.tax_identification_number && get_settings.citizen)
                    :
                    get_settings.citizen // only check Citizen if user selects mt volatility account
                );
                if (redirect_url && has_required_mt) {
                    localStorage.removeItem('personal_details_redirect');
                    $.scrollTo($('h1#heading'), 500, { offset: -10 });
                    $(form_id).setVisibility(0);
                    $('#missing_details_notice').setVisibility(0);
                    $('.rowCustomerSupport').setVisibility(0);
                    $('#msg_main').setVisibility(1);
                    return;
                }
                getDetailsResponse(get_settings);
            });
        }
        showFormMessage(is_error ?
            (getPropertyValue(response, ['error', 'message']) || localize('Sorry, an error occurred while processing your account.')) :
            localize('Your settings have been updated successfully.'), !is_error);
    };

    const showFormMessage = (localized_text, is_success) => {
        const $ul = $('<ul/>', { class: 'checked' }).append($('<li/>', { text: localized_text }));
        $('#formMessage')
            .attr('class', is_success ? 'success-msg' : 'errorfield')
            .html(is_success ? $ul : localized_text)
            .css('display', 'block')
            .delay(5000)
            .fadeOut(1000);
    };

    const populateResidence = (response) => (
        new Promise((resolve) => {
            const residence_list = response.residence_list;
            if (residence_list.length > 0) {
                const $options               = $('<div/>');
                const $options_with_disabled = $('<div/>');
                residence_list.forEach((res) => {
                    $options.append(CommonFunctions.makeOption({ text: res.text, value: res.value }));
                    $options_with_disabled.append(CommonFunctions.makeOption({
                        text       : res.text,
                        value      : res.value,
                        is_disabled: res.disabled,
                    }));
                });

                if (residence) {
                    const $tax_residence = $('#tax_residence');
                    $tax_residence.html($options_with_disabled.html()).promise().done(() => {
                        setTimeout(() => {
                            $tax_residence.select2()
                                .val(get_settings_data.tax_residence ? get_settings_data.tax_residence.split(',') : '')
                                .trigger('change')
                                .setVisibility(1);
                        }, 500);
                    });

                    if (!get_settings_data.place_of_birth) {
                        $options.prepend($('<option/>', { value: '', text: localize('Please select') }));
                        $('#place_of_birth')
                            .html($options.html())
                            .val(residence);
                    }

                    if (!get_settings_data.citizen) {
                        $options.prepend($('<option/>', { value: '', text: localize('Please select') }));
                        $('#citizen')
                            .html($options.html())
                            .val(residence);
                    }
                } else {
                    $('#country').parent().replaceWith($('<select/>', { id: 'residence', single: 'single' }));
                    const $residence = $('#residence');
                    $options_with_disabled.prepend($('<option/>', { text: localize('Please select a country'), value: '' }));
                    $residence.html($options_with_disabled.html());
                    $residence.select2({
                        matcher(params, data) {
                            return SelectMatcher(params, data);
                        },
                    });
                }
            }
            resolve();
        })
    );

    const populateStates = (response) => (
        new Promise((resolve) => {
            const states = response.states_list;

            const address_state = '#address_state';
            let $field          = $(address_state);

            $field.empty();

            if (states && states.length > 0) {
                $field.append($('<option/>', { value: '', text: localize('Please select') }));
                states.forEach((state) => {
                    $field.append($('<option/>', { value: state.value, text: state.text }));
                });
            } else {
                $field.replaceWith($('<input/>', { id: address_state.replace('#', ''), name: 'address_state', type: 'text', maxlength: '35', 'data-lpignore': true }));
                $field = $(address_state);
            }
            $field.val(get_settings_data.address_state);

            if (states && states.length > 0) {
                $('#address_state').select2({
                    matcher(params, data) {
                        return SelectMatcher(params, data);
                    },
                });
            }
            $field.val(get_settings_data.address_state);

            resolve();
        })
    );

    const onLoad = () => {
        BinarySocket.wait('get_account_status', 'get_settings').then(() => {
            init();
            get_settings_data = State.getResponse('get_settings');

            if (is_virtual) {
                getDetailsResponse(get_settings_data);
            }

            if (!is_virtual || !residence) {
                BinarySocket.send({ residence_list: 1 }).then(response => {
                    populateResidence(response).then(() => {
                        if (residence) {
                            BinarySocket.send({ states_list: residence }).then(response_state => {
                                populateStates(response_state).then(() => {
                                    getDetailsResponse(get_settings_data, response.residence_list);
                                });
                            });
                        } else {
                            getDetailsResponse(get_settings_data, response.residence_list);
                        }
                        $('#place_of_birth, #citizen').select2({
                            matcher(params, data) {
                                return SelectMatcher(params, data);
                            },
                        });
                    });
                });
            }
        });
    };

    const onUnload = () => {
        is_for_new_account = false;
        localStorage.removeItem('personal_details_redirect');
    };

    return {
        onLoad,
        onUnload,

        setIsForNewAccount: (bool) => { is_for_new_account = bool; },
    };
})();

module.exports = PersonalDetails;
<|endoftext|>


<commit_before>/* global SETTINGS: false */
import urljoin from 'url-join';

export const HIGH_SCHOOL = 'hs';
export const ASSOCIATE = 'a';
export const BACHELORS = 'b';
export const MASTERS = 'm';
export const DOCTORATE = 'p';

export const ISO_8601_FORMAT = 'YYYY-MM-DD';
export const DASHBOARD_FORMAT = 'MMM D, Y';
export const DASHBOARD_MONTH_FORMAT = 'MM[/]YYYY';

export const CP1252_REGEX = /^[\u0020-\u00FF]*$/;
// greater-than, comma, quotation-mark
export const INVALID_NAME_CHARS_REGEX = /[\u003E\u002C\u0022]/;

// NOTE: this is in order of attainment
export const EDUCATION_LEVELS = [
  {value: HIGH_SCHOOL, label: "High school"},
  {value: ASSOCIATE, label: 'Associate degree'},
  {value: BACHELORS, label: "Bachelor's degree"},
  {value: MASTERS, label: "Master's or professional degree"},
  {value: DOCTORATE, label: "Doctorate"}
];

export const SEARCH_FACET_FIELD_LABEL_MAP = {
  'program.enrollments.course_title': 'Course',
  'program.enrollments.semester': 'Semester',
  'program.enrollments.payment_status': 'Payment Status',
  'program.grade_average': 'Average Grade in Program',
  'grade-average': 'Average Grade in Program',
  'profile.birth_country': 'Country of Birth',
  'profile.country': 'Current Residence',
  'profile.education.degree_name': 'Degree',
  'profile.work_history.company_name': 'Company'
};

// NOTE: these need to be kept in sync with ui/url_utils.py
export const PERSONAL_STEP = 'personal';
export const EMPLOYMENT_STEP = 'professional';
export const EDUCATION_STEP = 'education';

export const YEAR_VALIDATION_CUTOFF = 120;

export const ALL_ERRORS_VISIBLE = 'ALL_ERRORS_VISIBLE';

export const PROFILE_STEP_LABELS = new Map([
  [PERSONAL_STEP, "Personal"],
  [EDUCATION_STEP, "Education"],
  [EMPLOYMENT_STEP, "Professional"]
]);

export const PROFILE_STEP_ORDER = [
  PERSONAL_STEP,
  EDUCATION_STEP,
  EMPLOYMENT_STEP
];

export const DEFAULT_OPTION_LIMIT_COUNT = 10;

export const SEARCH_FILTER_DEFAULT_VISIBILITY = true;

export const STATUS_PASSED = 'passed';
export const STATUS_NOT_PASSED = 'not-passed';
export const STATUS_CURRENTLY_ENROLLED = 'currently-enrolled';
export const STATUS_WILL_ATTEND = 'will-attend';
export const STATUS_CAN_UPGRADE = 'can-upgrade';
export const STATUS_MISSED_DEADLINE = 'missed-deadline';
export const STATUS_OFFERED = 'offered';
export const STATUS_PAID_BUT_NOT_ENROLLED = 'paid-but-not-enrolled';

// note: this status is not sent from the server
export const STATUS_PENDING_ENROLLMENT = 'pending-enrollment';

export const ALL_COURSE_STATUSES = [
  STATUS_PASSED,
  STATUS_NOT_PASSED,
  STATUS_OFFERED,
  STATUS_CAN_UPGRADE,
  STATUS_CURRENTLY_ENROLLED,
  STATUS_WILL_ATTEND,
  STATUS_PENDING_ENROLLMENT,
  STATUS_MISSED_DEADLINE,
  STATUS_PAID_BUT_NOT_ENROLLED,
];

// financial aid statuses
export const FA_STATUS_CREATED = 'created';
export const FA_STATUS_PENDING_DOCS = 'pending-docs';
export const FA_STATUS_DOCS_SENT = 'docs-sent';
export const FA_STATUS_PENDING_MANUAL_APPROVAL = 'pending-manual-approval';
export const FA_STATUS_APPROVED = 'approved';
export const FA_STATUS_AUTO_APPROVED = 'auto-approved';
export const FA_STATUS_SKIPPED = 'skipped';
export const FA_STATUS_RESET = 'reset';

export const FA_ALL_STATUSES = [
  FA_STATUS_CREATED,
  FA_STATUS_PENDING_DOCS,
  FA_STATUS_DOCS_SENT,
  FA_STATUS_PENDING_MANUAL_APPROVAL,
  FA_STATUS_APPROVED,
  FA_STATUS_AUTO_APPROVED,
  FA_STATUS_SKIPPED,
  FA_STATUS_RESET,
];
export const FA_PENDING_STATUSES = [
  FA_STATUS_PENDING_DOCS,
  FA_STATUS_DOCS_SENT,
  FA_STATUS_PENDING_MANUAL_APPROVAL,
];
export const FA_TERMINAL_STATUSES = [
  FA_STATUS_AUTO_APPROVED,
  FA_STATUS_APPROVED,
  FA_STATUS_SKIPPED,
];

export const TOAST_SUCCESS = 'done';
export const TOAST_FAILURE = 'error';

export const EDX_LINK_BASE = urljoin(SETTINGS.edx_base_url, 'courses/');

export const COUPON_CONTENT_TYPE_COURSERUN = 'courserun';
export const COUPON_CONTENT_TYPE_COURSE = 'course';
export const COUPON_CONTENT_TYPE_PROGRAM = 'program';

export const COUPON_AMOUNT_TYPE_PERCENT_DISCOUNT = 'percent-discount';
export const COUPON_AMOUNT_TYPE_FIXED_DISCOUNT = 'fixed-discount';
export const COUPON_AMOUNT_TYPE_FIXED_PRICE = 'fixed-price';

export const COUPON_TYPE_STANDARD = 'standard';
export const COUPON_TYPE_DISCOUNTED_PREVIOUS_COURSE = 'discounted-previous-course';

export const PEARSON_PROFILE_ABSENT = 'absent';
export const PEARSON_PROFILE_SUCCESS = 'success';
export const PEARSON_PROFILE_IN_PROGRESS = 'in-progress';
export const PEARSON_PROFILE_INVALID = 'invalid';
export const PEARSON_PROFILE_SCHEDULABLE = 'schedulable';

export const GET = 'GET';
export const PATCH = 'PATCH';
export const POST = 'POST';
<commit_msg>Added label for num courses passed (#3095)<commit_after>/* global SETTINGS: false */
import urljoin from 'url-join';

export const HIGH_SCHOOL = 'hs';
export const ASSOCIATE = 'a';
export const BACHELORS = 'b';
export const MASTERS = 'm';
export const DOCTORATE = 'p';

export const ISO_8601_FORMAT = 'YYYY-MM-DD';
export const DASHBOARD_FORMAT = 'MMM D, Y';
export const DASHBOARD_MONTH_FORMAT = 'MM[/]YYYY';

export const CP1252_REGEX = /^[\u0020-\u00FF]*$/;
// greater-than, comma, quotation-mark
export const INVALID_NAME_CHARS_REGEX = /[\u003E\u002C\u0022]/;

// NOTE: this is in order of attainment
export const EDUCATION_LEVELS = [
  {value: HIGH_SCHOOL, label: "High school"},
  {value: ASSOCIATE, label: 'Associate degree'},
  {value: BACHELORS, label: "Bachelor's degree"},
  {value: MASTERS, label: "Master's or professional degree"},
  {value: DOCTORATE, label: "Doctorate"}
];

export const SEARCH_FACET_FIELD_LABEL_MAP = {
  'program.enrollments.course_title': 'Course',
  'program.enrollments.semester': 'Semester',
  'program.enrollments.payment_status': 'Payment Status',
  'program.grade_average': 'Average Grade in Program',
  'grade-average': 'Average Grade in Program',
  'profile.birth_country': 'Country of Birth',
  'profile.country': 'Current Residence',
  'profile.education.degree_name': 'Degree',
  'profile.work_history.company_name': 'Company',
  'num-courses-passed': '# of Courses Passed',
};

// NOTE: these need to be kept in sync with ui/url_utils.py
export const PERSONAL_STEP = 'personal';
export const EMPLOYMENT_STEP = 'professional';
export const EDUCATION_STEP = 'education';

export const YEAR_VALIDATION_CUTOFF = 120;

export const ALL_ERRORS_VISIBLE = 'ALL_ERRORS_VISIBLE';

export const PROFILE_STEP_LABELS = new Map([
  [PERSONAL_STEP, "Personal"],
  [EDUCATION_STEP, "Education"],
  [EMPLOYMENT_STEP, "Professional"]
]);

export const PROFILE_STEP_ORDER = [
  PERSONAL_STEP,
  EDUCATION_STEP,
  EMPLOYMENT_STEP
];

export const DEFAULT_OPTION_LIMIT_COUNT = 10;

export const SEARCH_FILTER_DEFAULT_VISIBILITY = true;

export const STATUS_PASSED = 'passed';
export const STATUS_NOT_PASSED = 'not-passed';
export const STATUS_CURRENTLY_ENROLLED = 'currently-enrolled';
export const STATUS_WILL_ATTEND = 'will-attend';
export const STATUS_CAN_UPGRADE = 'can-upgrade';
export const STATUS_MISSED_DEADLINE = 'missed-deadline';
export const STATUS_OFFERED = 'offered';
export const STATUS_PAID_BUT_NOT_ENROLLED = 'paid-but-not-enrolled';

// note: this status is not sent from the server
export const STATUS_PENDING_ENROLLMENT = 'pending-enrollment';

export const ALL_COURSE_STATUSES = [
  STATUS_PASSED,
  STATUS_NOT_PASSED,
  STATUS_OFFERED,
  STATUS_CAN_UPGRADE,
  STATUS_CURRENTLY_ENROLLED,
  STATUS_WILL_ATTEND,
  STATUS_PENDING_ENROLLMENT,
  STATUS_MISSED_DEADLINE,
  STATUS_PAID_BUT_NOT_ENROLLED,
];

// financial aid statuses
export const FA_STATUS_CREATED = 'created';
export const FA_STATUS_PENDING_DOCS = 'pending-docs';
export const FA_STATUS_DOCS_SENT = 'docs-sent';
export const FA_STATUS_PENDING_MANUAL_APPROVAL = 'pending-manual-approval';
export const FA_STATUS_APPROVED = 'approved';
export const FA_STATUS_AUTO_APPROVED = 'auto-approved';
export const FA_STATUS_SKIPPED = 'skipped';
export const FA_STATUS_RESET = 'reset';

export const FA_ALL_STATUSES = [
  FA_STATUS_CREATED,
  FA_STATUS_PENDING_DOCS,
  FA_STATUS_DOCS_SENT,
  FA_STATUS_PENDING_MANUAL_APPROVAL,
  FA_STATUS_APPROVED,
  FA_STATUS_AUTO_APPROVED,
  FA_STATUS_SKIPPED,
  FA_STATUS_RESET,
];
export const FA_PENDING_STATUSES = [
  FA_STATUS_PENDING_DOCS,
  FA_STATUS_DOCS_SENT,
  FA_STATUS_PENDING_MANUAL_APPROVAL,
];
export const FA_TERMINAL_STATUSES = [
  FA_STATUS_AUTO_APPROVED,
  FA_STATUS_APPROVED,
  FA_STATUS_SKIPPED,
];

export const TOAST_SUCCESS = 'done';
export const TOAST_FAILURE = 'error';

export const EDX_LINK_BASE = urljoin(SETTINGS.edx_base_url, 'courses/');

export const COUPON_CONTENT_TYPE_COURSERUN = 'courserun';
export const COUPON_CONTENT_TYPE_COURSE = 'course';
export const COUPON_CONTENT_TYPE_PROGRAM = 'program';

export const COUPON_AMOUNT_TYPE_PERCENT_DISCOUNT = 'percent-discount';
export const COUPON_AMOUNT_TYPE_FIXED_DISCOUNT = 'fixed-discount';
export const COUPON_AMOUNT_TYPE_FIXED_PRICE = 'fixed-price';

export const COUPON_TYPE_STANDARD = 'standard';
export const COUPON_TYPE_DISCOUNTED_PREVIOUS_COURSE = 'discounted-previous-course';

export const PEARSON_PROFILE_ABSENT = 'absent';
export const PEARSON_PROFILE_SUCCESS = 'success';
export const PEARSON_PROFILE_IN_PROGRESS = 'in-progress';
export const PEARSON_PROFILE_INVALID = 'invalid';
export const PEARSON_PROFILE_SCHEDULABLE = 'schedulable';

export const GET = 'GET';
export const PATCH = 'PATCH';
export const POST = 'POST';
<|endoftext|>


<commit_before>(function () {
	'use strict';
	/*global angular, Blob, URL */

	angular.module('angular.img', [
	]).directive('httpSrc', ['$http', function ($http) {
		return {
			// do not share scope with sibling img tags and parent
			// (prevent show same images on img tag)
			scope: {},
			link: function ($scope, elem, attrs) {
				function revokeObjectURL() {
					if ($scope.objectURL) {
						URL.revokeObjectURL($scope.objectURL);
					}
				}

				$scope.$watch('objectURL', function (objectURL) {
					elem.attr('src', objectURL);
				});

				$scope.$on('$destroy', function () {
					revokeObjectURL();
				});

				attrs.$observe('httpSrc', function (url) {
					revokeObjectURL();

					if(url && url.indexOf('data:') === 0) {
						$scope.objectURL = url;
					} else if(url) {
						$http.get(url, { responseType: 'arraybuffer' })
							.then(function (response) {
								var blob = new Blob(
									[ response.data ],
									{ type: response.headers('Content-Type') }
								);
								$scope.objectURL = URL.createObjectURL(blob);
							});
					}
				});
			}
		};
	}]);
}());
<commit_msg>support function expression<commit_after>(function () {
	'use strict';
	/*global angular, Blob, URL */

	angular.module('angular.img', [
	]).directive('httpSrc', ['$http', function ($http) {
		return {
			// do not share scope with sibling img tags and parent
			// (prevent show same images on img tag)
			scope: {
				httpSrc: '@'
			},
			link: function ($scope, elem, attrs) {
				function revokeObjectURL() {
					if ($scope.objectURL) {
						URL.revokeObjectURL($scope.objectURL);
					}
				}

				$scope.$watch('objectURL', function (objectURL) {
					elem.attr('src', objectURL);
				});

				$scope.$on('$destroy', function () {
					revokeObjectURL();
				});

				attrs.$observe('httpSrc', function (url) {
					revokeObjectURL();

					if(url && url.indexOf('data:') === 0) {
						$scope.objectURL = url;
					} else if(url) {
						$http.get(url, { responseType: 'arraybuffer' })
							.then(function (response) {
								var blob = new Blob(
									[ response.data ],
									{ type: response.headers('Content-Type') }
								);
								$scope.objectURL = URL.createObjectURL(blob);
							});
					}
				});
			}
		};
	}]);
}());
<|endoftext|>


<commit_before>
exports.up = function(knex, Promise) {

};

exports.down = function(knex, Promise) {

};
<commit_msg>update migration file<commit_after>
exports.up = function(knex, Promise) {
  return knex.schema.createTableIfNotExists('gallery', function(table){
    table.increments()
    table.string('name')
    table.string('category')
    table.string('filepath')
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTableIfExists('gallery')
};
<|endoftext|>


<commit_before>// Restrict output in a codecell to a maximum length

define([
    'notebook/js/outputarea',
    'notebook/js/codecell',
    'services/config',
    'base/js/utils'
], function(oa, cc, configmod, utils) {
    "use strict";

    var base_url = utils.get_body_data("baseUrl");
    var config = new configmod.ConfigSection('notebook', {base_url: base_url});

    // define default values for config parameters
    var params = {
        // maximum number of characters the output area is allowed to print
        limit_output : 10000,
        // message to print when output is limited
        limit_output_message : 'limit_output extension: Maximum message size of {limit_output_length} exceeded with {output_length} characters'
    };

    // to be called once config is loaded, this updates default config vals
    // with the ones specified by the server's config file
    var update_params = function() {
        for (var key in params) {
            if (config.data.hasOwnProperty(key) ){
                params[key] = config.data[key];
            }
        }
    };

    function is_finite_number (n) {
        n = parseFloat(n);
        return !isNaN(n) && isFinite(n);
    }

    config.loaded.then(function() {
        update_params();
        // sometimes limit_output metadata val can get stored as a string
        params.limit_output = parseFloat(params.limit_output);

        var old_handle_output = oa.OutputArea.prototype.handle_output;
        oa.OutputArea.prototype.handle_output = function (msg) {
            if (msg.header.msg_type.match("stream|execute_result|display_data")) {
                var count = 0;
                if (msg.header.msg_type === "stream") {
                    count = String(msg.content.text).length;
                } else {
                    count = Math.max(
                        (msg.content.data['text/plain'] === undefined) ? 0 : String(msg.content.data['text/plain']).length,
                        (msg.content.data['text/html'] === undefined) ? 0 : String(msg.content.data['text/html']).length );
                }
                var MAX_CHARACTERS = params.limit_output;
                var cell = this.element.closest('.cell').data('cell');
                if (is_finite_number(cell.metadata.limit_output)) {
                    MAX_CHARACTERS = parseFloat(cell.metadata.limit_output);
                }
                if (count > MAX_CHARACTERS) {
                    console.log("limit_output: output", count, "exceeded", MAX_CHARACTERS, "characters. Further output muted.");
                    if (msg.header.msg_type === "stream") {
                        msg.content.text = msg.content.text.substr(0, MAX_CHARACTERS);
                    } else {
                        if (msg.content.data['text/plain'] !== undefined) {
                            msg.content.data['text/plain'] = msg.content.data['text/plain'].substr(0, MAX_CHARACTERS);
                        }
                        if (msg.content.data['text/html'] !== undefined) {
                            msg.content.data['text/html'] = msg.content.data['text/html'].substr(0, MAX_CHARACTERS);
                        }
                    }

                    // allow simple substitutions for output length for quick debugging
                    var limitmsg = params.limit_output_message.replace("{limit_output_length}", MAX_CHARACTERS)
                                                              .replace("{output_length}", count);
                    this.append_output({
                        "output_type": "display_data",
                        "metadata": {}, // included to avoid warning
                        "data": {"text/html": limitmsg},
                    });
                }
            }
            return old_handle_output.apply(this, arguments);
        };

        var old_clear_output = oa.OutputArea.prototype.clear_output;
        oa.OutputArea.prototype.clear_output = function () {
            // reset counter on execution.
            this.data('limit_output_count', 0);
            return old_clear_output.apply(this, arguments);
        };
    });

    var load_ipython_extension = function() {
        config.load();
    };

    return {
        load_ipython_extension : load_ipython_extension
    };
});
<commit_msg>[limit_output] limit outputs even over several distinct outputs<commit_after>// Restrict output in a codecell to a maximum length

define([
    'notebook/js/outputarea',
    'notebook/js/codecell',
    'services/config',
    'base/js/utils'
], function(oa, cc, configmod, utils) {
    "use strict";

    var base_url = utils.get_body_data("baseUrl");
    var config = new configmod.ConfigSection('notebook', {base_url: base_url});

    // define default values for config parameters
    var params = {
        // maximum number of characters the output area is allowed to print
        limit_output : 10000,
        // message to print when output is limited
        limit_output_message : 'limit_output extension: Maximum message size of {limit_output_length} exceeded with {output_length} characters'
    };

    // to be called once config is loaded, this updates default config vals
    // with the ones specified by the server's config file
    var update_params = function() {
        for (var key in params) {
            if (config.data.hasOwnProperty(key) ){
                params[key] = config.data[key];
            }
        }
    };

    function is_finite_number (n) {
        n = parseFloat(n);
        return !isNaN(n) && isFinite(n);
    }

    config.loaded.then(function() {
        update_params();
        // sometimes limit_output metadata val can get stored as a string
        params.limit_output = parseFloat(params.limit_output);

        var old_handle_output = oa.OutputArea.prototype.handle_output;
        oa.OutputArea.prototype.handle_output = function (msg) {
            var handled_msg_types = ['stream', 'execute_result', 'display_data'];
            if (handled_msg_types.indexOf(msg.header.msg_type) < 0) {
                return old_handle_output.apply(this, arguments);
            }
            else {
                // get MAX_CHARACTERS from cell metadata if present, otherwise param
                var MAX_CHARACTERS = params.limit_output;
                var cell_metadata = this.element.closest('.cell').data('cell').metadata;
                if (is_finite_number(cell_metadata.limit_output)) {
                    MAX_CHARACTERS = parseFloat(cell_metadata.limit_output);
                }

                // read the length of already-appended outputs from our data
                var count = this.element.data('limit_output_count') || 0;
                // update count with the length of this message
                var old_count = count;
                if (msg.header.msg_type === "stream") {
                    count += String(msg.content.text).length;
                }
                else {
                    count += Math.max(
                        (msg.content.data['text/plain'] === undefined) ? 0 : String(msg.content.data['text/plain']).length,
                        (msg.content.data['text/html'] === undefined) ? 0 : String(msg.content.data['text/html']).length
                    );
                }
                // save updated count
                this.element.data('limit_output_count', count);

                if (count <= MAX_CHARACTERS) {
                    return old_handle_output.apply(this, arguments);
                }
                // if here, we'd exceed MAX_CHARACTERS with addition of this message.
                if (old_count <= MAX_CHARACTERS) {
                    // Apply truncated portion of this message
                    var to_add = MAX_CHARACTERS - old_count;
                    if (msg.header.msg_type === "stream") {
                        msg.content.text = msg.content.text.substr(0, to_add);
                    }
                    else {
                        if (msg.content.data['text/plain'] !== undefined) {
                            msg.content.data['text/plain'] = msg.content.data['text/plain'].substr(0, to_add);
                        }
                        if (msg.content.data['text/html'] !== undefined) {
                            msg.content.data['text/html'] = msg.content.data['text/html'].substr(0, to_add);
                        }
                    }
                    old_handle_output.apply(this, arguments);

                    // display limit notification messages
                    console.log(
                        "limit_output: Maximum message size of", MAX_CHARACTERS,
                        "exceeded with",  count, "characters. Further output muted."
                    );
                    // allow simple substitutions for output length for quick debugging
                    var limitmsg = params.limit_output_message.replace("{limit_output_length}", MAX_CHARACTERS)
                                                              .replace("{output_length}", count);
                    this.append_output({
                        "output_type": "display_data",
                        "metadata": {}, // included to avoid warning
                        "data": {"text/html": limitmsg},
                    });
                }
            }
        };

        var old_clear_output = oa.OutputArea.prototype.clear_output;
        oa.OutputArea.prototype.clear_output = function () {
            // reset counter on execution.
            this.element.data('limit_output_count', 0);
            return old_clear_output.apply(this, arguments);
        };
    });

    var load_ipython_extension = function() {
        config.load();
    };

    return {
        load_ipython_extension : load_ipython_extension
    };
});
<|endoftext|>


<commit_before>var ss = require('simple-statistics');
var inside = require('turf-inside');

/**
* Calculates the sum of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/sum
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {string} inField the field in input data to analyze
* @param {string} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField` values in `aggregations`
* @example
* var polygons = turf.featurecollection([
*   turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]),
*   turf.polygon([[[10,0],[20,10],[20,20], [20,0]]])]);
* var points = turf.featurecollection([
*   turf.point(5,5, {population: 200}),
*   turf.point(1,3, {population: 600}),
*   turf.point(14,2, {population: 100}),
*   turf.point(13,1, {population: 200}),
*   turf.point(19,7, {population: 300})]);
* var aggregated = turf.sum(polygons, points, 'population', 'sum');
* //=polygons
* //=points
* //=aggregated
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = ss.sum(values);
  });

  return polyFC;
};
<commit_msg>Update properties<commit_after>var ss = require('simple-statistics');
var inside = require('turf-inside');

/**
* Calculates the sum of a field for {@link Point} features within a set of {@link Polygon} features.
*
* @module turf/sum
* @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
* @param {FeatureCollection} points a FeatureCollection of {@link Point} features
* @param {String} inField the field in input data to analyze
* @param {String} outField the field in which to store results
* @return {FeatureCollection} a FeatureCollection of {@link Polygon} features
* with properties listed as `outField`
* @example
* var polygons = turf.featurecollection([
*   turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]),
*   turf.polygon([[[10,0],[20,10],[20,20], [20,0]]])]);
* var points = turf.featurecollection([
*   turf.point(5,5, {population: 200}),
*   turf.point(1,3, {population: 600}),
*   turf.point(14,2, {population: 100}),
*   turf.point(13,1, {population: 200}),
*   turf.point(19,7, {population: 300})]);
* var aggregated = turf.sum(polygons, points, 'population', 'sum');
* //=polygons
* //=points
* //=aggregated
*/
module.exports = function(polyFC, ptFC, inField, outField){
  polyFC.features.forEach(function(poly){
    if(!poly.properties){
      poly.properties = {};
    }
    var values = [];
    ptFC.features.forEach(function(pt){
      if (inside(pt, poly)) {
        values.push(pt.properties[inField]);
      }
    });
    poly.properties[outField] = ss.sum(values);
  });

  return polyFC;
};
<|endoftext|>


<commit_before>/*
  Event Handlers
*/
$('document').ready(function() {

  /*
    Planbook initialization
  */
  $.ajax({
    type: "GET",
    url: "/settings?json=true",
    data: {
      'settings': ref.settings
    },
    statusCode: {
      500: function() {
        alert("There's been a server error. Contact NLTL for assistance.");
      }
    },
    success: function(data) {
      $('li#username').children('a').text(data.name);
      ref.settings = data.settings;

      if (typeof(ref.settings.rows[0]) != "object") { // if it's the old settings format
        for (var i = 0; i < ref.settings.rows.length; i++)
          ref.settings.rows[i] = [ref.settings.rows[i], i+1];
        setSettings(ref.settings, function() {});
      }
      renderRows(ref.settings.rows);
    }
  });

  /*
    Navigation Buttons
  */
  $('#save').click(function() {
    saveWeek(getAssignmentValues());
  });
  $('#back').click(function() {

    if (!ref.turnInProgress) {
      ref.turnInProgress = true;
      // animation
      saveWeek(getAssignmentValues()); // save the current state
      ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() - 7); // decrement by 1 week
      getWeek(function(o) {
        $('#sidebar').slide($(window).width(), 200);
        $("#planner").slide($(window).width(), 200, function() {
          setAssignmentValues(o);
          ref.turnInProgress = false;
        });
      });
    }
  });
  $('#next').click(function() {
    if (!ref.turnInProgress) {
      ref.turnInProgress = true;
      saveWeek(getAssignmentValues());
      ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() + 7);

      getWeek(function(o) {
        $('#sidebar').slide(-$(window).width(), 200);
        $("#planner").slide(-$(window).width(), 200, function() {
          setAssignmentValues(o);
          ref.turnInProgress = false;
        });
      });
    }
  });

  $(document).bind('keydown', 'meta+s', function(e) {
    e.preventDefault();
    saveWeek(getAssignmentValues());
  });

  $(document).bind('keydown', 'meta+right', function(e) {
    e.preventDefault();
    $('#next').click();
  });
  $(document).bind('keydown', 'meta+left', function(e) {
    e.preventDefault();
    $('#back').click();
  });

  // Mobile navigation buttons
  $('#msave').click(function() {
    saveWeek(getAssignmentValues());
  });
  $('#mback').click(function() {
    // animation
    saveWeek(getAssignmentValues()); // save the current state
    ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() - 7); // decrement by 1 week
    getWeek(setAssignmentValues);
    drawDates()
  });
  $('#mnext').click(function() {
    saveWeek(getAssignmentValues());
    ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() + 7);
    getWeek(setAssignmentValues);
    drawDates();
  });
  $('#mdays').change(function() {
    $('#' + ref.visibleDay).hide();
    $('#' + $("select option:selected").text()).show();
    ref.visibleDay = $( "select option:selected" ).text();
  });

  // add subject
  $('button#add').click(function() {
    // save
    var id = 0;
    for (var i = 0; i < ref.settings.rows.length; i++) {
      if (ref.settings.rows[i][1] >= id) {
        id = parseInt(ref.settings.rows[i][1])+1
      }
    }
    ref.settings.rows.push(["Class", id]);
    setSettings(ref.settings, function(data) {
      renderRows(ref.settings.rows);
      $('.subj#'+id).children('.subjectspan').trigger('dblclick');
    });
  });
  taListen();
  subjectListen();
});

function taListen() {
  $("textarea").unbind();
  $("textarea").bind('keydown', 'meta+s', function(e) {
    e.preventDefault();
    saveWeek(getAssignmentValues());
  });
  /*
    Keypress listener, for parsing and using inputs to different textareas.
    Will get quite large as features such as lab requests are added.
  */
  $("textarea").blur(function() {
    saveWeek(getAssignmentValues());
  });
  $("textarea").keydown(function(e) {
    if ($(this).val().indexOf('snake') >= 0) {
      $('#snakebtn').show();
    }
    // If it's been more than 30 seconds since you've updated from this device
    var taID = this.id;
    if (new Date().getTime() - ref.lastUpdate.getTime() > 30000) {
      getWeek(function(assignments) {
        // replace the server's version of what you're working on with your version
        var newVersion = getAssignmentValues()[taID];
        assignments[taID] = newVersion;
        setAssignmentValues(assignments); // update the planner with the server's version of events.
        saveWeek(getAssignmentValues());
      });
    }
    if ($('#saveIndicator').children('span')[0].classList[1] == "glyphicon-ok-circle")
      $('#saveIndicator').children('span').attr("class", "glyphicon glyphicon-ban-circle").parent().attr("data-original-title", "Click to save data.");
    if (e.which == 13) {
      saveWeek(getAssignmentValues());
    } else if (e.which == 8) {
      if ($(this).text() == '') {
        $.ajax({
          method: 'POST',
          url: '/reminders',
          data: {
            box: taID,
            monday: ref.monday.toISOString().slice(0, 10)
          },
          statusCode: {
            200: function() {
              getReminders();
            }
          }
        });
      }
    }
  });

  /*
  Setting assignment as done
  */
  $('textarea').parent().mouseenter(function() {
    $(this).children(".tabuttons").show();
  });
  $('textarea').parent().mouseleave(function() {
     $(this).children(".tabuttons").hide();
  });
  $('button.done').unbind();
  $('button.done').click(function() {
    var t = $(this).parent().parent().children("textarea");
    if ($(t).css("text-decoration") == "none") {
      $(t).css("text-decoration", "line-through");
      $(t).parent().children(".tabuttons").children('.done').html('');
      $.ajax({
        method: 'POST',
        url: '/reminders',
        data: {
          box: t[0].id,
          monday: ref.monday.toISOString().slice(0, 10)
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    }
    else {
      $(t).css("text-decoration", "none");
      $(t).parent().children(".tabuttons").children('.done').html('');
    }
    saveWeek(getAssignmentValues());

  });

  $('.cc').unbind();
  $('.cc').click(function() { // if they click on teh color code
    var code = this.classList[0];
    var ta = $(this).parent().parent().parent().parent().children('textarea');
    ta.css("background-color", ref.settings.colorCode[code]); // set the background

    saveWeek(getAssignmentValues());
  });

  $('.reminderSet').unbind();
  $('.reminderSet').click(function() {
    var box = $(this).parent().parent().children('textarea');
    var daysBefore = '1';
    var prev = false; // flag to see if there's been a reminder set for this box already, so we can display right amount of days
    // search for reminder in array
    for (var i = 0; i < ref.reminders.length; i++) {
      if (ref.reminders[i].monday == ref.monday.toISOString().slice(0, 10) && ref.reminders[i].box == box[0].id) {
        daysBefore = ref.reminders[i].startRemindingNum || '1';
        prev = true;
      }
    }

    var max = 14;
    var html = 'x\
                Start reminding me\
                <input type="number" class="r" name="amountInput" value="'+daysBefore+'" style="width:35px;" disabled/>\
                days before.\
                <input type="range" name="amountRange" min="1" max="'+max+'" value="'+daysBefore+'" oninput="$(this).parent().children(\'input.r\').val(this.value)" />\
                <button class="btn btn-primary btn-xs reminderSubmit">'+(prev ? 'Update' : 'Submit')+'</button>\
                <button class="btn btn-danger  btn-xs reminderRemove">Remove</button>'

    $(box).popover({content: html, html: 'true', placement: 'top'}).popover('show');

    $('.reminderSubmit').unbind();
    $('.reminderSubmit').click(function() {
      var b = $(this).parent().parent().parent().children();
      $('.reminderSubmit').unbind();
      b.popover('destroy');
      var d = new Date(ref.monday.getFullYear(),
            ref.monday.getMonth(),
            ref.monday.getDate() + parseInt(box.attr('id').split('').reverse()[0]-1));
      var ccde = '';
      for (var prop in ref.settings.colorCode) {
        if(ref.settings.colorCode[prop] == box.css('background-color'))
          ccde = prop;
      }
      $.ajax({
        type: 'POST',
        url: '/reminders',
        data: {
          box: box.attr('id'),
          colorCode: ccde,
          monday: ref.monday.toISOString().slice(0, 10),
          description: box.val().escapeHTML(),
          options: {
            startReminding: parseInt($(this).parent().children('.r').val()),
            dueDate: d.toJSON(),
            interval: 1
          }
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    });
    $('.reminderCancel').unbind();
    $('.reminderCancel').click(function() {
      $('.reminderCancel').unbind();
      var b = $(this).parent().parent().parent().children();
      b.popover('destroy');
    });

    $('.reminderRemove').unbind();
    $('.reminderRemove').click(function() {
      var b = $(this).parent().parent().parent().children();
      b.popover('destroy');
      $.ajax({
        method: 'POST',
        url: '/reminders',
        data: {
          box: box[0].id,
          monday: ref.monday.toISOString().slice(0, 10)
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    });
  });

  /*
    Double tap/Double click for setting assignments as completed.
  */
  var isiOS = false;
  var agent = navigator.userAgent.toLowerCase();
  if(agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0 || agent.indexOf('android') >= 0) {
    isiOS = true;
  }

  if (isiOS) {
    var action;
    $('textarea').bind('touchend', function(event){
      var now = new Date().getTime();
      var lastTouch = $(this).data('lastTouch') || now + 1 /** the first time this will make delta a negative number */;
      var delta = now - lastTouch;
      clearTimeout(action);
      if (delta<500 && delta>0){
        if ($(this).css("text-decoration") == "none") {
          $(this).css("text-decoration", "line-through");
        }
        else {
          $(this).css("text-decoration", "none");
        }
      } else {
        $(this).data('lastTouch', now);
        action = setTimeout(function(e){
         // If this runs you can invoke your 'click/touchend' code
         clearTimeout(action);   // clear the timeout
        }, 500, [event]);
      }
      $(this).data('lastTouch', now);
    });
  }
}

function subjectListen() {
  $('.subj').unbind(); // When you add a subject, need to re-add all the listeners

  $('.subj').on('dblclick', '.subjectspan', function () {
    var input = $('<input />', {
      'type': 'text',
      'name': 'unique',
      'value': $(this).html()
    });
    $(this).parent().prepend(input);
    $(this).remove();
    input.focus();
    input.select();

    input.keydown(function(e) {
      if (e.keyCode == 13) {
        e.preventDefault();
        this.blur();
      }
    });
  });

 $('.subj').on('blur', 'input', function () {
    $(this).parent().prepend($('', {'class':'subjectspan'}).html($(this).val()));
    var id = $(this).parent().get(0).id;
    var subj = $(this).val();
    $(this).unbind();
    $(this).remove();
    if (id != 0) {
      $(this).prop('contenteditable', false); // make it not editable
      for (var i = 0; i < ref.settings.rows.length; i++) {
        if (ref.settings.rows[i][1] == id) {
          ref.settings.rows[i][0] = subj; // actually change the name
          break;
        }
      }
      // Save the new settings
      setSettings(ref.settings, function(data) {
        renderRows(ref.settings.rows);
      });
    }
  });

  $('input').keydown(function(e) {
  if (e.keycode == 13) {
    e.preventDefault();
    this.blur();
  }
  });

  // mouseover logic
  $('.subj').mouseenter(function() {
    $(this).children(".subjbtns").show();
  });
  $('.subj').mouseleave(function() {
     $(this).children(".subjbtns").hide();
  });

  $('button.delete').unbind();
  // delete subject
  $('button.delete').click(function() {
    var id = $(this).parent().parent()[0].id;
    if (confirm("Are you sure you want to delete " + ref.settings.rows[id-1] + "?")){
      for (var i = 0; i < ref.settings.rows.length; i++) {
        if (ref.settings.rows[i][1] == id) {
          ref.settings.rows.splice(i, 1); // splice out the row from settings
          break;
        }
      }
      // save
      setSettings(ref.settings, function(data) {
        renderRows(ref.settings.rows);
      });
    }
  });
  $('button.edit').unbind();
  $('button.edit').click(function() {
      $(this).parent().parent().children('.subjectspan').trigger('dblclick');
  });
}<commit_msg>made the easter egg happen on keyup so that you don't have to type a space after snake for it to work<commit_after>/*
  Event Handlers
*/
$('document').ready(function() {

  /*
    Planbook initialization
  */
  $.ajax({
    type: "GET",
    url: "/settings?json=true",
    data: {
      'settings': ref.settings
    },
    statusCode: {
      500: function() {
        alert("There's been a server error. Contact NLTL for assistance.");
      }
    },
    success: function(data) {
      $('li#username').children('a').text(data.name);
      ref.settings = data.settings;

      if (typeof(ref.settings.rows[0]) != "object") { // if it's the old settings format
        for (var i = 0; i < ref.settings.rows.length; i++)
          ref.settings.rows[i] = [ref.settings.rows[i], i+1];
        setSettings(ref.settings, function() {});
      }
      renderRows(ref.settings.rows);
    }
  });

  /*
    Navigation Buttons
  */
  $('#save').click(function() {
    saveWeek(getAssignmentValues());
  });
  $('#back').click(function() {

    if (!ref.turnInProgress) {
      ref.turnInProgress = true;
      // animation
      saveWeek(getAssignmentValues()); // save the current state
      ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() - 7); // decrement by 1 week
      getWeek(function(o) {
        $('#sidebar').slide($(window).width(), 200);
        $("#planner").slide($(window).width(), 200, function() {
          setAssignmentValues(o);
          ref.turnInProgress = false;
        });
      });
    }
  });
  $('#next').click(function() {
    if (!ref.turnInProgress) {
      ref.turnInProgress = true;
      saveWeek(getAssignmentValues());
      ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() + 7);

      getWeek(function(o) {
        $('#sidebar').slide(-$(window).width(), 200);
        $("#planner").slide(-$(window).width(), 200, function() {
          setAssignmentValues(o);
          ref.turnInProgress = false;
        });
      });
    }
  });

  $(document).bind('keydown', 'meta+s', function(e) {
    e.preventDefault();
    saveWeek(getAssignmentValues());
  });

  $(document).bind('keydown', 'meta+right', function(e) {
    e.preventDefault();
    $('#next').click();
  });
  $(document).bind('keydown', 'meta+left', function(e) {
    e.preventDefault();
    $('#back').click();
  });

  // Mobile navigation buttons
  $('#msave').click(function() {
    saveWeek(getAssignmentValues());
  });
  $('#mback').click(function() {
    // animation
    saveWeek(getAssignmentValues()); // save the current state
    ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() - 7); // decrement by 1 week
    getWeek(setAssignmentValues);
    drawDates()
  });
  $('#mnext').click(function() {
    saveWeek(getAssignmentValues());
    ref.monday = new Date(ref.monday.getFullYear(), ref.monday.getMonth(), ref.monday.getDate() + 7);
    getWeek(setAssignmentValues);
    drawDates();
  });
  $('#mdays').change(function() {
    $('#' + ref.visibleDay).hide();
    $('#' + $("select option:selected").text()).show();
    ref.visibleDay = $( "select option:selected" ).text();
  });

  // add subject
  $('button#add').click(function() {
    // save
    var id = 0;
    for (var i = 0; i < ref.settings.rows.length; i++) {
      if (ref.settings.rows[i][1] >= id) {
        id = parseInt(ref.settings.rows[i][1])+1
      }
    }
    ref.settings.rows.push(["Class", id]);
    setSettings(ref.settings, function(data) {
      renderRows(ref.settings.rows);
      $('.subj#'+id).children('.subjectspan').trigger('dblclick');
    });
  });
  taListen();
  subjectListen();
});

function taListen() {
  $("textarea").unbind();
  $("textarea").bind('keydown', 'meta+s', function(e) {
    e.preventDefault();
    saveWeek(getAssignmentValues());
  });
  /*
    Keypress listener, for parsing and using inputs to different textareas.
    Will get quite large as features such as lab requests are added.
  */
  $("textarea").blur(function() {
    saveWeek(getAssignmentValues());
  });

  $("textarea").keyup(function(e) {
    if ($(this).val().indexOf('snake') >= 0) {
      $('#snakebtn').show();
    }
  });

  $("textarea").keydown(function(e) {
    // If it's been more than 30 seconds since you've updated from this device
    var taID = this.id;
    if (new Date().getTime() - ref.lastUpdate.getTime() > 30000) {
      getWeek(function(assignments) {
        // replace the server's version of what you're working on with your version
        var newVersion = getAssignmentValues()[taID];
        assignments[taID] = newVersion;
        setAssignmentValues(assignments); // update the planner with the server's version of events.
        saveWeek(getAssignmentValues());
      });
    }
    if ($('#saveIndicator').children('span')[0].classList[1] == "glyphicon-ok-circle")
      $('#saveIndicator').children('span').attr("class", "glyphicon glyphicon-ban-circle").parent().attr("data-original-title", "Click to save data.");
    if (e.which == 13) {
      saveWeek(getAssignmentValues());
    } else if (e.which == 8) {
      if ($(this).text() == '') {
        $.ajax({
          method: 'POST',
          url: '/reminders',
          data: {
            box: taID,
            monday: ref.monday.toISOString().slice(0, 10)
          },
          statusCode: {
            200: function() {
              getReminders();
            }
          }
        });
      }
    }
  });

  /*
  Setting assignment as done
  */
  $('textarea').parent().mouseenter(function() {
    $(this).children(".tabuttons").show();
  });
  $('textarea').parent().mouseleave(function() {
     $(this).children(".tabuttons").hide();
  });
  $('button.done').unbind();
  $('button.done').click(function() {
    var t = $(this).parent().parent().children("textarea");
    if ($(t).css("text-decoration") == "none") {
      $(t).css("text-decoration", "line-through");
      $(t).parent().children(".tabuttons").children('.done').html('');
      $.ajax({
        method: 'POST',
        url: '/reminders',
        data: {
          box: t[0].id,
          monday: ref.monday.toISOString().slice(0, 10)
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    }
    else {
      $(t).css("text-decoration", "none");
      $(t).parent().children(".tabuttons").children('.done').html('');
    }
    saveWeek(getAssignmentValues());

  });

  $('.cc').unbind();
  $('.cc').click(function() { // if they click on teh color code
    var code = this.classList[0];
    var ta = $(this).parent().parent().parent().parent().children('textarea');
    ta.css("background-color", ref.settings.colorCode[code]); // set the background

    saveWeek(getAssignmentValues());
  });

  $('.reminderSet').unbind();
  $('.reminderSet').click(function() {
    var box = $(this).parent().parent().children('textarea');
    var daysBefore = '1';
    var prev = false; // flag to see if there's been a reminder set for this box already, so we can display right amount of days
    // search for reminder in array
    for (var i = 0; i < ref.reminders.length; i++) {
      if (ref.reminders[i].monday == ref.monday.toISOString().slice(0, 10) && ref.reminders[i].box == box[0].id) {
        daysBefore = ref.reminders[i].startRemindingNum || '1';
        prev = true;
      }
    }

    var max = 14;
    var html = 'x\
                Start reminding me\
                <input type="number" class="r" name="amountInput" value="'+daysBefore+'" style="width:35px;" disabled/>\
                days before.\
                <input type="range" name="amountRange" min="1" max="'+max+'" value="'+daysBefore+'" oninput="$(this).parent().children(\'input.r\').val(this.value)" />\
                <button class="btn btn-primary btn-xs reminderSubmit">'+(prev ? 'Update' : 'Submit')+'</button>\
                <button class="btn btn-danger  btn-xs reminderRemove">Remove</button>'

    $(box).popover({content: html, html: 'true', placement: 'top'}).popover('show');

    $('.reminderSubmit').unbind();
    $('.reminderSubmit').click(function() {
      var b = $(this).parent().parent().parent().children();
      $('.reminderSubmit').unbind();
      b.popover('destroy');
      var d = new Date(ref.monday.getFullYear(),
            ref.monday.getMonth(),
            ref.monday.getDate() + parseInt(box.attr('id').split('').reverse()[0]-1));
      var ccde = '';
      for (var prop in ref.settings.colorCode) {
        if(ref.settings.colorCode[prop] == box.css('background-color'))
          ccde = prop;
      }
      $.ajax({
        type: 'POST',
        url: '/reminders',
        data: {
          box: box.attr('id'),
          colorCode: ccde,
          monday: ref.monday.toISOString().slice(0, 10),
          description: box.val().escapeHTML(),
          options: {
            startReminding: parseInt($(this).parent().children('.r').val()),
            dueDate: d.toJSON(),
            interval: 1
          }
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    });
    $('.reminderCancel').unbind();
    $('.reminderCancel').click(function() {
      $('.reminderCancel').unbind();
      var b = $(this).parent().parent().parent().children();
      b.popover('destroy');
    });

    $('.reminderRemove').unbind();
    $('.reminderRemove').click(function() {
      var b = $(this).parent().parent().parent().children();
      b.popover('destroy');
      $.ajax({
        method: 'POST',
        url: '/reminders',
        data: {
          box: box[0].id,
          monday: ref.monday.toISOString().slice(0, 10)
        },
        statusCode: {
          200: function() {
            getReminders();
          }
        }
      });
    });
  });

  /*
    Double tap/Double click for setting assignments as completed.
  */
  var isiOS = false;
  var agent = navigator.userAgent.toLowerCase();
  if(agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0 || agent.indexOf('android') >= 0) {
    isiOS = true;
  }

  if (isiOS) {
    var action;
    $('textarea').bind('touchend', function(event){
      var now = new Date().getTime();
      var lastTouch = $(this).data('lastTouch') || now + 1 /** the first time this will make delta a negative number */;
      var delta = now - lastTouch;
      clearTimeout(action);
      if (delta<500 && delta>0){
        if ($(this).css("text-decoration") == "none") {
          $(this).css("text-decoration", "line-through");
        }
        else {
          $(this).css("text-decoration", "none");
        }
      } else {
        $(this).data('lastTouch', now);
        action = setTimeout(function(e){
         // If this runs you can invoke your 'click/touchend' code
         clearTimeout(action);   // clear the timeout
        }, 500, [event]);
      }
      $(this).data('lastTouch', now);
    });
  }
}

function subjectListen() {
  $('.subj').unbind(); // When you add a subject, need to re-add all the listeners

  $('.subj').on('dblclick', '.subjectspan', function () {
    var input = $('<input />', {
      'type': 'text',
      'name': 'unique',
      'value': $(this).html()
    });
    $(this).parent().prepend(input);
    $(this).remove();
    input.focus();
    input.select();

    input.keydown(function(e) {
      if (e.keyCode == 13) {
        e.preventDefault();
        this.blur();
      }
    });
  });

 $('.subj').on('blur', 'input', function () {
    $(this).parent().prepend($('', {'class':'subjectspan'}).html($(this).val()));
    var id = $(this).parent().get(0).id;
    var subj = $(this).val();
    $(this).unbind();
    $(this).remove();
    if (id != 0) {
      $(this).prop('contenteditable', false); // make it not editable
      for (var i = 0; i < ref.settings.rows.length; i++) {
        if (ref.settings.rows[i][1] == id) {
          ref.settings.rows[i][0] = subj; // actually change the name
          break;
        }
      }
      // Save the new settings
      setSettings(ref.settings, function(data) {
        renderRows(ref.settings.rows);
      });
    }
  });

  $('input').keydown(function(e) {
  if (e.keycode == 13) {
    e.preventDefault();
    this.blur();
  }
  });

  // mouseover logic
  $('.subj').mouseenter(function() {
    $(this).children(".subjbtns").show();
  });
  $('.subj').mouseleave(function() {
     $(this).children(".subjbtns").hide();
  });

  $('button.delete').unbind();
  // delete subject
  $('button.delete').click(function() {
    var id = $(this).parent().parent()[0].id;
    if (confirm("Are you sure you want to delete " + ref.settings.rows[id-1] + "?")){
      for (var i = 0; i < ref.settings.rows.length; i++) {
        if (ref.settings.rows[i][1] == id) {
          ref.settings.rows.splice(i, 1); // splice out the row from settings
          break;
        }
      }
      // save
      setSettings(ref.settings, function(data) {
        renderRows(ref.settings.rows);
      });
    }
  });
  $('button.edit').unbind();
  $('button.edit').click(function() {
      $(this).parent().parent().children('.subjectspan').trigger('dblclick');
  });
}<|endoftext|>


<commit_before>var https = require('https');
module.exports = {
	check: function(user_id, user_access_token, app_access_token, callback) {

		if (!user_id || !user_access_token || !app_access_token) {
				callback(false);
		}

		var options = {
			host: 'graph.facebook.com',
			path: '/debug_token?input_token=' +	user_access_token + '&access_token=' + app_access_token
		};

		https.get(options, function(res) {
			var string_data = '';

			res.on('data', function(chunk) {
				string_data += chunk;
			});

			res.on('end', function() {
				var json_data = JSON.parse(string_data);
				if (json_data.data && json_data.data.is_valid && json_data.data.user_id == user_id) {
					callback(true);
				} else {
					callback(false);
				}
			});
		});
};
<commit_msg>Reformat index.js<commit_after>var https = require('https');

/**
 * Validate Facebook access token
 *
 * @param	{String} user_id, user_access_token, app_access_token
 * @return {bool}
 */
module.exports = {
	check: function(user_id, user_access_token, app_access_token, callback) {

		if (!user_id || !user_access_token || !app_access_token) {
				callback(false);
		}

		var options = {
			host: 'graph.facebook.com',
			path: '/debug_token?input_token=' +	user_access_token + '&access_token=' + app_access_token
		};

		https.get(options, function(res) {
			var string_data = '';

			res.on('data', function(chunk) {
				string_data += chunk;
			});

			res.on('end', function() {
				var json_data = JSON.parse(string_data);
				if (json_data.data && json_data.data.is_valid && json_data.data.user_id == user_id) {
					callback(true);
				} else {
					callback(false);
				}
			});
		});
	}
};
<|endoftext|>


<commit_before>var session = null, picker;

// instead of windows.onload
$(document).ready( function() {
    // hide iphone/ipad URL bar
    setTimeout(function() { window.scrollTo(0, 1) }, 100);

    // initialize zoness
    session = new Session(
        SESSION_TYPE_DRAW,
        function() {
            //console.log("page_draw/ready: session callback ok");

            var board = new Board( session, 'session-board');
            var drawing = new Editor(session, board, 'session-drawing');
            var chat = new Chat(session);

            //console.log("page_draw/ready: prepicker");
            $("#brush").click(function(event){
                event.preventDefault();
                var firstClick = false;
                if (undefined === picker) {
                    picker = new Color.Picker({
                        size: Math.floor($(window).width() / 3),
                        callback: function(hex) {
                            drawing.color_set( "#" + hex );
                        }
                    });
                    picker.el.style.bottom = "50px";
                    picker.el.style.left = "10px";
                    firstClick = true;
                    $("#brush-action").text("Hide");
                }
                if (true === $(picker.el).is(":hidden")) {
                    $(picker.el).show();
                    $("#brush-action").text("Hide");
                } else if (!firstClick) {
                    $(picker.el).hide();
                    $("#brush-action").text("Show");
                }
            });
        }
    );
});
<commit_msg>Initialize the color picker on startup but hide it, so the editor get the correct color.<commit_after>var session = null;

// instead of windows.onload
$(document).ready( function() {
    // hide iphone/ipad URL bar
    setTimeout(function() { window.scrollTo(0, 1) }, 100);

    // initialize zoness
    session = new Session(
        SESSION_TYPE_DRAW,
        function() {
            //console.log("page_draw/ready: session callback ok");

            var board = new Board( session, 'session-board');
            var drawing = new Editor(session, board, 'session-drawing');
            var chat = new Chat(session),
            picker = new Color.Picker({
                size: Math.floor($(window).width() / 3),
                callback: function(hex) {
                    drawing.color_set( "#" + hex );
                }
            });
            $(picker.el).hide(); // hide color picker on startup
            picker.el.style.bottom = "50px";
            picker.el.style.left = "10px";

            //console.log("page_draw/ready: prepicker");
            $("#brush").click(function(event){
                event.preventDefault();
                if (true === $(picker.el).is(":hidden")) {
                    $(picker.el).show();
                    $("#brush-action").text("Hide");
                } else {
                    $(picker.el).hide();
                    $("#brush-action").text("Show");
                }
            });
        }
    );
});
<|endoftext|>


<commit_before>var level = require('level')
var rimraf = require('rimraf')
var os = require('os')
var path = require('path')

function tmpdir () {
  return os.tmpdir ? os.tmpdir() : process.env.TMPDIR
}

module.exports = function () {

  return function (name, opts, cb) {
    name = name || 'db_' + Date.now()
    var dir = path.join(tmpdir(), name)
    rimraf.sync(dir)
    return level(dir, opts, cb)
  }

}

<commit_msg>optionally do not delete<commit_after>var level = require('level')
var rimraf = require('rimraf')
var os = require('os')
var path = require('path')

function tmpdir () {
  return os.tmpdir ? os.tmpdir() : process.env.TMPDIR
}

module.exports = function (opts) {
  opts = opts || {}
  return function (name, opts, cb) {
    name = name || 'db_' + Date.now()
    var dir = path.join(tmpdir(), name)
    if(opts.clean !== false)
      rimraf.sync(dir)
    return level(dir, opts, cb)
  }

}

<|endoftext|>