<commit_before>const BinaryPjax          = require('./binary_pjax');
const Client              = require('./client');
const GTM                 = require('./gtm');
const localize            = require('./localize').localize;
const Login               = require('./login');
const State               = require('./storage').State;
const urlFor              = require('./url').urlFor;
const isEmptyObject       = require('./utility').isEmptyObject;
const checkClientsCountry = require('../common_functions/country_base').checkClientsCountry;
const jpClient            = require('../common_functions/country_base').jpClient;
const BinarySocket        = require('../websocket_pages/socket');
const MetaTrader          = require('../websocket_pages/user/metatrader/metatrader');

const Header = (() => {
    'use strict';

    const onLoad = () => {
        showOrHideLoginForm();
        bindClick();
        if (!Login.isLoginPages()) {
            checkClientsCountry();
        }
        if (Client.isLoggedIn()) {
            $('ul#menu-top').addClass('smaller-font');
            displayAccountStatus();
        }
    };

    const bindClick = () => {
        $('#logo').off('click').on('click', () => {
            BinaryPjax.load(urlFor(Client.isLoggedIn() ? (jpClient() ? 'multi_barriers_trading' : 'trading') : ''));
        });
        $('#btn_login').off('click').on('click', (e) => {
            e.preventDefault();
            Login.redirectToLogin();
        });
        $('a.logout').off('click').on('click', () => {
            Client.sendLogoutRequest();
        });
    };

    const showOrHideLoginForm = () => {
        if (!Client.isLoggedIn()) return;
        const loginid_select = $('<div/>');
        const loginid_array = Client.get('loginid_array');
        loginid_array.forEach((client) => {
            if (!client.disabled) {
                let type = 'Virtual';
                if (client.real) {
                    if (client.financial)          type = 'Investment';
                    else if (client.non_financial) type = 'Gaming';
                    else                           type = 'Real';
                }
                type += ' Account';

                const curr_id = client.id;
                const localized_type = localize(type);
                if (curr_id === Client.get('loginid')) { // default account
                    $('.account-type').html(localized_type);
                    $('.account-id').html(curr_id);
                } else {
                    loginid_select.append($('<a/>', { href: `${'java'}${'script:;'}`, 'data-value': curr_id })
                        .append($('<li/>', { text: localized_type }).append($('<div/>', { text: curr_id }))))
                        .append($('<div/>', { class: 'separator-line-thin-gray' }));
                }
            }
        });
        let $this;
        $('.login-id-list').html(loginid_select)
            .find('a').off('click')
            .on('click', function(e) {
                e.preventDefault();
                $this = $(this);
                $this.attr('disabled', 'disabled');
                switchLoginid($this.attr('data-value'));
            });
    };

    const metatraderMenuItemVisibility = (landing_company_response) => {
        if (MetaTrader.isEligible(landing_company_response)) {
            $('#all-accounts').find('#user_menu_metatrader').setVisibility(1);
        }
    };

    const switchLoginid = (loginid) => {
        if (!loginid || loginid.length === 0) return;
        const token = Client.getToken(loginid);
        if (!token || token.length === 0) {
            Client.sendLogoutRequest(true);
            return;
        }

        // cleaning the previous values
        Client.clear();
        sessionStorage.setItem('active_tab', '1');
        // set cookies: loginid, login
        Client.setCookie('loginid', loginid);
        Client.setCookie('login',   token);
        // set local storage
        GTM.setLoginFlag();
        localStorage.setItem('active_loginid', loginid);
        $('.login-id-list a').removeAttr('disabled');
        window.location.reload();
    };

    const upgradeMessageVisibility = () => {
        BinarySocket.wait('authorize', 'landing_company', 'get_settings').then(() => {
            const landing_company = State.get(['response', 'landing_company', 'landing_company']);
            const loginid_array = Client.get('loginid_array');

            const $upgrade_msg = $('.upgrademessage');

            const showUpgrade = (url, msg) => {
                $upgrade_msg.setVisibility(1)
                    .find('a').setVisibility(1)
                    .attr('href', urlFor(url))
                    .html($('<span/>', { text: localize(msg) }));
            };

            if (Client.get('is_virtual')) {
                const show_upgrade_msg = !loginid_array.some(client => client.real);

                $upgrade_msg.setVisibility(1)
                    .find('> span').setVisibility(1).end()
                    .find('a')
                    .setVisibility(0);

                const jp_account_status = (State.get(['response', 'get_settings', 'get_settings', 'jp_account_status']) || {}).status;
                if (jp_account_status && show_upgrade_msg) {
                    if (/jp_knowledge_test_(pending|fail)/.test(jp_account_status)) { // do not show upgrade for user that filled up form
                        showUpgrade('/new_account/knowledge_testws', '{JAPAN ONLY}Take knowledge test');
                    } else {
                        $upgrade_msg.setVisibility(1);
                        if (jp_account_status === 'jp_activation_pending') {
                            if ($('.activation-message').length === 0) {
                                $('#virtual-text').append($('<div/>', { class: 'activation-message', text: ` ${localize('Your Application is Being Processed.')}` }));
                            }
                        } else if (jp_account_status === 'activated') {
                            if ($('.activated-message').length === 0) {
                                $('#virtual-text').append($('<div/>', { class: 'activated-message', text: ` ${localize('{JAPAN ONLY}Your Application has Been Processed. Please Re-Login to Access Your Real-Money Account.')}` }));
                            }
                        }
                    }
                } else if (show_upgrade_msg) {
                    $upgrade_msg.find('> span').setVisibility(1);
                    if (Client.canUpgradeVirtualToFinancial(landing_company)) {
                        showUpgrade('new_account/maltainvestws', 'Upgrade to a Financial Account');
                    } else if (Client.canUpgradeVirtualToJapan(landing_company)) {
                        showUpgrade('new_account/japanws', 'Upgrade to a Real Account');
                    } else {
                        showUpgrade('new_account/realws', 'Upgrade to a Real Account');
                    }
                } else {
                    $upgrade_msg.find('a').setVisibility(0).html('');
                }
            } else {
                let show_financial = false;
                // also allow UK MLT client to open MF account
                if (Client.canUpgradeGamingToFinancial(landing_company) || (Client.get('residence') === 'gb' && /^MLT/.test(Client.get('loginid')))) {
                    show_financial = !loginid_array.some(client => client.financial);
                }
                if (show_financial) {
                    $('#virtual-text').parent().setVisibility(0);
                    showUpgrade('new_account/maltainvestws', 'Open a Financial Account');
                } else {
                    $upgrade_msg.setVisibility(0);
                }
            }
        });
    };

    const displayNotification = (message, is_error, msg_code = '') => {
        const $msg_notification = $('#msg_notification');
        $msg_notification.html(message).attr({ 'data-message': message, 'data-code': msg_code });
        if ($msg_notification.is(':hidden')) $msg_notification.removeClass('error').slideDown(500, () => { if (is_error) $msg_notification.addClass('error'); });
    };

    const hideNotification = (msg_code) => {
        const $msg_notification = $('#msg_notification');
        if (msg_code && $msg_notification.attr('data-code') !== msg_code) return;
        if ($msg_notification.is(':visible')) $msg_notification.removeClass('error').slideUp(500, () => { $msg_notification.html('').removeAttr('data-message'); });
    };

    const displayAccountStatus = () => {
        BinarySocket.wait('authorize').then(() => {
            let get_account_status,
                status,
                should_authenticate = false;

            const costarica_landing_company = /costarica/.test(Client.get('landing_company_name'));

            const riskAssessment = () => {
                if (get_account_status.risk_classification === 'high') {
                    return isEmptyObject(State.get(['response', 'get_financial_assessment', 'get_financial_assessment']));
                }
                return false;
            };

            const authenticate = () => {
                // don't show age verification check for costarica clients
                const should_age_verify = !/age_verification/.test(status) && !costarica_landing_company;
                return (!/authenticated/.test(status) || should_age_verify) && !jpClient() && should_authenticate;
            };

            const buildMessage = (string, path, hash = '') => localize(string, [`<a href="${urlFor(path)}${hash}">`, '</a>']);

            const messages = {
                authenticate   : () => buildMessage('[_1]Authenticate your account[_2] now to take full advantage of all withdrawal options available.',        'user/authenticate'),
                financial_limit: () => buildMessage('Please set your 30-day turnover limit in our [_1]self-exclusion facilities[_2] to remove deposit limits.', 'user/security/self_exclusionws', '#max_30day_turnover'),
                residence      : () => buildMessage('Please set [_1]country of residence[_2] before upgrading to a real-money account.',                        'user/settings/detailsws'),
                risk           : () => buildMessage('Please complete the [_1]financial assessment form[_2] to lift your withdrawal and trading limits.',        'user/settings/assessmentws'),
                tax            : () => buildMessage('Please [_1]complete your account profile[_2] to lift your withdrawal and trading limits.',                 'user/settings/detailsws'),
                tnc            : () => buildMessage('Please [_1]accept the updated Terms and Conditions[_2] to lift your withdrawal and trading limits.',       'user/tnc_approvalws'),
                unwelcome      : () => buildMessage('Your account is restricted. Kindly [_1]contact customer support[_2] for assistance.',                      'contact'),
            };

            const validations = {
                authenticate   : () => authenticate(),
                financial_limit: () => /ukrts_max_turnover_limit_not_set/.test(status),
                residence      : () => !Client.get('residence'),
                risk           : () => riskAssessment(),
                tax            : () => Client.shouldCompleteTax(),
                tnc            : () => Client.shouldAcceptTnc(),
                unwelcome      : () => /(unwelcome|(cashier|withdrawal)_locked)/.test(status),
            };

            // real account checks in order
            const check_statuses_real = [
                'tnc',
                'financial_limit',
                'risk',
                'tax',
                'authenticate',
                'unwelcome',
            ];

            // virtual checks
            const check_statuses_virtual = [
                'residence',
            ];

            const checkStatus = (check_statuses) => {
                const notified = check_statuses.some((check_type) => {
                    if (validations[check_type]()) {
                        displayNotification(messages[check_type]());
                        return true;
                    }
                    return false;
                });
                if (!notified) hideNotification();
            };

            if (Client.get('is_virtual')) {
                checkStatus(check_statuses_virtual);
            } else {
                BinarySocket.wait('website_status', 'get_account_status', 'get_settings', 'get_financial_assessment', 'balance').then(() => {
                    get_account_status = State.get(['response', 'get_account_status', 'get_account_status']) || {};
                    status = get_account_status.status;
                    if (costarica_landing_company && +Client.get('balance') < 200) {
                        BinarySocket.send({ mt5_login_list: 1 }).then((response) => {
                            if (response.mt5_login_list.length) {
                                should_authenticate = true;
                            }
                            checkStatus(check_statuses_real);
                        });
                    } else {
                        should_authenticate = true;
                        checkStatus(check_statuses_real);
                    }
                });
            }
        });
    };

    return {
        onLoad: onLoad,

        upgradeMessageVisibility    : upgradeMessageVisibility,
        metatraderMenuItemVisibility: metatraderMenuItemVisibility,
        displayNotification         : displayNotification,
        hideNotification            : hideNotification,
        displayAccountStatus        : displayAccountStatus,
    };
})();

module.exports = Header;
<commit_msg>Remove attribute<commit_after>const BinaryPjax          = require('./binary_pjax');
const Client              = require('./client');
const GTM                 = require('./gtm');
const localize            = require('./localize').localize;
const Login               = require('./login');
const State               = require('./storage').State;
const urlFor              = require('./url').urlFor;
const isEmptyObject       = require('./utility').isEmptyObject;
const checkClientsCountry = require('../common_functions/country_base').checkClientsCountry;
const jpClient            = require('../common_functions/country_base').jpClient;
const BinarySocket        = require('../websocket_pages/socket');
const MetaTrader          = require('../websocket_pages/user/metatrader/metatrader');

const Header = (() => {
    'use strict';

    const onLoad = () => {
        showOrHideLoginForm();
        bindClick();
        if (!Login.isLoginPages()) {
            checkClientsCountry();
        }
        if (Client.isLoggedIn()) {
            $('ul#menu-top').addClass('smaller-font');
            displayAccountStatus();
        }
    };

    const bindClick = () => {
        $('#logo').off('click').on('click', () => {
            BinaryPjax.load(urlFor(Client.isLoggedIn() ? (jpClient() ? 'multi_barriers_trading' : 'trading') : ''));
        });
        $('#btn_login').off('click').on('click', (e) => {
            e.preventDefault();
            Login.redirectToLogin();
        });
        $('a.logout').off('click').on('click', () => {
            Client.sendLogoutRequest();
        });
    };

    const showOrHideLoginForm = () => {
        if (!Client.isLoggedIn()) return;
        const loginid_select = $('<div/>');
        const loginid_array = Client.get('loginid_array');
        loginid_array.forEach((client) => {
            if (!client.disabled) {
                let type = 'Virtual';
                if (client.real) {
                    if (client.financial)          type = 'Investment';
                    else if (client.non_financial) type = 'Gaming';
                    else                           type = 'Real';
                }
                type += ' Account';

                const curr_id = client.id;
                const localized_type = localize(type);
                if (curr_id === Client.get('loginid')) { // default account
                    $('.account-type').html(localized_type);
                    $('.account-id').html(curr_id);
                } else {
                    loginid_select.append($('<a/>', { href: `${'java'}${'script:;'}`, 'data-value': curr_id })
                        .append($('<li/>', { text: localized_type }).append($('<div/>', { text: curr_id }))))
                        .append($('<div/>', { class: 'separator-line-thin-gray' }));
                }
            }
        });
        let $this;
        $('.login-id-list').html(loginid_select)
            .find('a').off('click')
            .on('click', function(e) {
                e.preventDefault();
                $this = $(this);
                $this.attr('disabled', 'disabled');
                switchLoginid($this.attr('data-value'));
            });
    };

    const metatraderMenuItemVisibility = (landing_company_response) => {
        if (MetaTrader.isEligible(landing_company_response)) {
            $('#all-accounts').find('#user_menu_metatrader').setVisibility(1);
        }
    };

    const switchLoginid = (loginid) => {
        if (!loginid || loginid.length === 0) return;
        const token = Client.getToken(loginid);
        if (!token || token.length === 0) {
            Client.sendLogoutRequest(true);
            return;
        }

        // cleaning the previous values
        Client.clear();
        sessionStorage.setItem('active_tab', '1');
        // set cookies: loginid, login
        Client.setCookie('loginid', loginid);
        Client.setCookie('login',   token);
        // set local storage
        GTM.setLoginFlag();
        localStorage.setItem('active_loginid', loginid);
        $('.login-id-list a').removeAttr('disabled');
        window.location.reload();
    };

    const upgradeMessageVisibility = () => {
        BinarySocket.wait('authorize', 'landing_company', 'get_settings').then(() => {
            const landing_company = State.get(['response', 'landing_company', 'landing_company']);
            const loginid_array = Client.get('loginid_array');

            const $upgrade_msg = $('.upgrademessage');

            const showUpgrade = (url, msg) => {
                $upgrade_msg.setVisibility(1)
                    .find('a').setVisibility(1)
                    .attr('href', urlFor(url))
                    .html($('<span/>', { text: localize(msg) }));
            };

            if (Client.get('is_virtual')) {
                const show_upgrade_msg = !loginid_array.some(client => client.real);

                $upgrade_msg.setVisibility(1)
                    .find('> span').setVisibility(1).end()
                    .find('a')
                    .setVisibility(0);

                const jp_account_status = (State.get(['response', 'get_settings', 'get_settings', 'jp_account_status']) || {}).status;
                if (jp_account_status && show_upgrade_msg) {
                    if (/jp_knowledge_test_(pending|fail)/.test(jp_account_status)) { // do not show upgrade for user that filled up form
                        showUpgrade('/new_account/knowledge_testws', '{JAPAN ONLY}Take knowledge test');
                    } else {
                        $upgrade_msg.setVisibility(1);
                        if (jp_account_status === 'jp_activation_pending') {
                            if ($('.activation-message').length === 0) {
                                $('#virtual-text').append($('<div/>', { class: 'activation-message', text: ` ${localize('Your Application is Being Processed.')}` }));
                            }
                        } else if (jp_account_status === 'activated') {
                            if ($('.activated-message').length === 0) {
                                $('#virtual-text').append($('<div/>', { class: 'activated-message', text: ` ${localize('{JAPAN ONLY}Your Application has Been Processed. Please Re-Login to Access Your Real-Money Account.')}` }));
                            }
                        }
                    }
                } else if (show_upgrade_msg) {
                    $upgrade_msg.find('> span').setVisibility(1);
                    if (Client.canUpgradeVirtualToFinancial(landing_company)) {
                        showUpgrade('new_account/maltainvestws', 'Upgrade to a Financial Account');
                    } else if (Client.canUpgradeVirtualToJapan(landing_company)) {
                        showUpgrade('new_account/japanws', 'Upgrade to a Real Account');
                    } else {
                        showUpgrade('new_account/realws', 'Upgrade to a Real Account');
                    }
                } else {
                    $upgrade_msg.find('a').setVisibility(0).html('');
                }
            } else {
                let show_financial = false;
                // also allow UK MLT client to open MF account
                if (Client.canUpgradeGamingToFinancial(landing_company) || (Client.get('residence') === 'gb' && /^MLT/.test(Client.get('loginid')))) {
                    show_financial = !loginid_array.some(client => client.financial);
                }
                if (show_financial) {
                    $('#virtual-text').parent().setVisibility(0);
                    showUpgrade('new_account/maltainvestws', 'Open a Financial Account');
                } else {
                    $upgrade_msg.setVisibility(0);
                }
            }
        });
    };

    const displayNotification = (message, is_error, msg_code = '') => {
        const $msg_notification = $('#msg_notification');
        $msg_notification.html(message).attr({ 'data-message': message, 'data-code': msg_code });
        if ($msg_notification.is(':hidden')) $msg_notification.removeClass('error').slideDown(500, () => { if (is_error) $msg_notification.addClass('error'); });
    };

    const hideNotification = (msg_code) => {
        const $msg_notification = $('#msg_notification');
        if (msg_code && $msg_notification.attr('data-code') !== msg_code) return;
        if ($msg_notification.is(':visible')) $msg_notification.removeClass('error').slideUp(500, () => { $msg_notification.html('').removeAttr('data-message data-code'); });
    };

    const displayAccountStatus = () => {
        BinarySocket.wait('authorize').then(() => {
            let get_account_status,
                status,
                should_authenticate = false;

            const costarica_landing_company = /costarica/.test(Client.get('landing_company_name'));

            const riskAssessment = () => {
                if (get_account_status.risk_classification === 'high') {
                    return isEmptyObject(State.get(['response', 'get_financial_assessment', 'get_financial_assessment']));
                }
                return false;
            };

            const authenticate = () => {
                // don't show age verification check for costarica clients
                const should_age_verify = !/age_verification/.test(status) && !costarica_landing_company;
                return (!/authenticated/.test(status) || should_age_verify) && !jpClient() && should_authenticate;
            };

            const buildMessage = (string, path, hash = '') => localize(string, [`<a href="${urlFor(path)}${hash}">`, '</a>']);

            const messages = {
                authenticate   : () => buildMessage('[_1]Authenticate your account[_2] now to take full advantage of all withdrawal options available.',        'user/authenticate'),
                financial_limit: () => buildMessage('Please set your 30-day turnover limit in our [_1]self-exclusion facilities[_2] to remove deposit limits.', 'user/security/self_exclusionws', '#max_30day_turnover'),
                residence      : () => buildMessage('Please set [_1]country of residence[_2] before upgrading to a real-money account.',                        'user/settings/detailsws'),
                risk           : () => buildMessage('Please complete the [_1]financial assessment form[_2] to lift your withdrawal and trading limits.',        'user/settings/assessmentws'),
                tax            : () => buildMessage('Please [_1]complete your account profile[_2] to lift your withdrawal and trading limits.',                 'user/settings/detailsws'),
                tnc            : () => buildMessage('Please [_1]accept the updated Terms and Conditions[_2] to lift your withdrawal and trading limits.',       'user/tnc_approvalws'),
                unwelcome      : () => buildMessage('Your account is restricted. Kindly [_1]contact customer support[_2] for assistance.',                      'contact'),
            };

            const validations = {
                authenticate   : () => authenticate(),
                financial_limit: () => /ukrts_max_turnover_limit_not_set/.test(status),
                residence      : () => !Client.get('residence'),
                risk           : () => riskAssessment(),
                tax            : () => Client.shouldCompleteTax(),
                tnc            : () => Client.shouldAcceptTnc(),
                unwelcome      : () => /(unwelcome|(cashier|withdrawal)_locked)/.test(status),
            };

            // real account checks in order
            const check_statuses_real = [
                'tnc',
                'financial_limit',
                'risk',
                'tax',
                'authenticate',
                'unwelcome',
            ];

            // virtual checks
            const check_statuses_virtual = [
                'residence',
            ];

            const checkStatus = (check_statuses) => {
                const notified = check_statuses.some((check_type) => {
                    if (validations[check_type]()) {
                        displayNotification(messages[check_type]());
                        return true;
                    }
                    return false;
                });
                if (!notified) hideNotification();
            };

            if (Client.get('is_virtual')) {
                checkStatus(check_statuses_virtual);
            } else {
                BinarySocket.wait('website_status', 'get_account_status', 'get_settings', 'get_financial_assessment', 'balance').then(() => {
                    get_account_status = State.get(['response', 'get_account_status', 'get_account_status']) || {};
                    status = get_account_status.status;
                    if (costarica_landing_company && +Client.get('balance') < 200) {
                        BinarySocket.send({ mt5_login_list: 1 }).then((response) => {
                            if (response.mt5_login_list.length) {
                                should_authenticate = true;
                            }
                            checkStatus(check_statuses_real);
                        });
                    } else {
                        should_authenticate = true;
                        checkStatus(check_statuses_real);
                    }
                });
            }
        });
    };

    return {
        onLoad: onLoad,

        upgradeMessageVisibility    : upgradeMessageVisibility,
        metatraderMenuItemVisibility: metatraderMenuItemVisibility,
        displayNotification         : displayNotification,
        hideNotification            : hideNotification,
        displayAccountStatus        : displayAccountStatus,
    };
})();

module.exports = Header;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var result = require('./result');
var calc = require('../biz/calculate');
var recommend = require('../biz/recommend');
router.get('/info', function (req, res, next) {
    req.models.sick.get(req.param('id'), function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            req.models.doctor.get(data.doctor_id, function(err, doctor) {
                if (err) {
                    res.json(result(true, '', data));
                } else {
                    data.title = doctor.title;
                    res.json(result(true, '', data));
                }
            });

        }
    });
});

router.post('/create', function (req, res, next) {
    var sick = JSON.parse(req.param('sick'));
    var sick_name = sick.name, bed_id = sick.bed_id, doctor_id = sick.doctor_id, sick_id = sick.id;
    if (sick_id && sick_id > 0) {
        req.models.sick.get(sick_id, function (err, item) {
            if (err) {
                res.json(result(false,err.msg,err));
            } else {
                item.save(sick, function (err) {
                    if (err) {
                        res.json(result(false, err.msg, {}));
                    } else {
                        res.json(result(true, '', item));
                    }
                });
            }
        });
    } else if (sick.name && sick.bed_id && doctor_id) {
        req.models.sick.find({name: sick_name, bed_id: bed_id, doctor_id: doctor_id}, function (err, data) {
            if (!err && data && data.length > 0) {
                //merge info
                sick.doctor_name = data[0].doctor_name;
                data[0].save(sick, function (err, item) {
                    if (err) {
                        res.json(result(false, 'save failed', {}));
                    } else {
                        res.json(result(true, '', item));
                    }
                });
            } else {
                req.models.sick.create(sick, function (err, data) {
                    if (err) {
                        res.json(result(false, 'save failed', {}));
                    } else {
                        res.json(result(true, '', data));
                    }
                });
            }
        });
    } else {
        req.models.sick.create(sick, function (err, data) {
            if (err || !data) {
                res.json(result(false, 'save failed', {}));
            } else {
                res.json(result(true, '', data));
            }
        });
    }
});

router.get('/print', function (req, res, next) {
    var id = req.param('id');
    req.models.sick.get(id, function (err, sick) {
        if (err || !sick) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', sick));
        }
    })
});

router.get('/sickdrug', function (req, res, next) {
    var sick_id = req.param('sick_id');
    var type = req.param('type');
    var query = {};
    if (sick_id) {
        query.sick_id = sick_id;
    }
    if (type) {
        query.type = type;
    }
    req.models.sickdrug.find(query, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

router.get('/doctor', function (req, res, next) {
    var sick_id = req.param('sick_id');
    if (!sick_id) {
        res.json(result(false, 'no sick id', {}));
    } else {
        req.models.sick.get(sick_id, function (err, sick) {
            console.info("sick=>" + sick);
            if (err || !sick || !sick.doctor_id) {
                res.json(result(false, 'get sick info err', err));
            } else {
                req.models.doctor.get(sick.doctor_id, function (err, doctor) {
                    if (err || !doctor) {
                        res.json(result(false, 'get doctor info err'), {});
                    } else {
                        res.json(result(true, '', doctor));
                    }
                });
            }
        });
    }
});

router.get('/sicktablelist', function(req, res, next) {
    req.models.sicktables.find({}, function(err, data) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            res.json(result(true, '', data));
        }
    });
});

router.post('/savesicktable', function(req, res, next) {
    var table_type= req.param('table_type');
    var value = req.param('value');
    var target = req.param('target');
    req.models.sicktables.create({table_type: table_type, value: value, target: target}, function(err, item) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            res.json(result(true,'',item));
        }
    });
});

router.get('/sickstatus', function(req, res, next) {
    var sick_id = req.param('sick_id');
    var table_type = req.param('table_type');
    var query = {};
    if (sick_id) {
        query.sick_id=sick_id;
    }
    if (table_type) {
        query.table_type=table_type;
    }
    req.models.sickstatus.find(query, function(err, data){
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            if (!data || data.length == 0) {
                req.models.sicktables.find({table_type: table_type}, function(err, data) {
                    if (err) {
                        res.json(result(false, 'err', err));
                    } else {
                        res.json(result(true,'', data[0]));
                    }
                });
            } else {
                res.json(result(true, '', data[0]));
            }
        }
    });
});

var saveProhibitDrug = function(req, pro_drug, sick_id, table_type) {
    req.models.sickdrug.find({sick_id:sick_id, table_type:table_type, type:'f'}).remove(function(err){
    for (type in pro_drug) {
        console.info("pro_drug=" + JSON.stringify(pro_drug[type]));
        for (sickname in pro_drug[type]) {
            var drug_arr = pro_drug[type][sickname];

                if (err) {
                    console.error(err);
                } else {
                    for (var i = 0; i< drug_arr.length;i++) {
                        req.models.sickdrug.create({sick_id: sick_id,
                        drug_name: drug_arr[i],
                        drug_type: type,
                        table_type:table_type,
                        type: 'f',//s-建议 f-禁忌 c-慎用
                        drug_reason: sickname}, function(err, item){
                            if (err) {
                                console.error(err);
                            }
                        });
                    }
                }
        }
    }
    });
};

var saveRecommDrug = function(req, rec_drug, sick_id, table_type) {
    var recomm_drug = rec_drug.drugs;
    var recomm_name = rec_drug.name;
    console.info("recomm_name=>" + recomm_name + ", recomm_drug=>" + JSON.stringify(recomm_drug));
    req.models.sickdrug.find({sick_id:sick_id, table_type:table_type, type:'s'}).remove(function(err){
        console.info("startsaverecomm");
        if (err) {console.error(err);} else {
        for (var i = 0; i< recomm_drug.length;i++) {
            console.info("saverecomm=>" + recomm_drug[i]);
            req.models.sickdrug.create({sick_id: sick_id,
                    table_type:table_type,
                    drug_name: recomm_drug[i],
                    drug_type: recomm_name,
                    type: 's',//s-建议 f-禁忌 c-慎用
                    drug_reason: ''}, function(err, item) {
                    if (err) {
                        console.error(err);
                    }
            });
        }
    }
    });
}

router.post('/savestatus', function(req, res, next) {
    var sick_id = req.param('sick_id');
    var table_type = req.param('table_type');
    var table = req.param('table');
    req.models.sickstatus.find({sick_id: sick_id, table_type: table_type}, function(err, data) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            if (data && data.length > 0) {
                var tablejson = JSON.parse(table);
                var score = calc.score(tablejson);
                var level = calc.level(table_type, tablejson);
                var pro_drug = recommend.prohibit(tablejson);
                var rec_drug = recommend.recomm(pro_drug);

                saveProhibitDrug(req, pro_drug, sick_id, table_type);
                saveRecommDrug(req, rec_drug, sick_id, table_type);

                data[0].save({value: JSON.stringify(tablejson), score:score, level:level}, function(err) {
                    if (err) {
                        res.json(result(false, 'err', err));
                    } else {
                        res.json(result(true, '',{}));
                    }
                });
            } else {
                try {
                    var tablejson = JSON.parse(table);
                    var score = calc.score(tablejson);
                    var level = calc.level(table_type, tablejson);
                    var pro_drug = recommend.prohibit(tablejson);
                    var rec_drug = recommend.recomm(pro_drug);

                    saveProhibitDrug(req, pro_drug, sick_id, table_type);
                    saveRecommDrug(req, rec_drug, sick_id, table_type);
                    req.models.sickstatus.create({sick_id:sick_id, table_type:table_type, value:JSON.stringify(tablejson),score:score, level:level},
                    function(err, item){
                    if (err) {
                        res.json(result(false, 'err', err));
                        } else {
                        res.json(result(true,'',{}));
                    }
                    });
                } catch (e) {
                    console.error(e);
                    res.json(result(false,'err', e));
                }

            }
        }
    });
});

router.get('/sickscore', function(req, res, next) {
    var sick_id = req.param('sick_id');
    req.models.sickstatus.find({sick_id:sick_id}, function(err, data){
        if (err) {
            res.json(result(false,'err', err));
        } else {
        var re = {caprini:'',hss:0,rapt:''};
        for(var i=0;i<data.length;i++) {
            var item = data[i];
            console.info("item.table_type=" + item.table_type + ", score=" + item.score);
            if (item.table_type === 'caprini') {
                re.caprini = item.level||'';
            }
            if (item.table_type === 'hss_left') {
                re.hss += item.score||0;
            }
            if (item.table_type === 'hss_right') {
                re.hss += item.score||0;
            }
            if (item.table_type === 'rapt') {
                re.rapt = item.level||'';
            }
        }
        res.json(result(true, '', re));
    }
    });
});

router.get('/sickdrugcount', function(req, res, next){
    var sick_id = req.param('sick_id');

    req.models.sickdrug.find({sick_id:sick_id}, function(err, data){
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            var sick_name = {};
            var reason = {};
            for (var i = 0;i < data.length;i++) {

            }
        }
    });
});

module.exports = router;
<commit_msg>bug fixed<commit_after>var express = require('express');
var router = express.Router();
var result = require('./result');
var calc = require('../biz/calculate');
var recommend = require('../biz/recommend');
router.get('/info', function (req, res, next) {
    req.models.sick.get(req.param('id'), function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            req.models.doctor.get(data.doctor_id, function(err, doctor) {
                if (err) {
                    res.json(result(true, '', data));
                } else {
                    data.title = doctor.title;
                    res.json(result(true, '', data));
                }
            });

        }
    });
});

router.post('/create', function (req, res, next) {
    var sick = JSON.parse(req.param('sick'));
    var sick_name = sick.name, bed_id = sick.bed_id, doctor_id = sick.doctor_id, sick_id = sick.id;
    if (sick_id && sick_id > 0) {
        req.models.sick.get(sick_id, function (err, item) {
            if (err) {
                res.json(result(false,err.msg,err));
            } else {
                item.save(sick, function (err) {
                    if (err) {
                        res.json(result(false, err.msg, {}));
                    } else {
                        res.json(result(true, '', item));
                    }
                });
            }
        });
    } else if (sick.name && sick.bed_id && doctor_id) {
        req.models.sick.find({name: sick_name, bed_id: bed_id, doctor_id: doctor_id}, function (err, data) {
            if (!err && data && data.length > 0) {
                //merge info
                sick.doctor_name = data[0].doctor_name;
                data[0].save(sick, function (err, item) {
                    if (err) {
                        res.json(result(false, 'save failed', {}));
                    } else {
                        res.json(result(true, '', item));
                    }
                });
            } else {
                req.models.sick.create(sick, function (err, data) {
                    if (err) {
                        res.json(result(false, 'save failed', {}));
                    } else {
                        res.json(result(true, '', data));
                    }
                });
            }
        });
    } else {
        req.models.sick.create(sick, function (err, data) {
            if (err || !data) {
                res.json(result(false, 'save failed', {}));
            } else {
                res.json(result(true, '', data));
            }
        });
    }
});

router.get('/print', function (req, res, next) {
    var id = req.param('id');
    req.models.sick.get(id, function (err, sick) {
        if (err || !sick) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', sick));
        }
    })
});

router.get('/sickdrug', function (req, res, next) {
    var sick_id = req.param('sick_id');
    var type = req.param('type');
    var query = {};
    if (sick_id) {
        query.sick_id = sick_id;
    }
    if (type) {
        query.type = type;
    }
    req.models.sickdrug.find(query, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

router.get('/doctor', function (req, res, next) {
    var sick_id = req.param('sick_id');
    if (!sick_id) {
        res.json(result(false, 'no sick id', {}));
    } else {
        req.models.sick.get(sick_id, function (err, sick) {
            console.info("sick=>" + sick);
            if (err || !sick || !sick.doctor_id) {
                res.json(result(false, 'get sick info err', err));
            } else {
                req.models.doctor.get(sick.doctor_id, function (err, doctor) {
                    if (err || !doctor) {
                        res.json(result(false, 'get doctor info err'), {});
                    } else {
                        res.json(result(true, '', doctor));
                    }
                });
            }
        });
    }
});

router.get('/sicktablelist', function(req, res, next) {
    req.models.sicktables.find({}, function(err, data) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            res.json(result(true, '', data));
        }
    });
});

router.post('/savesicktable', function(req, res, next) {
    var table_type= req.param('table_type');
    var value = req.param('value');
    var target = req.param('target');
    req.models.sicktables.create({table_type: table_type, value: value, target: target}, function(err, item) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            res.json(result(true,'',item));
        }
    });
});

router.get('/sickstatus', function(req, res, next) {
    var sick_id = req.param('sick_id');
    var table_type = req.param('table_type');
    var query = {};
    if (sick_id) {
        query.sick_id=sick_id;
    }
    if (table_type) {
        query.table_type=table_type;
    }
    req.models.sickstatus.find(query, function(err, data){
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            if (!data || data.length == 0) {
                req.models.sicktables.find({table_type: table_type}, function(err, data) {
                    if (err) {
                        res.json(result(false, 'err', err));
                    } else {
                        res.json(result(true,'', data[0]));
                    }
                });
            } else {
                res.json(result(true, '', data[0]));
            }
        }
    });
});

var saveProhibitDrug = function(req, pro_drug, sick_id, table_type) {
    req.models.sickdrug.find({sick_id:sick_id, table_type:table_type, type:'f'}).remove(function(err){
    for (type in pro_drug) {
        console.info("pro_drug=" + JSON.stringify(pro_drug[type]));
        for (sickname in pro_drug[type]) {
            var drug_arr = pro_drug[type][sickname];

                if (err) {
                    console.error(err);
                } else {
                    for (var i = 0; i< drug_arr.length;i++) {
                        req.models.sickdrug.create({sick_id: sick_id,
                        drug_name: drug_arr[i],
                        drug_type: type,
                        table_type:table_type,
                        type: 'f',//s-建议 f-禁忌 c-慎用
                        drug_reason: sickname}, function(err, item){
                            if (err) {
                                console.error(err);
                            }
                        });
                    }
                }
        }
    }
    });
};

var saveRecommDrug = function(req, rec_drug, sick_id, table_type) {
    var recomm_drug = rec_drug.drugs;
    var recomm_name = rec_drug.name;
    console.info("recomm_name=>" + recomm_name + ", recomm_drug=>" + JSON.stringify(recomm_drug));
    req.models.sickdrug.find({sick_id:sick_id, table_type:table_type, type:'s'}).remove(function(err){
        console.info("startsaverecomm");
        if (err) {console.error(err);} else {
        for (var i = 0; i< recomm_drug.length;i++) {
            console.info("saverecomm=>" + recomm_drug[i]);
            req.models.sickdrug.create({sick_id: sick_id,
                    table_type:table_type,
                    drug_name: recomm_drug[i],
                    drug_type: recomm_name,
                    type: 's',//s-建议 f-禁忌 c-慎用
                    drug_reason: ''}, function(err, item) {
                    if (err) {
                        console.error(err);
                    }
            });
        }
    }
    });
}

router.post('/savestatus', function(req, res, next) {
    var sick_id = req.param('sick_id');
    var table_type = req.param('table_type');
    var table = req.param('table');
    req.models.sickstatus.find({sick_id: sick_id, table_type: table_type}, function(err, data) {
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            if (data && data.length > 0) {
                var tablejson = JSON.parse(table);
                var score = calc.score(tablejson);
                var level = calc.level(table_type, tablejson);
                var pro_drug = recommend.prohibit(tablejson);
                var rec_drug = recommend.recomm(pro_drug);

                saveProhibitDrug(req, pro_drug, sick_id, table_type);
                saveRecommDrug(req, rec_drug, sick_id, table_type);

                data[0].save({value: JSON.stringify(tablejson), score:score, level:level}, function(err) {
                    if (err) {
                        res.json(result(false, 'err', err));
                    } else {
                        res.json(result(true, '',{}));
                    }
                });
            } else {
                try {
                    var tablejson = JSON.parse(table);
                    var score = calc.score(tablejson);
                    var level = calc.level(table_type, tablejson);
                    var pro_drug = recommend.prohibit(tablejson);
                    var rec_drug = recommend.recomm(pro_drug);

                    saveProhibitDrug(req, pro_drug, sick_id, table_type);
                    saveRecommDrug(req, rec_drug, sick_id, table_type);
                    req.models.sickstatus.create({sick_id:sick_id, table_type:table_type, value:JSON.stringify(tablejson),score:score, level:level},
                    function(err, item){
                    if (err) {
                        res.json(result(false, 'err', err));
                        } else {
                        res.json(result(true,'',{}));
                    }
                    });
                } catch (e) {
                    console.error(e);
                    res.json(result(false,'err', e));
                }

            }
        }
    });
});

router.get('/sickscore', function(req, res, next) {
    var sick_id = req.param('sick_id');
    req.models.sickstatus.find({sick_id:sick_id}, function(err, data){
        if (err) {
            res.json(result(false,'err', err));
        } else {
        var re = {caprini:'',hss:0,rapt:''};
        for(var i=0;i<data.length;i++) {
            var item = data[i];
            console.info("item.table_type=" + item.table_type + ", score=" + item.score);
            if (item.table_type === 'caprini') {
                re.caprini = item.level||'';
            }
            if (item.table_type === 'hss_left') {
                re.hss += item.score||0;
            }
            if (item.table_type === 'hss_right') {
                re.hss += item.score||0;
            }
            if (item.table_type === 'rapt') {
                re.rapt = item.level||'';
            }
        }
        res.json(result(true, '', re));
    }
    });
});

router.get('/sickdrugcount', function(req, res, next){
    var sick_id = req.param('sick_id');

    req.models.sickdrug.find({sick_id:sick_id}, function(err, data){
        if (err) {
            res.json(result(false, 'err', err));
        } else {
            var sick_name = {};
            var reason = {};
            for (var i = 0;i < data.length;i++) {
                sick_name[data[i].drug_name] = 1;
                if (data[i].type==='f') {
                    reason[data[i].drug_reason] = 1;
                }
            }
            res.json(result(true, '', {"drug_count":Object.keys(sick_name).length, "select_count" : Object.keys(reason).length}));

        }
    });
});

module.exports = router;
<|endoftext|>


<commit_before>"use strict";
/**
 * @ngInject
 */
var AutoConfig = function(environment) {

  this.detectEnvironment = function(hostname) {
    var environment;
    if ("localhost" === hostname) {
      environment = "development";
    } else if ("apptest.data.npolar.no" === hostname) {
      environment = "test";
    } else if ("api.npolar.no" === hostname) {
      environment = "production";
    }
    return environment;
  };

  var config = {};

  // Auto-detect environment
  if (window && (environment === undefined || environment === null)) {
    environment = this.detectEnvironment(window.location.hostname);
    console.log("Environment:", environment, "[auto-detected]");
  }

  config.environment = environment;
  if ("development" === environment) {
    config.base = "//localhost:9393";
  } else if ("test" === environment) {
    config.base = "//apptest.data.npolar.no";
  } else {
    config.base = "//api.npolar.no";
  }

  if ("production" === environment && window) {
    if ("https:" !== window.location.production) {
      console.error("WARNING", "Not using HTTPS in production environment");
    }
    if ("data.npolar.no" !== window.location.hostname) {
      console.error("WARNING", "Running against production API", config.base, "from", window.location.href);
    }
  }
  return config;

};

module.exports = AutoConfig;<commit_msg>Only allow environment override on localhost<commit_after>"use strict";
/**
 * @ngInject
 */
var AutoConfig = function(environment) {

  var config = {};

  this.isTest = function(hostname) {
    return (/test/.test(hostname.split(".")[0]));
  };

  this.detectEnvironment = function(hostname) {
    var environment;
    if ("localhost" === hostname) {
      environment = "development";
    } else if (this.isTest(hostname)) {
      environment = "test";
    } else if ("api.npolar.no" === hostname) {
      environment = "production";
    }
    return environment;
  };

  this.base = function(environment) {
    var base;
    if ("development" === environment) {
      base = "//localhost:9393";
    } else if ("test" === environment) {
      base = "//apptest.data.npolar.no";
    } else if ("production" === environment){
      base = "//api.npolar.no";
    } else {
      throw "Unknown environment: "+environment;
    }
    return base;
  };

  // Auto-detect environment - only allow overriding on localhost
  if ("localhost" === window.location.hostname && (typeof environment === 'string' || environment instanceof String)) {
    console.error("Environment:", environment, "[localhost override]");
  } else {
    environment = this.detectEnvironment(window.location.hostname);
    console.log("Environment:", environment, "[auto-detected]");
  }

  config.base = this.base(environment);
  config.environment = environment;

  if ("production" === environment && window) {
    if ("https:" !== window.location.protocol) {
      console.error("WARNING", "Not using HTTPS in production environment");
    }
    if ("data.npolar.no" !== window.location.hostname) {
      console.error("WARNING", "Running against production API", config.base, "from", window.location.href);
    }
  }
  return config;

};

module.exports = AutoConfig;<|endoftext|>


<commit_before>// 13 colors
export const COLORS = [
  "red",
  "orange",
  "yellow",
  "olive",
  "green",
  "teal",
  "blue",
  "violet",
  "purple",
  "pink",
  "brown",
  "grey",
  "black"
];

export const SECTIONS = [
  "Top",
  "About",
  //'Portfolio',
  "Resume"
  // 'Work', 'Education', 'Skills',
];

export const BASIC = {
  name: "louis",
  tagline: "❤愛 ☮life ✋敬重",
  taglineUrl: "https://en.wikipedia.org/wiki/Hacker_culture",
  about: "I teach bots to steal jobs and make games for the retired.",
  email: "lgvichy@gmail.com",
  logo: "id/icon-white.png",
  url: "https://louisgv.ga/"
};

export const PHOTO = {
  normal: "id/selfid.jpg",
  normalInverted: "id/selfid-inverted.jpg",
  small: "id/selfid-small.jpg",
  smallInverted: "id/selfid-small-inverted.jpg"
};

export const CONTACT = {
  email: {
    icon: "envelope",
    color: COLORS[6],
    value: "lgvichy@gmail.com"
  },
  location: {
    icon: "globe",
    color: COLORS[5],
    name: "Seattle, Washington",
    url: "https://en.wikipedia.org/wiki/Seattle"
  }
};

export const HOBBIES = [
  {
    name: "Hacking on cutting edge technology",
    color: "orange",
    icon: "terminal",
    url: "https://louisgv.github.io/dev/www/index.html#/"
  },
  {
    name: "Reading research paper",
    color: "yellow",
    icon: "sticky note",
    url: "https://arxiv.org/"
  },
  {
    name: "Listening to scientific podcast",
    color: "olive",
    icon: "podcast",
    url: "https://twit.tv/shows/floss-weekly"
  },
  {
    name: "Kick-boxing",
    color: "green",
    icon: "grab",
    url: "https://en.wikipedia.org/wiki/Kickboxing"
  }
];

export const INTERESTS = [
  {
    name: "Robotic Automation",
    color: COLORS[11],
    icon: "radio",
    url: "https://en.wikipedia.org/wiki/Robotic_automation_software"
  },
  {
    name: "Life Extension",
    color: COLORS[10],
    icon: "power",
    url: "https://en.wikipedia.org/wiki/Life_extension"
  },
  {
    name: "Machine Learning",
    color: COLORS[9],
    icon: "linkify",
    url: "https://lmgtfy.com/?s=d&q=Machine+learning"
  },
  {
    name: "Decentralization",
    color: COLORS[8],
    icon: "unlinkify",
    url: "https://lmgtfy.com/?s=d&q=Decentralization"
  },
  {
    name: "Entertainment",
    color: COLORS[7],
    icon: "game",
    url: "https://lmgtfy.com/?s=d&q=Entertainment"
  }
];

export const SOCIALS = [
  {
    name: "tweet",
    color: COLORS[5],
    icon: "twitter",
    url: "https://twitter.com/litbid",
    uid: "lidbid"
  },
  {
    name: "biz",
    color: COLORS[6],
    icon: "linkedin",
    url: "https://www.linkedin.com/in/louisgv/",
    uid: "louisgv"
  },
  {
    name: "art",
    color: COLORS[7],
    icon: "instagram",
    url: "https://www.instagram.com/lgvichy/",
    uid: "lgvichy"
  },
  {
    name: "code",
    color: COLORS[8],
    icon: "github",
    url: "https://github.com/louisgv/",
    uid: "louisgv"
  }
];

export const WORK_SAMPLES = [
  {
    label: "networking",
    name: "HyperProxy",
    color: COLORS[0],
    url: "https://goonism.github.io/hyperproxy/"
  },
  {
    label: "production",
    name: "Janus",
    color: COLORS[1],
    url: "https://janus-game.com"
  },
  {
    label: "visualization",
    name: "Pattar",
    color: COLORS[2],
    url: "https://louisgv.ga/pattar/"
  }
];

export const PORTFOLIOS = [
  {
    name: "SmartLook Web",
    type: "Web Application",
    color: COLORS[0],
    description: "TurboTax's real-time customer support feature",
    technology: "ES6, React.js, CSS, Glance",
    image: "project/smartlook_mobile.gif",
    role: "Lead Front-end Engineer",
    license: "PROPRIETARY",
    status: "In production, TurboTax 2016",
    url: "https://www.youtube.com/watch?v=E19Znq9EDZ0"
  },
  {
    name: "Cryptoville",
    type: "Web Application",
    color: COLORS[1],
    description: "Decentralized market making platform for agriculture",
    license: "MIT",
    role: "Core Contributor",
    technology: "React.js, Lisk",
    image: "project/cryptoville.gif",
    status: "Opensource Project",
    url: "https://www.crypto-ville.herokuapp.com"
  },
  {
    name: "JanusLauncher",
    type: "Mobile Application",
    color: COLORS[2],
    description:
      "An Android launcher with hand written letter recognition capability for quick app browsing",
    role: "Author",
    license: "MIT",
    technology:
      "Kotlin, Android Studio Canary, TensorFlow, Jupyter Notebook, EMNIST database",
    image: "project/janusLauncher.gif",
    status: "Opensource Project",
    url: "https://github.com/louisgv/janusLauncher"
  },
  {
    name: "VegaHub",
    type: "Hybrid Application",
    color: COLORS[3],
    description:
      "A hybrid mobile application used to control any robot implementing Cumulonimbus's ROS bridge",
    role: "Lead Front-end Engineer",
    license: "PROPRIETARY",
    status: "N/A",
    technology:
      "Google Mobile Kit (Bluetooth module), Firebase, Ionic, Cordova, CrossWalk, ES5, SASS",
    image: "project/vegahub.gif",
    url: "https://clnb.io/vega/"
  }
];

export const RESUME = {
  // "embedded": "https://docs.google.com/document/d/e/2PACX-1vT9bDNvMitcORMx7nmL0-zOwDkTPMRZXuwR8OwN0j_1A1IMqm9hX4X5zY7_a27Os_CSGGnCJPkHwVYp/pub?embedded=true",
  embedded:
    "https://docs.google.com/document/d/1_UE4yS3lA81l3HdBwhKABcKXAJIO0HyDkcaOxNAjJPs/preview",
  external:
    "https://docs.google.com/document/d/1_UE4yS3lA81l3HdBwhKABcKXAJIO0HyDkcaOxNAjJPs/edit?usp=sharing"
};

export const REFERENCES = [
  {
    url: "https://reactjs.org/",
    name: "React.js"
  },
  {
    url: "https://react.semantic-ui.com/",
    name: "Semantic-ui"
  },
  {
    url: "https://github.com/negomi/react-burger-menu/",
    name: "react-burger-menu"
  },
  {
    url: "https://github.com/oliviertassinari/react-swipeable-views",
    name: "react-swipeable-views"
  }
];

export const LICENSE = {
  name: "MIT License",
  url: "https://en.wikipedia.org/wiki/MIT_License"
};
<commit_msg>Update resume.js<commit_after>// 13 colors
export const COLORS = [
  "red",
  "orange",
  "yellow",
  "olive",
  "green",
  "teal",
  "blue",
  "violet",
  "purple",
  "pink",
  "brown",
  "grey",
  "black"
];

export const SECTIONS = [
  "Top",
  "About",
  //'Portfolio',
  "Resume"
  // 'Work', 'Education', 'Skills',
];

export const BASIC = {
  name: "louis",
  tagline: "❤愛 ☮life ✋敬重",
  taglineUrl: "https://en.wikipedia.org/wiki/Hacker_culture",
  about: "I teach bots to steal jobs and make games for the retired.",
  email: "lgvichy@gmail.com",
  logo: "id/icon-white.png",
  url: "https://louisgv.ga/"
};

export const PHOTO = {
  normal: "id/selfid.jpg",
  normalInverted: "id/selfid-inverted.jpg",
  small: "id/selfid-small.jpg",
  smallInverted: "id/selfid-small-inverted.jpg"
};

export const CONTACT = {
  email: {
    icon: "envelope",
    color: COLORS[6],
    value: "lgvichy@gmail.com"
  },
  location: {
    icon: "globe",
    color: COLORS[5],
    name: "Seattle, Washington",
    url: "https://en.wikipedia.org/wiki/Seattle"
  }
};

export const HOBBIES = [
  {
    name: "Hacking on cutting edge technology",
    color: "orange",
    icon: "terminal",
    url: "https://louisgv.github.io/dev/www/index.html#/"
  },
  {
    name: "Reading research paper",
    color: "yellow",
    icon: "sticky note",
    url: "https://arxiv.org/"
  },
  {
    name: "Listening to scientific podcast",
    color: "olive",
    icon: "podcast",
    url: "https://twit.tv/shows/floss-weekly"
  },
  {
    name: "Kick-boxing",
    color: "green",
    icon: "grab",
    url: "https://en.wikipedia.org/wiki/Kickboxing"
  }
];

export const INTERESTS = [
  {
    name: "Robotic Automation",
    color: COLORS[11],
    icon: "radio",
    url: "https://en.wikipedia.org/wiki/Robotic_automation_software"
  },
  {
    name: "Life Extension",
    color: COLORS[10],
    icon: "power",
    url: "https://en.wikipedia.org/wiki/Life_extension"
  },
  {
    name: "Machine Learning",
    color: COLORS[9],
    icon: "linkify",
    url: "https://lmgtfy.com/?s=d&q=Machine+learning"
  },
  {
    name: "Decentralization",
    color: COLORS[8],
    icon: "unlinkify",
    url: "https://lmgtfy.com/?s=d&q=Decentralization"
  },
  {
    name: "Entertainment",
    color: COLORS[7],
    icon: "game",
    url: "https://lmgtfy.com/?s=d&q=Entertainment"
  }
];

export const SOCIALS = [
  {
    name: "tweet",
    color: COLORS[5],
    icon: "twitter",
    url: "https://twitter.com/litbid",
    uid: "lidbid"
  },
  {
    name: "biz",
    color: COLORS[6],
    icon: "linkedin",
    url: "https://www.linkedin.com/in/louisgv/",
    uid: "louisgv"
  },
  {
    name: "art",
    color: COLORS[7],
    icon: "instagram",
    url: "https://www.instagram.com/lgvichy/",
    uid: "lgvichy"
  },
  {
    name: "code",
    color: COLORS[8],
    icon: "github",
    url: "https://github.com/louisgv/",
    uid: "louisgv"
  }
];

export const WORK_SAMPLES = [
  {
    label: "networking",
    name: "HyperProxy",
    color: COLORS[0],
    url: "https://goonism.github.io/hyperproxy/"
  },
  {
    label: "production",
    name: "Janus",
    color: COLORS[1],
    url: "https://louisgv.itch.io/jhc"
  },
  {
    label: "visualization",
    name: "Pattar",
    color: COLORS[2],
    url: "https://louisgv.github.io/pattar/"
  }
];

export const PORTFOLIOS = [
  {
    name: "SmartLook Web",
    type: "Web Application",
    color: COLORS[0],
    description: "TurboTax's real-time customer support feature",
    technology: "ES6, React.js, CSS, Glance",
    image: "project/smartlook_mobile.gif",
    role: "Lead Front-end Engineer",
    license: "PROPRIETARY",
    status: "In production, TurboTax 2016",
    url: "https://www.youtube.com/watch?v=E19Znq9EDZ0"
  },
  {
    name: "Cryptoville",
    type: "Web Application",
    color: COLORS[1],
    description: "Decentralized market making platform for agriculture",
    license: "MIT",
    role: "Core Contributor",
    technology: "React.js, Lisk",
    image: "project/cryptoville.gif",
    status: "Opensource Project",
    url: "https://www.crypto-ville.herokuapp.com"
  },
  {
    name: "JanusLauncher",
    type: "Mobile Application",
    color: COLORS[2],
    description:
      "An Android launcher with hand written letter recognition capability for quick app browsing",
    role: "Author",
    license: "MIT",
    technology:
      "Kotlin, Android Studio Canary, TensorFlow, Jupyter Notebook, EMNIST database",
    image: "project/janusLauncher.gif",
    status: "Opensource Project",
    url: "https://github.com/louisgv/janusLauncher"
  },
  {
    name: "VegaHub",
    type: "Hybrid Application",
    color: COLORS[3],
    description:
      "A hybrid mobile application used to control any robot implementing Cumulonimbus's ROS bridge",
    role: "Lead Front-end Engineer",
    license: "PROPRIETARY",
    status: "N/A",
    technology:
      "Google Mobile Kit (Bluetooth module), Firebase, Ionic, Cordova, CrossWalk, ES5, SASS",
    image: "project/vegahub.gif",
    url: "https://clnb.io/vega/"
  }
];

export const RESUME = {
  // "embedded": "https://docs.google.com/document/d/e/2PACX-1vT9bDNvMitcORMx7nmL0-zOwDkTPMRZXuwR8OwN0j_1A1IMqm9hX4X5zY7_a27Os_CSGGnCJPkHwVYp/pub?embedded=true",
  embedded:
    "https://docs.google.com/document/d/1_UE4yS3lA81l3HdBwhKABcKXAJIO0HyDkcaOxNAjJPs/preview",
  external:
    "https://docs.google.com/document/d/1_UE4yS3lA81l3HdBwhKABcKXAJIO0HyDkcaOxNAjJPs/edit?usp=sharing"
};

export const REFERENCES = [
  {
    url: "https://reactjs.org/",
    name: "React.js"
  },
  {
    url: "https://react.semantic-ui.com/",
    name: "Semantic-ui"
  },
  {
    url: "https://github.com/negomi/react-burger-menu/",
    name: "react-burger-menu"
  },
  {
    url: "https://github.com/oliviertassinari/react-swipeable-views",
    name: "react-swipeable-views"
  }
];

export const LICENSE = {
  name: "MIT License",
  url: "https://en.wikipedia.org/wiki/MIT_License"
};
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
(function () { /* Begin of privacy scope */
    "use strict";
/*#endif*/

    var
        /**
         * Read-only property accessor template
         *
         * @return {*}
         */
        _roProperty = function () {
            return this._MEMBER_;
        },

        /**
         * Property accessor template
         *
         * @return {*}
         */
        _rwProperty = function () {
            var result = this._MEMBER_;
            if (0 < arguments.length) {
                this._MEMBER_ = arguments[0];
            }
            return result;
        },

        /**
         * Base class for class-specific attributes
         *
         * @class gpf.attributes.ClassAttribute
         * @extends gpf.attributes.Attribute
         */
        _base = gpf._defAttr("ClassAttribute");

    /**
     * Creates getter (and setter) methods for a private member. The created
     * accessor is a method with the following signature:
     * {type} MEMBER({type} [value=undefined] value)
     * When value is not set, the member acts as a getter
     *
     *
     * @class gpf.attributes.ClassPropertyAttribute
     * @extends gpf.attributes.ClassAttribute
     * @alias gpf.$ClassProperty
     */
    gpf._defAttr("$ClassProperty", _base, {

        private: {

            /**
             * If true, generates a write wrapper
             *
             * @type {Boolean}
             * @private
             */
            _writeAllowed: false,

            /**
             * If set, provides the member name. Otherwise, name is based on
             * member.
             *
             * @type {String|undefined}
             * @private
             */
            _publicName: undefined,

            /**
             * If set, provides the member visibility.
             * Default is 'public'
             * member.
             *
             * @type {String|undefined}
             * @private
             */
            _visibility: undefined

        },

        protected: {

            /**
             * @inheritdoc gpf.attributes.Attribute:_alterPrototype
             */
            _alterPrototype: function (objPrototype) {
                var
                    member = this._member,
                    publicName = this._publicName,
                    classDef = gpf.classDef(objPrototype.constructor),
                    src,
                    start,
                    end;
                if (!publicName) {
                    publicName = member.substr(1); // starts with _
                }
                if (this._writeAllowed) {
                    src = _rwProperty.toString();
                } else {
                    src = _roProperty.toString();
                }
                // Replace all occurrences of _MEMBER_ with the right name
                src = src.split("_MEMBER_").join(member);
                // Extract content of resulting function source
                start = src.indexOf("{") + 1;
                end = src.lastIndexOf("}") - 1;
                src =  src.substr(start, end - start + 1);
                classDef.addMember(publicName, gpf._func(src),
                    this._visibility);
            }

        },

        public: {

            /**
             * @param {Boolean} writeAllowed
             * @param {String} [publicName=undefined] publicName When not
             * specified, the member name (without _) is applied
             * @param {String} [visibility=undefined] visibility When not
             * specified, public is used
             * @constructor
             */
            constructor: function (writeAllowed, publicName, visibility) {
                if (writeAllowed) {
                    this._writeAllowed = true;
                }
                if ("string" === typeof publicName) {
                    this._publicName = publicName;
                }
                if ("string" === typeof visibility) {
                    this._visibility = visibility;
                }
            }

        }

    });

    /**
     * Used to flag a method which owns a last parameter being an event handler
     *
     * @class gpf.attributes.ClassEventHandlerAttribute
     * @extends gpf.attributes.ClassAttribute
     * @alias gpf.$ClassEventHandler
     */
    gpf._defAttr("$ClassEventHandler", _base, {});

    /**
     * Defines a class extension (internal)
     *
     * @param {String} ofClass
     * @param {String} [publicName=undefined] publicName When not specified,
     * the original method name is used
     *
     * @class gpf.attributes.ClassExtensionAttribute
     * @extends gpf.attributes.ClassAttribute
     * @alias gpf.$ClassExtension
     */
    gpf._defAttr("$ClassExtension", _base, {

        private: {

            /**
             * Constructor of the class to extend
             *
             * @type {Function}
             * @private
             */
            _ofClass: gpf.emptyFunction(),

            /**
             * Name of the method if added to the class
             *
             * @type {String}
             * @private
             */
            _publicName: ""

        },

        public: {

            /**
             * @param {Function} ofClass Constructor of the class to extend
             * @param {String} publicName Name of the method if added to the
             * class
             * @constructor
             */
            constructor: function (ofClass, publicName) {
                this._ofClass = ofClass;
                if ("string" === typeof publicName) {
                    this._publicName = publicName;
                }
            }

        }

    });

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/<commit_msg>New source model (WIP)<commit_after>/*#ifndef(UMD)*/
"use strict";
/*global _gpfEmptyFunc*/
/*#endif*/

var
    /**
     * Read-only property accessor template
     *
     * @return {*}
     */
    _roProperty = function () {
        return this._MEMBER_;
    },

    /**
     * Property accessor template
     *
     * @return {*}
     */
    _rwProperty = function () {
        var result = this._MEMBER_;
        if (0 < arguments.length) {
            this._MEMBER_ = arguments[0];
        }
        return result;
    },

    /**
     * Base class for class-specific attributes
     *
     * @class gpf.attributes.ClassAttribute
     * @extends gpf.attributes.Attribute
     */
    _base = gpf._defAttr("ClassAttribute");

/**
 * Creates getter (and setter) methods for a private member. The created
 * accessor is a method with the following signature:
 * {type} MEMBER({type} [value=undefined] value)
 * When value is not set, the member acts as a getter
 *
 *
 * @class gpf.attributes.ClassPropertyAttribute
 * @extends gpf.attributes.ClassAttribute
 * @alias gpf.$ClassProperty
 */
gpf._defAttr("$ClassProperty", _base, {

    private: {

        /**
         * If true, generates a write wrapper
         *
         * @type {Boolean}
         * @private
         */
        _writeAllowed: false,

        /**
         * If set, provides the member name. Otherwise, name is based on
         * member.
         *
         * @type {String|undefined}
         * @private
         */
        _publicName: undefined,

        /**
         * If set, provides the member visibility.
         * Default is 'public'
         * member.
         *
         * @type {String|undefined}
         * @private
         */
        _visibility: undefined

    },

    protected: {

        /**
         * @inheritdoc gpf.attributes.Attribute:_alterPrototype
         */
        _alterPrototype: function (objPrototype) {
            var
                member = this._member,
                publicName = this._publicName,
                classDef = gpf.classDef(objPrototype.constructor),
                src,
                start,
                end;
            if (!publicName) {
                publicName = member.substr(1); // starts with _
            }
            if (this._writeAllowed) {
                src = _rwProperty.toString();
            } else {
                src = _roProperty.toString();
            }
            // Replace all occurrences of _MEMBER_ with the right name
            src = src.split("_MEMBER_").join(member);
            // Extract content of resulting function source
            start = src.indexOf("{") + 1;
            end = src.lastIndexOf("}") - 1;
            src =  src.substr(start, end - start + 1);
            classDef.addMember(publicName, gpf._func(src),
                this._visibility);
        }

    },

    public: {

        /**
         * @param {Boolean} writeAllowed
         * @param {String} [publicName=undefined] publicName When not
         * specified, the member name (without _) is applied
         * @param {String} [visibility=undefined] visibility When not
         * specified, public is used
         * @constructor
         */
        constructor: function (writeAllowed, publicName, visibility) {
            if (writeAllowed) {
                this._writeAllowed = true;
            }
            if ("string" === typeof publicName) {
                this._publicName = publicName;
            }
            if ("string" === typeof visibility) {
                this._visibility = visibility;
            }
        }

    }

});

/**
 * Used to flag a method which owns a last parameter being an event handler
 *
 * @class gpf.attributes.ClassEventHandlerAttribute
 * @extends gpf.attributes.ClassAttribute
 * @alias gpf.$ClassEventHandler
 */
gpf._defAttr("$ClassEventHandler", _base, {});

/**
 * Defines a class extension (internal)
 *
 * @param {String} ofClass
 * @param {String} [publicName=undefined] publicName When not specified,
 * the original method name is used
 *
 * @class gpf.attributes.ClassExtensionAttribute
 * @extends gpf.attributes.ClassAttribute
 * @alias gpf.$ClassExtension
 */
gpf._defAttr("$ClassExtension", _base, {

    private: {

        /**
         * Constructor of the class to extend
         *
         * @type {Function}
         * @private
         */
        _ofClass: _gpfEmptyFunc,

        /**
         * Name of the method if added to the class
         *
         * @type {String}
         * @private
         */
        _publicName: ""

    },

    public: {

        /**
         * @param {Function} ofClass Constructor of the class to extend
         * @param {String} publicName Name of the method if added to the
         * class
         * @constructor
         */
        constructor: function (ofClass, publicName) {
            this._ofClass = ofClass;
            if ("string" === typeof publicName) {
                this._publicName = publicName;
            }
        }

    }

});

<|endoftext|>


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

'use strict';

var fs = require('fs');
var path = require('path');
var split2 = require('split2');
var test = require('tape');
var util = require('util');

var Errors = require('../errors.js');

var errorsPath = path.resolve(path.join(__dirname, '..', 'errors.js'));

test('errors module should be in sorted order', function t(assert) {
    var exportedErrors = [];
    processLineMatches(errorsPath,
        /^module\.exports\.([^ ]+) *= *([\w_\-]+)/,
        function each(match) {
            if (/Error$/.test(match[2])) {
                exportedErrors.push(match[1]);
            }
        }, checkExportedErrors);

    function checkExportedErrors() {
        var expected = exportedErrors.slice().sort();
        var allOk = true;
        for (var i = 0; i < expected.length; i++) {
            if (exportedErrors[i] !== expected[i]) {
                allOk = false;
                assert.fail(util.format(
                    'errors module not in sorted order: %s is out of place (expected %s)',
                    exportedErrors[i], expected[i]));
            }
        }
        if (allOk) assert.pass('errors module is in sorted order');
        assert.end();
    }
});

test('error classification cases must be sorted', function t(assert) {
    var caseAccum = [];
    var cases = {};

    processLineMatches(errorsPath,
        /\breturn +'(\w+)'|case\s+(['"])(.+?)\2/,
        function each(match) {
            if (match[1]) {
                cases[match[1]] = caseAccum;
                caseAccum = [];
            } else {
                caseAccum.push(match[3]);
            }
        }, checkCases);

    function checkCases() {
        Object.keys(cases).forEach(checkCase);
        assert.end();
    }

    function checkCase(category) {
        var catCases = cases[category];
        var expected = catCases.slice().sort();
        var allOk = true;
        for (var i = 0; i < expected.length; i++) {
            if (catCases[i] !== expected[i]) {
                allOk = false;
                assert.fail(util.format(
                    '%s cases not in sorted order: %s is out of place (expected %s)',
                    category, catCases[i], expected[i]));
            }
        }

        if (allOk) {
            assert.pass(util.format('%s cases are in sorted order', category));
        }
    }
});

test('error case statements should not be duplicates', function t(assert) {
    var caseTypes = [];
    processLineMatches(errorsPath,
        /case\s+(['"])(.+?)\1/,
        function each(match) {
            caseTypes.push(match[2]);
        }, checkCases);

    function checkCases() {
        var errorTypes = getValueTypes(Errors);
        caseTypes.sort();
        errorTypes.sort();
        assert.equal(caseTypes.length, errorTypes.length);
        assert.deepEqual(caseTypes, errorTypes);
        assert.end();
    }

    function getValueTypes(obj) {
        var types = [];
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
            var val = obj[keys[i]];
            if (val && val.type) {
                types.push(val.type);
            }
        }
        return types;
    }
});

test('all errors are classified', function t(assert) {
    var keys = Object.keys(Errors);
    for (var i = 0; i < keys.length; i++) {
        var errorFn = Errors[keys[i]];
        if (!errorFn || !errorFn.type) {
            continue;
        }

        var errObj = errorFn(new Error('e'));

        var errorClass = Errors.classify(errObj);
        assert.ok(errorClass, errorFn.type + ' can be classified');
    }

    assert.end();
});

function processLineMatches(filePath, pattern, proc, done) {
    fs.createReadStream(filePath, 'utf8')
        .pipe(split2())
        .on('data', eachLine)
        .on('end', streamDone);

    function eachLine(line) {
        var match = pattern.exec(line);
        if (match) {
            proc(match);
        }
    }

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

'use strict';

var fs = require('fs');
var path = require('path');
var split2 = require('split2');
var test = require('tape');
var util = require('util');

var Errors = require('../errors.js');

var errorsPath = path.resolve(path.join(__dirname, '..', 'errors.js'));

test('errors module should be in sorted order', function t(assert) {
    var exportedErrors = [];

    processLineMatches({
        filePath: errorsPath,
        caseRegex: /^module\.exports\.([^ ]+) *= *([\w_\-]+)/,
        onMatch: function each(match) {
            if (/Error$/.test(match[2])) {
                exportedErrors.push(match[1]);
            }
        },
        onFinish: checkExportedErrors
    });

    function checkExportedErrors() {
        var expected = exportedErrors.slice().sort();
        var allOk = true;
        for (var i = 0; i < expected.length; i++) {
            if (exportedErrors[i] !== expected[i]) {
                allOk = false;
                assert.fail(util.format(
                    'errors module not in sorted order: %s is out of place (expected %s)',
                    exportedErrors[i], expected[i]));
            }
        }
        if (allOk) assert.pass('errors module is in sorted order');
        assert.end();
    }
});

test('error classification cases must be sorted', function t(assert) {
    var caseAccum = [];
    var cases = {};

    processLineMatches({
        filePath: errorsPath,
        caseRegex: /\breturn +'(\w+)'|case\s+(['"])(.+?)\2/,
        onMatch: function each(match) {
            if (match[1]) {
                cases[match[1]] = caseAccum;
                caseAccum = [];
            } else {
                caseAccum.push(match[3]);
            }
        },
        onFinish: checkCases
    });

    function checkCases() {
        Object.keys(cases).forEach(checkCase);
        assert.end();
    }

    function checkCase(category) {
        var catCases = cases[category];
        var expected = catCases.slice().sort();
        var allOk = true;
        for (var i = 0; i < expected.length; i++) {
            if (catCases[i] !== expected[i]) {
                allOk = false;
                assert.fail(util.format(
                    '%s cases not in sorted order: %s is out of place (expected %s)',
                    category, catCases[i], expected[i]));
            }
        }

        if (allOk) {
            assert.pass(util.format('%s cases are in sorted order', category));
        }
    }
});

test('error case statements should not be duplicates', function t(assert) {
    var caseTypes = [];
    processLineMatches({
        filePath: errorsPath,
        startRegex: /module\.exports\.classify = function classify\(err\) \{/,
        caseRegex: /case\s+(['"])(.+?)\1/,
        endRegex: /\};/,
        onMatch: function each(match) {
            caseTypes.push(match[2]);
        },
        onFinish: checkCases
    });

    function checkCases() {
        var errorTypes = getValueTypes(Errors);
        caseTypes.sort();
        errorTypes.sort();
        assert.equal(caseTypes.length, errorTypes.length);
        assert.deepEqual(caseTypes, errorTypes);
        assert.end();
    }

    function getValueTypes(obj) {
        var types = [];
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
            var val = obj[keys[i]];
            if (val && val.type) {
                types.push(val.type);
            }
        }
        return types;
    }
});

test('all errors are classified', function t(assert) {
    var keys = Object.keys(Errors);
    for (var i = 0; i < keys.length; i++) {
        var errorFn = Errors[keys[i]];
        if (!errorFn || !errorFn.type) {
            continue;
        }

        var errObj = errorFn(new Error('e'));

        var errorClass = Errors.classify(errObj);
        assert.ok(errorClass, errorFn.type + ' can be classified');
    }

    assert.end();
});

function processLineMatches(options) {
    var inScope = false;

    fs.createReadStream(options.filePath, 'utf8')
        .pipe(split2())
        .on('data', eachLine)
        .on('end', streamDone);

    function eachLine(line) {
        if (options.startRegex && !inScope) {
            if (options.startRegex.test(line)) {
                inScope = true;
            }
        }

        if (!options.startRegex || inScope) {
            var match = options.caseRegex.exec(line);
            if (match) {
                options.onMatch(match);
            }
        }

        if (options.endRegex && inScope) {
            if (options.endRegex.test(line)) {
                inScope = false;
            }
        }
    }

    function streamDone() {
        process.nextTick(options.onFinish);
    }
}
<|endoftext|>


<commit_before>window.__i10c = {};

window.__i10c.getInput = (inputEle) => {
    return inputEle.val;
}

window.__i10c.setInput = (inputEle, val) => {
    inputEle.value = val;
}

window.__i10c.allInput = () => {
    var elements = document.getElementsByTagName('input');
    for (var i = 0; i < elements.length; i++) {
        console.log("Found " + elements[i].value);
    }
};<commit_msg>Update function name<commit_after>window.__i10c = {};

window.__i10c.getInputValue = (inputEle) => {
    return inputEle.val;
}

window.__i10c.setInputValue = (inputEle, val) => {
    inputEle.value = val;
}

window.__i10c.allInputValue = () => {
    var elements = document.getElementsByTagName('input');
    for (var i = 0; i < elements.length; i++) {
        console.log("Found " + elements[i].value);
    }
};<|endoftext|>