<commit_before>import m from 'mithril';
import prop from 'mithril/stream';
import _ from 'underscore';
import h from '../h';
import railsErrorsVM from '../vms/rails-errors-vm';
import projectGoalVM from '../vms/project-goal-vm';
import popNotification from './pop-notification';
import bigCard from './big-card';
import projectEditSaveBtn from './project-edit-save-btn';

const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_goal');

const projectGoalEdit = {
    oninit: function(vnode) {
        const vm = projectGoalVM,
            mapErrors = [
                  ['mode', ['mode']],
                  ['goal', ['goal']],
                  ['online_days', ['online_days']]
            ],
            showSuccess = h.toggleProp(false, true),
            showError = h.toggleProp(false, true),
            showModeDiff = h.toggleProp(false, true),
            showTaxesDiff = h.toggleProp(false, true),
            applyGoalMask = _.compose(vm.fields.goal, h.applyMonetaryMask),
            loading = prop(false),
            onSubmit = (event) => {
                loading(true);
                m.redraw();
                vm.updateProject(vnode.attrs.projectId).then((data) => {
                    loading(false);
                    vm.e.resetFieldErrors();
                    if (!showSuccess()) { showSuccess.toggle(); }
                    if (showError()) { showError.toggle(); }
                    railsErrorsVM.validatePublish();
                }).catch((err) => {
                    if (err.errors_json) {
                        railsErrorsVM.mapRailsErrors(err.errors_json, mapErrors, vm.e);
                    }
                    loading(false);
                    if (showSuccess()) { showSuccess.toggle(); }
                    if (!showError()) { showError.toggle(); }
                });
                return false;
            };

        if (railsErrorsVM.railsErrors()) {
            railsErrorsVM.mapRailsErrors(railsErrorsVM.railsErrors(), mapErrors, vm.e);
        }
        vm.fillFields(vnode.attrs.project);

        vnode.state = {
            onSubmit,
            showSuccess,
            showError,
            showModeDiff,
            showTaxesDiff,
            vm,
            applyGoalMask,
            loading
        };
    },
    view: function({state, attrs}) {
        const vm = state.vm;
        return m('#goal-tab', [
            (state.showSuccess() ? m(popNotification, {
                message: window.I18n.t('shared.successful_update'),
                toggleOpt: state.showSuccess
            }) : ''),
            (state.showError() ? m(popNotification, {
                message: window.I18n.t('shared.failed_update'),
                toggleOpt: state.showError,
                error: true
            }) : ''),

            m('form.w-form', { onsubmit: state.onSubmit }, [
                m('.w-container', [
                    m('.w-row', [
                        m('.w-col.w-col-10.w-col-push-1', [
                            m(bigCard, {
                                label: window.I18n.t('mode_label', I18nScope()),
                                label_hint: window.I18n.t('mode_hint', I18nScope()),
                                children: [
                                    m('.flex-row.u-marginbottom-30', [
                                        m('a.choose-mode.choose-aon.w-inline-block.btn-select.flex-column.u-text-center[data-mode="aon"][href="javascript:void(0);"]', {
                                            onclick: vm.genClickChangeMode('aon'),
                                            class: vm.fields.mode() == 'aon' ? 'selected' : false
                                        }, [
                                            m('img[alt="Badge aon"][src="/assets/catarse_bootstrap/badge-aon.png"]')
                                        ]),
                                        m('a.choose-mode.choose-flex.w-inline-block.btn-select.flex-column.u-text-center[data-mode="flex"][href="javascript:void(0);"]', {
                                            onclick: vm.genClickChangeMode('flex'),
                                            class: vm.fields.mode() == 'flex' ? 'selected' : false
                                        }, [
                                            m('img[alt="Badge flex"][src="/assets/catarse_bootstrap/badge-flex.png"]')
                                        ])
                                    ]),
                                    m('.u-text-center.fontsize-smaller', [
                                        m('a.mode-diff-toggle.link-hidden-light.fontweight-semibold[href="javascript:void(0);"]', { onclick: state.showModeDiff.toggle }, [
                                            'Veja a diferença entre os modelos ',
                                            m('span.fa.fa-chevron-down')
                                        ])
                                    ]),
                                    (state.showModeDiff() ? m('.mode-diff.u-margintop-30', [
                                        m('.flex-row', [
                                            m('.w-hidden-small.w-hidden-tiny.fontsize-smaller.flex-column', m.trust(window.I18n.t('aon_diff_html', I18nScope()))),
                                            m('.w-hidden-small.w-hidden-tiny.fontsize-smaller.flex-column', m.trust(window.I18n.t('flex_diff_html', I18nScope())))
                                        ]),
                                        m('.u-text-center.u-margintop-30', [
                                            m('.divider.u-marginbottom-20'),
                                            m('.fontsize-base', window.I18n.t('want_more', I18nScope())),
                                            m.trust(window.I18n.t('mode_diff_ebook', I18nScope()))
                                        ])
                                    ]) : '')
                                ]
                            }),
                            m(bigCard, {
                                label: window.I18n.t('goal_label', I18nScope()),
                                label_hint: window.I18n.t('goal_hint', I18nScope()),
                                children: [
                                    m('.w-row.u-marginbottom-30', [
                                        m('.w-col.w-col-2'),
                                        m('.w-col.w-col-8', [
                                            m('.w-row', [
                                                m('.w-col.w-col-4.w-col-small-6.w-col-tiny-6.text-field.prefix.no-hover.medium.prefix-permalink', [
                                                    m('.fontcolor-secondary.u-text-center.fontsize-base.lineheight-tightest', 'R$')
                                                ]),
                                                m('.w-col.w-col-8.w-col-small-6.w-col-tiny-6.label-hide',
                                                    [
                                                        m('.input.tel.optional.project_goal', [
                                                            m('label.field-label'),
                                                            m('input.string.optional.w-input.text-field.postfix.positive.medium[autocomplete="off"][id="project-goal-input"][name="project[goal]"][type="tel"]', {
                                                                class: vm.e.hasError('goal') ? 'error' : false,
                                                                value: vm.fields.goal(),
                                                                maxlength: 14,
                                                                onkeyup: m.withAttr('value', state.applyGoalMask)
                                                            }),
                                                        ]),
                                                    ])
                                            ]),
                                            m('.u-text-center', vm.e.inlineError('goal'))
                                        ]),
                                        m('.w-col.w-col-2')
                                    ]),
                                    m('.u-text-center.fontsize-smaller.fontweight-semibold', [
                                        m('a.fee-toggle.link-hidden-light[href="javascript:void(0)"]', {
                                            onclick: state.showTaxesDiff.toggle
                                        }, [
                                            window.I18n.t('goal_taxes_link', I18nScope()),
                                            m('span.fa.fa-chevron-down')
                                        ])
                                    ]),
                                    (state.showTaxesDiff() ? m('.fee-explanation.u-margintop-30', [
                                        m('.u-marginbottom-30', [
                                            m('.fontsize-small.fontweight-semibold', window.I18n.t('goal_taxes_label', I18nScope())),
                                            m('.fontsize-smaller', window.I18n.t(`goal_${vm.fields.mode()}_taxes_hint`, I18nScope()))
                                        ]),
                                        m('.u-text-center.u-margintop-30', [
                                            m('.divider.u-marginbottom-20'),
                                            m('.fontsize-base', window.I18n.t('want_more', I18nScope())),
                                            m.trust(window.I18n.t('goal_taxes_watch_video_html', I18nScope()))
                                        ])
                                    ]) : ''),
                                ]
                            }),
                            m(bigCard, {
                                label: window.I18n.t('online_days_label', I18nScope()),
                                label_hint: m.trust(window.I18n.t(`online_days_${vm.fields.mode()}_hint`, I18nScope())),
                                children: (vm.fields.mode() == 'aon' ? [
                                    m('.w-row', [
                                        m('.w-col.w-col-2'),
                                        m('.w-col.w-col-8', [
                                            m('.w-row', [
                                                m('.w-col.w-col-8.w-col-tiny-6.w-col-small-6.label-hide', [
                                                    m('.input.integer.optional.disabled.project_online_days', [
                                                        m('label.field-label'),
                                                        m('input.numeric.integer.optional.disabled.w-input.text-field.positive.medium[id="project_online_days"][name="project[online_days]"][type="number"]', {
                                                            onchange: m.withAttr('value', vm.fields.online_days),
                                                            value: vm.fields.online_days(),
                                                            class: vm.e.hasError('online_days') ? 'error' : false
                                                        })
                                                    ])
                                                ]),
                                                m('.w-col.w-col-4.w-col-tiny-6.w-col-small-6', [
                                                    m('.text-field.medium.prefix-permalink.u-text-center', [
                                                        m('', 'dias')])
                                                ])
                                            ]),
                                            vm.e.inlineError('online_days')
                                        ])
                                    ])
                                ] : [
                                    m('.flex-row', [
                                        m('a.choose-time.choose-unlimited.w-inline-block.btn-select.flex-column.u-text-center', {
                                            class: _.isEmpty(vm.fields.online_days().toString()) ? 'selected' : '',
                                            onclick: () => { vm.fields.online_days(''); }
                                        }, [
                                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20', window.I18n.t('online_days_open', I18nScope())),
                                            m('.w-hidden-tiny', window.I18n.t('online_days_open_hint', I18nScope())),
                                        ]),
                                        m('a.choose-time.choose-limited.w-inline-block.btn-select.flex-column.u-text-center', {
                                            class: _.isEmpty(vm.fields.online_days().toString()) ? '' : 'selected',
                                            onclick: () => { vm.fields.online_days(1); }
                                        }, [
                                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20', window.I18n.t('online_days_closed', I18nScope())),
                                            m('.w-hidden-tiny.u-marginbottom-30', window.I18n.t('online_days_closed_hint', I18nScope())),
                                            m('.w-row', [
                                                m('.w-col.w-col-6.w-col-tiny-6.w-col-small-6.label-hide', [
                                                    m('.input.integer.optional.project_online_days', [
                                                        m('label.field-label'),
                                                        m('input.numeric.integer.optional.w-input.text-field.field.w-input.text-field.medium.prefix[id="project_online_days"][name="project[online_days]"][type="number"]', {
                                                            onchange: m.withAttr('value', vm.fields.online_days),
                                                            value: vm.fields.online_days(),
                                                            class: vm.e.hasError('online_days') ? 'error' : false
                                                        })
                                                    ]),
                                                ]),
                                                m('.w-col.w-col-6.w-col-tiny-6.w-col-small-6', [
                                                    m('.text-field.medium.prefix-permalink', {
                                                        class: vm.e.hasError('online_days') ? 'error' : false
                                                    }, [
                                                        m('', 'dias')
                                                    ])
                                                ])
                                            ]),
                                            m('.w-row', vm.e.inlineError('online_days'))
                                        ])
                                    ])
                                ])
                            })
                        ])
                    ])
                ]),
                m(projectEditSaveBtn, { loading: state.loading, onSubmit: state.onSubmit })
            ])

        ]);
    }
};

export default projectGoalEdit;
<commit_msg>remove percentage from differences between aon and flex<commit_after>import m from 'mithril';
import prop from 'mithril/stream';
import _ from 'underscore';
import h from '../h';
import railsErrorsVM from '../vms/rails-errors-vm';
import projectGoalVM from '../vms/project-goal-vm';
import popNotification from './pop-notification';
import bigCard from './big-card';
import projectEditSaveBtn from './project-edit-save-btn';

const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_goal');

const projectGoalEdit = {
    oninit: function(vnode) {
        const vm = projectGoalVM,
            mapErrors = [
                  ['mode', ['mode']],
                  ['goal', ['goal']],
                  ['online_days', ['online_days']]
            ],
            showSuccess = h.toggleProp(false, true),
            showError = h.toggleProp(false, true),
            showModeDiff = h.toggleProp(false, true),
            showTaxesDiff = h.toggleProp(false, true),
            applyGoalMask = _.compose(vm.fields.goal, h.applyMonetaryMask),
            loading = prop(false),
            onSubmit = (event) => {
                loading(true);
                m.redraw();
                vm.updateProject(vnode.attrs.projectId).then((data) => {
                    loading(false);
                    vm.e.resetFieldErrors();
                    if (!showSuccess()) { showSuccess.toggle(); }
                    if (showError()) { showError.toggle(); }
                    railsErrorsVM.validatePublish();
                }).catch((err) => {
                    if (err.errors_json) {
                        railsErrorsVM.mapRailsErrors(err.errors_json, mapErrors, vm.e);
                    }
                    loading(false);
                    if (showSuccess()) { showSuccess.toggle(); }
                    if (!showError()) { showError.toggle(); }
                });
                return false;
            };

        if (railsErrorsVM.railsErrors()) {
            railsErrorsVM.mapRailsErrors(railsErrorsVM.railsErrors(), mapErrors, vm.e);
        }
        vm.fillFields(vnode.attrs.project);

        const project = vnode.attrs.project;
        const projectSolidarityIntegration = (project.integrations || []).find(integration => integration.name === 'SOLIDARITY_SERVICE_FEE');
        const isSolidarityProject = !_.isEmpty(projectSolidarityIntegration);
        console.log('isSolidarityProject', isSolidarityProject);

        vnode.state = {
            onSubmit,
            showSuccess,
            showError,
            showModeDiff,
            showTaxesDiff,
            vm,
            applyGoalMask,
            loading,
            isSolidarityProject,
        };
    },
    view: function({state, attrs}) {
        const vm = state.vm;
        const isSolidarityProject = state.isSolidarityProject;
        const project = vnode.attrs.project;

        return m('#goal-tab', [
            (state.showSuccess() ? m(popNotification, {
                message: window.I18n.t('shared.successful_update'),
                toggleOpt: state.showSuccess
            }) : ''),
            (state.showError() ? m(popNotification, {
                message: window.I18n.t('shared.failed_update'),
                toggleOpt: state.showError,
                error: true
            }) : ''),

            m('form.w-form', { onsubmit: state.onSubmit }, [
                m('.w-container', [
                    m('.w-row', [
                        m('.w-col.w-col-10.w-col-push-1', [
                            m(bigCard, {
                                label: window.I18n.t('mode_label', I18nScope()),
                                label_hint: window.I18n.t('mode_hint', I18nScope()),
                                children: [
                                    m('.flex-row.u-marginbottom-30', [
                                        m('a.choose-mode.choose-aon.w-inline-block.btn-select.flex-column.u-text-center[data-mode="aon"][href="javascript:void(0);"]', {
                                            onclick: vm.genClickChangeMode('aon'),
                                            class: vm.fields.mode() == 'aon' ? 'selected' : false
                                        }, [
                                            m('img[alt="Badge aon"][src="/assets/catarse_bootstrap/badge-aon.png"]')
                                        ]),
                                        m('a.choose-mode.choose-flex.w-inline-block.btn-select.flex-column.u-text-center[data-mode="flex"][href="javascript:void(0);"]', {
                                            onclick: vm.genClickChangeMode('flex'),
                                            class: vm.fields.mode() == 'flex' ? 'selected' : false
                                        }, [
                                            m('img[alt="Badge flex"][src="/assets/catarse_bootstrap/badge-flex.png"]')
                                        ])
                                    ]),
                                    m('.u-text-center.fontsize-smaller', [
                                        m('a.mode-diff-toggle.link-hidden-light.fontweight-semibold[href="javascript:void(0);"]', { onclick: state.showModeDiff.toggle }, [
                                            'Veja a diferença entre os modelos ',
                                            m('span.fa.fa-chevron-down')
                                        ])
                                    ]),
                                    (state.showModeDiff() ? m('.mode-diff.u-margintop-30', [
                                        m('.flex-row', [
                                            m('.w-hidden-small.w-hidden-tiny.fontsize-smaller.flex-column', [
                                                m.trust(window.I18n.t('aon_diff_html', I18nScope())),
                                                (
                                                    isSolidarityProject ?
                                                        null
                                                    :
                                                        m.trust(window.I18n.t('aon_diff_fees_html', I18nScope({ percentage: 13 })))
                                                )
                                            ]),
                                            m('.w-hidden-small.w-hidden-tiny.fontsize-smaller.flex-column', [
                                                m.trust(window.I18n.t('flex_diff_html', I18nScope())),
                                                (
                                                    isSolidarityProject ?
                                                        null
                                                    :
                                                        m.trust(window.I18n.t('flex_diff_fees_html', I18nScope({ percentage: 13 })))
                                                )
                                            ])
                                        ]),
                                        m('.u-text-center.u-margintop-30', [
                                            m('.divider.u-marginbottom-20'),
                                            m('.fontsize-base', window.I18n.t('want_more', I18nScope())),
                                            m.trust(window.I18n.t('mode_diff_ebook', I18nScope()))
                                        ])
                                    ]) : '')
                                ]
                            }),
                            m(bigCard, {
                                label: window.I18n.t('goal_label', I18nScope()),
                                label_hint: window.I18n.t('goal_hint', I18nScope()),
                                children: [
                                    m('.w-row.u-marginbottom-30', [
                                        m('.w-col.w-col-2'),
                                        m('.w-col.w-col-8', [
                                            m('.w-row', [
                                                m('.w-col.w-col-4.w-col-small-6.w-col-tiny-6.text-field.prefix.no-hover.medium.prefix-permalink', [
                                                    m('.fontcolor-secondary.u-text-center.fontsize-base.lineheight-tightest', 'R$')
                                                ]),
                                                m('.w-col.w-col-8.w-col-small-6.w-col-tiny-6.label-hide',
                                                    [
                                                        m('.input.tel.optional.project_goal', [
                                                            m('label.field-label'),
                                                            m('input.string.optional.w-input.text-field.postfix.positive.medium[autocomplete="off"][id="project-goal-input"][name="project[goal]"][type="tel"]', {
                                                                class: vm.e.hasError('goal') ? 'error' : false,
                                                                value: vm.fields.goal(),
                                                                maxlength: 14,
                                                                onkeyup: m.withAttr('value', state.applyGoalMask)
                                                            }),
                                                        ]),
                                                    ])
                                            ]),
                                            m('.u-text-center', vm.e.inlineError('goal'))
                                        ]),
                                        m('.w-col.w-col-2')
                                    ]),
                                    m('.u-text-center.fontsize-smaller.fontweight-semibold', [
                                        m('a.fee-toggle.link-hidden-light[href="javascript:void(0)"]', {
                                            onclick: state.showTaxesDiff.toggle
                                        }, [
                                            window.I18n.t('goal_taxes_link', I18nScope()),
                                            m('span.fa.fa-chevron-down')
                                        ])
                                    ]),
                                    (state.showTaxesDiff() ? m('.fee-explanation.u-margintop-30', [
                                        m('.u-marginbottom-30', [
                                            m('.fontsize-small.fontweight-semibold', window.I18n.t('goal_taxes_label', I18nScope())),
                                            m('.fontsize-smaller', window.I18n.t(`goal_${vm.fields.mode()}_taxes_hint`, I18nScope()))
                                        ]),
                                        m('.u-text-center.u-margintop-30', [
                                            m('.divider.u-marginbottom-20'),
                                            m('.fontsize-base', window.I18n.t('want_more', I18nScope())),
                                            m.trust(window.I18n.t('goal_taxes_watch_video_html', I18nScope()))
                                        ])
                                    ]) : ''),
                                ]
                            }),
                            m(bigCard, {
                                label: window.I18n.t('online_days_label', I18nScope()),
                                label_hint: m.trust(window.I18n.t(`online_days_${vm.fields.mode()}_hint`, I18nScope())),
                                children: (vm.fields.mode() == 'aon' ? [
                                    m('.w-row', [
                                        m('.w-col.w-col-2'),
                                        m('.w-col.w-col-8', [
                                            m('.w-row', [
                                                m('.w-col.w-col-8.w-col-tiny-6.w-col-small-6.label-hide', [
                                                    m('.input.integer.optional.disabled.project_online_days', [
                                                        m('label.field-label'),
                                                        m('input.numeric.integer.optional.disabled.w-input.text-field.positive.medium[id="project_online_days"][name="project[online_days]"][type="number"]', {
                                                            onchange: m.withAttr('value', vm.fields.online_days),
                                                            value: vm.fields.online_days(),
                                                            class: vm.e.hasError('online_days') ? 'error' : false
                                                        })
                                                    ])
                                                ]),
                                                m('.w-col.w-col-4.w-col-tiny-6.w-col-small-6', [
                                                    m('.text-field.medium.prefix-permalink.u-text-center', [
                                                        m('', 'dias')])
                                                ])
                                            ]),
                                            vm.e.inlineError('online_days')
                                        ])
                                    ])
                                ] : [
                                    m('.flex-row', [
                                        m('a.choose-time.choose-unlimited.w-inline-block.btn-select.flex-column.u-text-center', {
                                            class: _.isEmpty(vm.fields.online_days().toString()) ? 'selected' : '',
                                            onclick: () => { vm.fields.online_days(''); }
                                        }, [
                                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20', window.I18n.t('online_days_open', I18nScope())),
                                            m('.w-hidden-tiny', window.I18n.t('online_days_open_hint', I18nScope())),
                                        ]),
                                        m('a.choose-time.choose-limited.w-inline-block.btn-select.flex-column.u-text-center', {
                                            class: _.isEmpty(vm.fields.online_days().toString()) ? '' : 'selected',
                                            onclick: () => { vm.fields.online_days(1); }
                                        }, [
                                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20', window.I18n.t('online_days_closed', I18nScope())),
                                            m('.w-hidden-tiny.u-marginbottom-30', window.I18n.t('online_days_closed_hint', I18nScope())),
                                            m('.w-row', [
                                                m('.w-col.w-col-6.w-col-tiny-6.w-col-small-6.label-hide', [
                                                    m('.input.integer.optional.project_online_days', [
                                                        m('label.field-label'),
                                                        m('input.numeric.integer.optional.w-input.text-field.field.w-input.text-field.medium.prefix[id="project_online_days"][name="project[online_days]"][type="number"]', {
                                                            onchange: m.withAttr('value', vm.fields.online_days),
                                                            value: vm.fields.online_days(),
                                                            class: vm.e.hasError('online_days') ? 'error' : false
                                                        })
                                                    ]),
                                                ]),
                                                m('.w-col.w-col-6.w-col-tiny-6.w-col-small-6', [
                                                    m('.text-field.medium.prefix-permalink', {
                                                        class: vm.e.hasError('online_days') ? 'error' : false
                                                    }, [
                                                        m('', 'dias')
                                                    ])
                                                ])
                                            ]),
                                            m('.w-row', vm.e.inlineError('online_days'))
                                        ])
                                    ])
                                ])
                            })
                        ])
                    ])
                ]),
                m(projectEditSaveBtn, { loading: state.loading, onSubmit: state.onSubmit })
            ])

        ]);
    }
};

export default projectGoalEdit;
<|endoftext|>


<commit_before>/*
 * @package jsDAV
 * @subpackage CalDAV
 * @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl>
 * @author Oleg Elifantiev <oleg@elifantiev.ru>
 * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
 */

"use strict";

var Base = require('./../shared/base');
var Util = require("./../shared/util");
var Exc = require("./../shared/exceptions");
var Xml = require("./../shared/xml");
var xpath = require('xpath');
var XPathResult = xpath.XPathResult;
var jsVObject_DateTimeParser = require('./../VObject/dateTimeParser');

function xSelect(expr, doc, single) {

    var nodesWithXMLNS = xpath.select("//@*[starts-with(name(), 'xmlns:')]", doc);
    var revmap = {};

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

        revmap[node.nodeName.substr(6)] = node.nodeValue;
    }

    // FIXME THIS IS UGLY!
    var expression = xpath.createExpression(expr, {

        lookupNamespaceURI: function(short) {
            if(short in revmap) {
                return revmap[short];
            }
            for(var fullNs in Xml.xmlNamespaces) {
                if(Xml.xmlNamespaces.hasOwnProperty(fullNs)) {
                    if(Xml.xmlNamespaces[fullNs] == short) {
                        revmap[short] = fullNs;
                        return fullNs;
                    }
                }
            }
            return null;
        }
    });
    var type = XPathResult.ANY_TYPE;

    var result = expression.evaluate(doc, type, null);

    if (result.resultType == XPathResult.STRING_TYPE) {
        result = result.stringValue;
    }
    else if (result.resultType == XPathResult.NUMBER_TYPE) {
        result = result.numberValue;
    }
    else if (result.resultType == XPathResult.BOOLEAN_TYPE) {
        result = result.booleanValue;
    }
    else {
        result = result.nodes;
        if (single) {
            result = result[0];
        }
    }

    return result;
}

var jsCalDAV_CalendarQueryParser = module.exports = Base.extend({

    dom: null,
    filters: null,
    requestedProperties: null,
    expand: null,

    initialize: function(dom) {

        this.dom = dom;
        //this.xpath = new \DOMXPath($dom);
        //this.xpath.registerNameSpace('cal',Plugin::NS_CALDAV);
        //this.xpath.registerNameSpace('dav','urn:DAV');
    },

    _parseExpand: function (parentNode) {

        var start, end;

        start = parentNode.getAttribute('start');
        if(!start) {
            throw Exc.BadRequest('The "start" attribute is required for the CALDAV:expand element');
        }
        start = jsVObject_DateTimeParser.parseDateTime(start);

        end = parentNode.getAttribute('end');
        if(!end) {
            throw Exc.BadRequest('The "end" attribute is required for the CALDAV:expand element');
        }

        end = jsVObject_DateTimeParser.parseDateTime(end);

        if (end <= start) {
            throw Exc.BadRequest('The end-date must be larger than the start-date in the expand element.');
        }

        return {
            'start': start,
            'end': end
        };

    },
    parse: function() {
        var expand,
            filter,
            compFilters;

        filter = xSelect('/cal:calendar-query/cal:filter', this.dom);
        if (filter.length !== 1) {
            throw Exc.BadRequest('Only one filter element is allowed');
        }

        compFilters = this._parseCompFilters(filter[0]);
        if (compFilters.length !==1) {
            throw Exc.BadRequest('There must be exactly 1 top-level comp-filter.');
        }

        this.filters = compFilters[0];
        this.requestedProperties = Object.keys(Xml.parseProperties(this.dom));

        expand = xSelect('/cal:calendar-query/dav:prop/cal:calendar-data/cal:expand', this.dom);
        if (expand.length > 0) {
            this.expand = this._parseExpand(expand[0]);
        }
    },

    _parseParamFilters: function (parentNode) {
        var paramFilterNodes,
            paramFilterNode,
            paramFilter,
            result = [];

        paramFilterNodes = xSelect('cal:param-filter', parentNode);

        for(var i= 0, l = paramFilterNodes.length; i < l; i++) {

            paramFilterNode = paramFilterNodes[i];
            paramFilter = {};
            paramFilter['name'] = paramFilterNode.getAttribute('name');
            paramFilter['is-not-defined'] = xSelect('cal:is-not-defined', paramFilterNode).length > 0;
            paramFilter['text-match'] = this._parseTextMatch(paramFilterNode);

            result.push(paramFilter);

        }

        return result;
    },

    _parseTextMatch: function (parentNode) {
        var textMatchNodes,
            textMatchNode,
            negateCondition,
            collation;

        textMatchNodes = this.xpath.query('cal:text-match', parentNode);

        if (textMatchNodes.length === 0) {
            return null;
        }

        textMatchNode = textMatchNodes[0];
        negateCondition = textMatchNode.getAttribute('negate-condition');
        negateCondition = negateCondition === 'yes';
        collation = textMatchNode.getAttribute('collation');
        if (!collation) {
            collation = 'i;ascii-casemap';
        }

        return {
            'negate-condition': negateCondition,
            'collation': collation,
            'value': textMatchNode.nodeValue
        };
    },

    _parsePropFilters: function (parentNode) {
        var propFilterNodes,
            propFilterNode,
            propFilter,
            result = [];

        propFilterNodes = xSelect('cal:prop-filter', parentNode);

        for (var i= 0, l = propFilterNodes.length; i < l; i++) {

            propFilterNode = propFilterNodes[i];
            propFilter = {};
            propFilter['name'] = propFilterNode.getAttribute('name');
            propFilter['is-not-defined'] = xSelect('cal:is-not-defined', propFilterNode).length > 0;
            propFilter['param-filters'] = this._parseParamFilters(propFilterNode);
            propFilter['text-match'] = this._parseTextMatch(propFilterNode);
            propFilter['time-range'] = this._parseTimeRange(propFilterNode);

            result.push(propFilter);

        }

        return result;

    },

    _parseTimeRange: function (parentNode) {

        var timeRangeNodes,
            timeRangeNode,
            start, end;

        timeRangeNodes = xSelect('cal:time-range', parentNode);

        if (timeRangeNodes.length === 0) {
            return null;
        }

        timeRangeNode = timeRangeNodes[0];

        if (start = timeRangeNode.getAttribute('start')) {
            start = jsVObject_DateTimeParser.parseDateTime(start);
        } else {
            start = null;
        }
        if (end = timeRangeNode.getAttribute('end')) {
            end = jsVObject_DateTimeParser.parseDateTime(end);
        } else {
            end = null;
        }

        if (start && end && end <= start) {
            throw Exc.BadRequest('The end-date must be larger than the start-date in the time-range filter');
        }

        return {
            'start': start,
            'end': end
        };
    },

    _parseCompFilters: function(parentNode) {
        var result = [],
            eventTypes = { 'VEVENT': 1, 'VTODO': 1, 'VJOURNAL': 1, 'VFREEBUSY': 1, 'VALARM': 1},
            compFilterNodes,
            compFilterNode,
            compFilter;

        compFilterNodes = xSelect('cal:comp-filter', parentNode);

        for(var i= 0, l = compFilterNodes.length; i < l; i++) {

            compFilterNode = compFilterNodes[i];

            compFilter = {};
            compFilter['name'] = compFilterNode.getAttribute('name');
            compFilter['is-not-defined'] = xSelect('cal:is-not-defined', compFilterNode).length > 0;
            compFilter['comp-filters'] = this._parseCompFilters(compFilterNode);
            compFilter['prop-filters'] = this._parsePropFilters(compFilterNode);
            compFilter['time-range'] = this._parseTimeRange(compFilterNode);

            if (compFilter['time-range'] && !(compFilter['name'] in eventTypes)) {
                throw Exc.BadRequest('The time-range filter is not defined for the ' + compFilter['name'] + ' component');
            }

            result.push(compFilter);

        }

        return result;
    }

});<commit_msg>Fixed incorrect textMatch parsing<commit_after>/*
 * @package jsDAV
 * @subpackage CalDAV
 * @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl>
 * @author Oleg Elifantiev <oleg@elifantiev.ru>
 * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
 */

"use strict";

var Base = require('./../shared/base');
var Util = require("./../shared/util");
var Exc = require("./../shared/exceptions");
var Xml = require("./../shared/xml");
var xpath = require('xpath');
var XPathResult = xpath.XPathResult;
var jsVObject_DateTimeParser = require('./../VObject/dateTimeParser');

function xSelect(expr, doc, single) {

    var nodesWithXMLNS = xpath.select("//@*[starts-with(name(), 'xmlns:')]", doc);
    var revmap = {};

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

        revmap[node.nodeName.substr(6)] = node.nodeValue;
    }

    // FIXME THIS IS UGLY!
    var expression = xpath.createExpression(expr, {

        lookupNamespaceURI: function(short) {
            if(short in revmap) {
                return revmap[short];
            }
            for(var fullNs in Xml.xmlNamespaces) {
                if(Xml.xmlNamespaces.hasOwnProperty(fullNs)) {
                    if(Xml.xmlNamespaces[fullNs] == short) {
                        revmap[short] = fullNs;
                        return fullNs;
                    }
                }
            }
            return null;
        }
    });
    var type = XPathResult.ANY_TYPE;

    var result = expression.evaluate(doc, type, null);

    if (result.resultType == XPathResult.STRING_TYPE) {
        result = result.stringValue;
    }
    else if (result.resultType == XPathResult.NUMBER_TYPE) {
        result = result.numberValue;
    }
    else if (result.resultType == XPathResult.BOOLEAN_TYPE) {
        result = result.booleanValue;
    }
    else {
        result = result.nodes;
        if (single) {
            result = result[0];
        }
    }

    return result;
}

var jsCalDAV_CalendarQueryParser = module.exports = Base.extend({

    dom: null,
    filters: null,
    requestedProperties: null,
    expand: null,

    initialize: function(dom) {

        this.dom = dom;
        //this.xpath = new \DOMXPath($dom);
        //this.xpath.registerNameSpace('cal',Plugin::NS_CALDAV);
        //this.xpath.registerNameSpace('dav','urn:DAV');
    },

    _parseExpand: function (parentNode) {

        var start, end;

        start = parentNode.getAttribute('start');
        if(!start) {
            throw Exc.BadRequest('The "start" attribute is required for the CALDAV:expand element');
        }
        start = jsVObject_DateTimeParser.parseDateTime(start);

        end = parentNode.getAttribute('end');
        if(!end) {
            throw Exc.BadRequest('The "end" attribute is required for the CALDAV:expand element');
        }

        end = jsVObject_DateTimeParser.parseDateTime(end);

        if (end <= start) {
            throw Exc.BadRequest('The end-date must be larger than the start-date in the expand element.');
        }

        return {
            'start': start,
            'end': end
        };

    },
    parse: function() {
        var expand,
            filter,
            compFilters;

        filter = xSelect('/cal:calendar-query/cal:filter', this.dom);
        if (filter.length !== 1) {
            throw Exc.BadRequest('Only one filter element is allowed');
        }

        compFilters = this._parseCompFilters(filter[0]);
        if (compFilters.length !==1) {
            throw Exc.BadRequest('There must be exactly 1 top-level comp-filter.');
        }

        this.filters = compFilters[0];
        this.requestedProperties = Object.keys(Xml.parseProperties(this.dom));

        expand = xSelect('/cal:calendar-query/dav:prop/cal:calendar-data/cal:expand', this.dom);
        if (expand.length > 0) {
            this.expand = this._parseExpand(expand[0]);
        }
    },

    _parseParamFilters: function (parentNode) {
        var paramFilterNodes,
            paramFilterNode,
            paramFilter,
            result = [];

        paramFilterNodes = xSelect('cal:param-filter', parentNode);

        for(var i= 0, l = paramFilterNodes.length; i < l; i++) {

            paramFilterNode = paramFilterNodes[i];
            paramFilter = {};
            paramFilter['name'] = paramFilterNode.getAttribute('name');
            paramFilter['is-not-defined'] = xSelect('cal:is-not-defined', paramFilterNode).length > 0;
            paramFilter['text-match'] = this._parseTextMatch(paramFilterNode);

            result.push(paramFilter);

        }

        return result;
    },

    _parseTextMatch: function (parentNode) {
        var textMatchNodes,
            textMatchNode,
            negateCondition,
            collation;

        textMatchNodes = xSelect('//cal:text-match', parentNode);

        if (textMatchNodes.length === 0) {
            return null;
        }

        textMatchNode = textMatchNodes[0];
        negateCondition = textMatchNode.getAttribute('negate-condition');
        negateCondition = negateCondition === 'yes';
        collation = textMatchNode.getAttribute('collation');
        if (!collation) {
            collation = 'i;ascii-casemap';
        }

        return {
            'negate-condition': negateCondition,
            'collation': collation,
            'value': textMatchNode.textContent
        };
    },

    _parsePropFilters: function (parentNode) {
        var propFilterNodes,
            propFilterNode,
            propFilter,
            result = [];

        propFilterNodes = xSelect('cal:prop-filter', parentNode);

        for (var i= 0, l = propFilterNodes.length; i < l; i++) {

            propFilterNode = propFilterNodes[i];
            propFilter = {};
            propFilter['name'] = propFilterNode.getAttribute('name');
            propFilter['is-not-defined'] = xSelect('cal:is-not-defined', propFilterNode).length > 0;
            propFilter['param-filters'] = this._parseParamFilters(propFilterNode);
            propFilter['text-match'] = this._parseTextMatch(propFilterNode);
            propFilter['time-range'] = this._parseTimeRange(propFilterNode);

            result.push(propFilter);

        }

        return result;

    },

    _parseTimeRange: function (parentNode) {

        var timeRangeNodes,
            timeRangeNode,
            start, end;

        timeRangeNodes = xSelect('cal:time-range', parentNode);

        if (timeRangeNodes.length === 0) {
            return null;
        }

        timeRangeNode = timeRangeNodes[0];

        if (start = timeRangeNode.getAttribute('start')) {
            start = jsVObject_DateTimeParser.parseDateTime(start);
        } else {
            start = null;
        }
        if (end = timeRangeNode.getAttribute('end')) {
            end = jsVObject_DateTimeParser.parseDateTime(end);
        } else {
            end = null;
        }

        if (start && end && end <= start) {
            throw Exc.BadRequest('The end-date must be larger than the start-date in the time-range filter');
        }

        return {
            'start': start,
            'end': end
        };
    },

    _parseCompFilters: function(parentNode) {
        var result = [],
            eventTypes = { 'VEVENT': 1, 'VTODO': 1, 'VJOURNAL': 1, 'VFREEBUSY': 1, 'VALARM': 1},
            compFilterNodes,
            compFilterNode,
            compFilter;

        compFilterNodes = xSelect('cal:comp-filter', parentNode);

        for(var i= 0, l = compFilterNodes.length; i < l; i++) {

            compFilterNode = compFilterNodes[i];

            compFilter = {};
            compFilter['name'] = compFilterNode.getAttribute('name');
            compFilter['is-not-defined'] = xSelect('cal:is-not-defined', compFilterNode).length > 0;
            compFilter['comp-filters'] = this._parseCompFilters(compFilterNode);
            compFilter['prop-filters'] = this._parsePropFilters(compFilterNode);
            compFilter['time-range'] = this._parseTimeRange(compFilterNode);

            if (compFilter['time-range'] && !(compFilter['name'] in eventTypes)) {
                throw Exc.BadRequest('The time-range filter is not defined for the ' + compFilter['name'] + ' component');
            }

            result.push(compFilter);

        }

        return result;
    }

});<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Curve');

test('Curve#getPointAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var points = [
		[0, new Point(0, 100)],
		[0.25, new Point(7.8585, 61.07549)],
		[0.5, new Point(29.28932, 29.28932)],
		[0.75, new Point(61.07549, 7.8585)],
		[1, new Point(100, 0)]
	];

	for (var i = 0; i < points.length; i++) {
		var entry = points[i];
		comparePoints(curve.getPointAt(entry[0], true), entry[1],
				'curve.getPointAt(' + entry[0] + ', true);');
	}
});

test('Curve#getTangentAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var points = [
		[0, new Point(0, -165.68542 )],
		[0.25, new Point(60.7233, -143.56602)],
		[0.5, new Point(108.57864, -108.57864)],
		[0.75, new Point(143.56602, -60.7233)],
		[1, new Point(165.68542, 0)]
	];

	for (var i = 0; i < points.length; i++) {
		var entry = points[i];
		comparePoints(curve.getTangentAt(entry[0], true), entry[1],
				'curve.getPointAt(' + entry[0] + ', true);');
	}
});

test('Curve#getNormalAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var points = [
		[0, new Point(-165.68542, 0)],
		[0.25, new Point(-143.56602, -60.7233)],
		[0.5, new Point(-108.57864, -108.57864)],
		[0.75, new Point(-60.7233, -143.56602)],
		[1, new Point(0, -165.68542)]
	];

	for (var i = 0; i < points.length; i++) {
		var entry = points[i];
		comparePoints(curve.getNormalAt(entry[0], true), entry[1],
				'curve.getPointAt(' + entry[0] + ', true);');
	}
});
<commit_msg>Implement unit tests for Curve#getCurvatureAt().<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Curve');

test('Curve#getPointAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var points = [
		[0, new Point(0, 100)],
		[0.25, new Point(7.8585, 61.07549)],
		[0.5, new Point(29.28932, 29.28932)],
		[0.75, new Point(61.07549, 7.8585)],
		[1, new Point(100, 0)]
	];

	for (var i = 0; i < points.length; i++) {
		var entry = points[i];
		comparePoints(curve.getPointAt(entry[0], true), entry[1],
				'curve.getPointAt(' + entry[0] + ', true);');
	}
});

test('Curve#getTangentAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var tangents = [
		[0, new Point(0, -165.68542 )],
		[0.25, new Point(60.7233, -143.56602)],
		[0.5, new Point(108.57864, -108.57864)],
		[0.75, new Point(143.56602, -60.7233)],
		[1, new Point(165.68542, 0)]
	];

	for (var i = 0; i < tangents.length; i++) {
		var entry = tangents[i];
		comparePoints(curve.getTangentAt(entry[0], true), entry[1],
				'curve.getTangentAt(' + entry[0] + ', true);');
	}
});

test('Curve#getNormalAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var normals = [
		[0, new Point(-165.68542, 0)],
		[0.25, new Point(-143.56602, -60.7233)],
		[0.5, new Point(-108.57864, -108.57864)],
		[0.75, new Point(-60.7233, -143.56602)],
		[1, new Point(0, -165.68542)]
	];

	for (var i = 0; i < normals.length; i++) {
		var entry = normals[i];
		comparePoints(curve.getNormalAt(entry[0], true), entry[1],
				'curve.getNormalAt(' + entry[0] + ', true);');
	}
});

test('Curve#getCurvatureAt()', function() {
	var curve = new Path.Circle({
		center: [100, 100],
		radius: 100
	}).getFirstCurve();

	var curvatures = [
		[0, 0.009785533905932729],
		[0.25, 0.010062133221584524],
		[0.5, 0.009937576453041297],
		[0.75, 0.010062133221584524],
		[1, 0.009785533905932727]
	];

	for (var i = 0; i < curvatures.length; i++) {
		var entry = curvatures[i];
		compareNumbers(curve.getCurvatureAt(entry[0], true), entry[1],
				'curve.getCurvatureAt(' + entry[0] + ', true);');
	}
});
<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Point');
test('new Point(10, 20)', function() {
	var point = new Point(10, 20);
	equals(point.toString(), '{ x: 10, y: 20 }');
});

test('new Point([10, 20])', function() {
	var point = new Point([10, 20]);
	equals(point.toString(), '{ x: 10, y: 20 }');
});

test('new Point({x: 10, y: 20})', function() {
	var point = new Point({x: 10, y: 20});
	equals(point.toString(), '{ x: 10, y: 20 }');
});

test('new Point(new Size(10, 20))', function() {
	var point = new Point(new Size(10, 20));
	equals(point.toString(), '{ x: 10, y: 20 }');
});

test('new Point({ width: 10, height: 20})', function() {
	var point = new Point({width: 10, height: 20});
	equals(point.toString(), '{ x: 10, y: 20 }');
});

test('new Point({ angle: 45, length: 20})', function() {
	var point = new Point({angle: 40, length: 20});
	equals(point.toString(), '{ x: 15.32089, y: 12.85575 }');
});

module('Point vector operations');

test('normalize(length)', function() {
	var point = new Point(0, 10).normalize(20)
	equals(point.toString(), '{ x: 0, y: 20 }');
});

test('set length', function() {
	var point = new Point(0, 10);
	point.length = 20;
	equals(point.toString(), '{ x: 0, y: 20 }');
});

test('get angle', function() {
	var angle = new Point(0, 10).angle;
    equals(angle, 90);
});

test('getAngle(point)', function() {
	var angle = new Point(0, 10).getAngle([10, 10]);
    equals(Math.round(angle), 45);
});

test('rotate(degrees)', function() {
	var point = new Point(100, 50).rotate(90);
	equals(point.toString(), '{ x: -50, y: 100 }');
});

test('set angle', function() {
	var point = new Point(10, 20);
	point.angle = 92;
    equals(point.angle, 92);
});

test('set angle & length', function() {
	var point1 = new Point();
	point1.length = Math.sqrt(2);
	point1.angle = -45;

	var point2 = new Point();
	point2.angle = -45;
	point2.length = Math.sqrt(2);

	comparePoints(point2, point1);
});

test('getDirectedAngle(point)', function() {
	var angle = new Point(10, 10).getDirectedAngle(new Point(1, 0));
	equals(angle, -45);

	var angle = new Point(-10, 10).getDirectedAngle(new Point(1, 0));
	equals(angle, -135);

	var angle = new Point(-10, -10).getDirectedAngle(new Point(1, 0));
	equals(angle, 135);

	var angle = new Point(10, -10).getDirectedAngle(new Point(1, 0));
	equals(angle, 45);
});

test('equals()', function() {
	equals(function() {
		return new Point(10, 10).equals([10, 10]);
	}, true);

	equals(function() {
		return new Point(0, 0).equals({});
	}, false);

	equals(function() {
		return new Point(0, 0).equals(null);
	}, false);
});
<commit_msg>Use comparePoints() helper in Point tests.<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Point');
test('new Point(10, 20)', function() {
	var point = new Point(10, 20);
	comparePoints(point, { x: 10, y: 20 });
});

test('new Point([10, 20])', function() {
	var point = new Point([10, 20]);
	comparePoints(point, { x: 10, y: 20 });
});

test('new Point({x: 10, y: 20})', function() {
	var point = new Point({x: 10, y: 20});
	comparePoints(point, { x: 10, y: 20 });
});

test('new Point(new Size(10, 20))', function() {
	var point = new Point(new Size(10, 20));
	comparePoints(point, { x: 10, y: 20 });
});

test('new Point({ width: 10, height: 20})', function() {
	var point = new Point({width: 10, height: 20});
	comparePoints(point, { x: 10, y: 20 });
});

test('new Point({ angle: 45, length: 20})', function() {
	var point = new Point({ angle: 40, length: 20 });
	comparePoints(point, new Point(15.32089, 12.85575));
});

module('Point vector operations');

test('normalize(length)', function() {
	var point = new Point(0, 10).normalize(20);
	comparePoints(point, { x: 0, y: 20 });
});

test('set length', function() {
	var point = new Point(0, 10);
	point.length = 20;
	comparePoints(point, { x: 0, y: 20 });
});

test('get angle', function() {
	var angle = new Point(0, 10).angle;
    equals(angle, 90);
});

test('getAngle(point)', function() {
	var angle = new Point(0, 10).getAngle([10, 10]);
    equals(Math.round(angle), 45);
});

test('rotate(degrees)', function() {
	var point = new Point(100, 50).rotate(90);
	comparePoints(point, { x: -50, y: 100 });
});

test('set angle', function() {
	var point = new Point(10, 20);
	point.angle = 92;
    equals(point.angle, 92);
	comparePoints(point, new Point({
		angle: 92,
		length: Math.sqrt(10 * 10 + 20 * 20)
	}));
});

test('set angle & length', function() {
	var point1 = new Point();
	point1.length = Math.sqrt(2);
	point1.angle = -45;

	var point2 = new Point();
	point2.angle = -45;
	point2.length = Math.sqrt(2);

	comparePoints(point2, point1);
});

test('getDirectedAngle(point)', function() {
	var angle = new Point(10, 10).getDirectedAngle(new Point(1, 0));
	equals(angle, -45);

	var angle = new Point(-10, 10).getDirectedAngle(new Point(1, 0));
	equals(angle, -135);

	var angle = new Point(-10, -10).getDirectedAngle(new Point(1, 0));
	equals(angle, 135);

	var angle = new Point(10, -10).getDirectedAngle(new Point(1, 0));
	equals(angle, 45);
});

test('equals()', function() {
	equals(function() {
		return new Point(10, 10).equals([10, 10]);
	}, true);

	equals(function() {
		return new Point(0, 0).equals({});
	}, false);

	equals(function() {
		return new Point(0, 0).equals(null);
	}, false);
});
<|endoftext|>


<commit_before>var Varint = require('../lib/varint');
var Transaction = require('../lib/transaction');
var Txin = require('../lib/txin');
var Txout = require('../lib/txout');
var should = require('chai').should();
var BufferReader = require('../lib/bufferreader');
var BufferWriter = require('../lib/bufferwriter');
var vectors = require('./vectors/bitcoind/sighash');
var Script = require('../lib/script');
var Signature = require('../lib/signature');

describe('Transaction', function() {

  var txin = Txin().fromBuffer(new Buffer('00000000000000000000000000000000000000000000000000000000000000000000000001ae00000000', 'hex'));
  var txout = Txout().fromBuffer(new Buffer('050000000000000001ae', 'hex'));
  var tx = Transaction().set({
    version: 0,
    txinsvi: Varint(1),
    txins: [txin],
    txoutsvi: Varint(1),
    txouts: [txout],
    nlocktime: 0
  });
  var txhex = '000000000100000000000000000000000000000000000000000000000000000000000000000000000001ae0000000001050000000000000001ae00000000';
  var txbuf = new Buffer(txhex, 'hex');

  var tx2idhex = '8c9aa966d35bfeaf031409e0001b90ccdafd8d859799eb945a3c515b8260bcf2';
  var tx2hex = '01000000029e8d016a7b0dc49a325922d05da1f916d1e4d4f0cb840c9727f3d22ce8d1363f000000008c493046022100e9318720bee5425378b4763b0427158b1051eec8b08442ce3fbfbf7b30202a44022100d4172239ebd701dae2fbaaccd9f038e7ca166707333427e3fb2a2865b19a7f27014104510c67f46d2cbb29476d1f0b794be4cb549ea59ab9cc1e731969a7bf5be95f7ad5e7f904e5ccf50a9dc1714df00fbeb794aa27aaff33260c1032d931a75c56f2ffffffffa3195e7a1ab665473ff717814f6881485dc8759bebe97e31c301ffe7933a656f020000008b48304502201c282f35f3e02a1f32d2089265ad4b561f07ea3c288169dedcf2f785e6065efa022100e8db18aadacb382eed13ee04708f00ba0a9c40e3b21cf91da8859d0f7d99e0c50141042b409e1ebbb43875be5edde9c452c82c01e3903d38fa4fd89f3887a52cb8aea9dc8aec7e2c9d5b3609c03eb16259a2537135a1bf0f9c5fbbcbdbaf83ba402442ffffffff02206b1000000000001976a91420bb5c3bfaef0231dc05190e7f1c8e22e098991e88acf0ca0100000000001976a9149e3e2d23973a04ec1b02be97c30ab9f2f27c3b2c88ac00000000';
  var tx2buf = new Buffer(tx2hex, 'hex');

  describe('test vectors', function() {
    vectors.forEach(function(vector, i) {
      if (i === 0)
        return;
      it('should pass sighash test vector ' + i, function() {
        var txbuf = new Buffer(vector[0], 'hex');
        var scriptbuf = new Buffer(vector[1], 'hex');
        var subscript = Script(scriptbuf);
        var nin = vector[2];
        var nhashtype = vector[3];
        var sighashbuf = new Buffer(vector[4], 'hex');
        var tx = Transaction().fromBuffer(txbuf);

        //make sure transacion to/from buffer is isomorphic
        tx.toBuffer().toString('hex').should.equal(txbuf.toString('hex'));

        //sighash ought to be correct
        tx.sighash(nhashtype, nin, subscript).toString('hex').should.equal(sighashbuf.toString('hex'))
      });
    });
  });

  it('should make a new transaction', function() {
    var tx = new Transaction();
    should.exist(tx);
    tx = Transaction();
    should.exist(tx);

    Transaction(txbuf).toBuffer().toString('hex').should.equal(txhex);

    //should set known defaults
    tx.version.should.equal(1);
    tx.txinsvi.toNumber().should.equal(0);
    tx.txins.length.should.equal(0);
    tx.txoutsvi.toNumber().should.equal(0);
    tx.txouts.length.should.equal(0);
    tx.nlocktime.should.equal(0xffffffff);
  });

  describe('#initialize', function() {

    it('should set these known defaults', function() {
      var tx = new Transaction();
      tx.initialize();
      tx.version.should.equal(1);
      tx.txinsvi.toNumber().should.equal(0);
      tx.txins.length.should.equal(0);
      tx.txoutsvi.toNumber().should.equal(0);
      tx.txouts.length.should.equal(0);
      tx.nlocktime.should.equal(0xffffffff);
    });

  });

  describe('#set', function() {

    it('should set all the basic parameters', function() {
      var tx = Transaction().set({
        version: 0,
        txinsvi: Varint(1),
        txins: [txin],
        txoutsvi: Varint(1),
        txouts: [txout],
        nlocktime: 0
      });
      should.exist(tx.version);
      should.exist(tx.txinsvi);
      should.exist(tx.txins);
      should.exist(tx.txoutsvi);
      should.exist(tx.txouts);
      should.exist(tx.nlocktime);
    });

  });

  describe('#fromJSON', function() {

    it('should set all the basic parameters', function() {
      var tx = Transaction().fromJSON({
        version: 0,
        txinsvi: Varint(1).toJSON(),
        txins: [txin.toJSON()],
        txoutsvi: Varint(1).toJSON(),
        txouts: [txout.toJSON()],
        nlocktime: 0
      });
      should.exist(tx.version);
      should.exist(tx.txinsvi);
      should.exist(tx.txins);
      should.exist(tx.txoutsvi);
      should.exist(tx.txouts);
      should.exist(tx.nlocktime);
    });

  });

  describe('#toJSON', function() {

    it('should recover all the basic parameters', function() {
      var json = tx.toJSON();
      should.exist(json.version);
      should.exist(json.txinsvi);
      should.exist(json.txins);
      should.exist(json.txoutsvi);
      should.exist(json.txouts);
      should.exist(json.nlocktime);
    });

  });

  describe('#fromBuffer', function() {

    it('should recover from this known tx', function() {
      Transaction().fromBuffer(txbuf).toBuffer().toString('hex').should.equal(txhex);
    });

    it('should recover from this known tx from the blockchain', function() {
      Transaction().fromBuffer(tx2buf).toBuffer().toString('hex').should.equal(tx2hex);
    });

  });

  describe('#fromBufferReader', function() {

    it('should recover from this known tx', function() {
      Transaction().fromBufferReader(BufferReader(txbuf)).toBuffer().toString('hex').should.equal(txhex);
    });

  });

  describe('#toBuffer', function() {

    it('should produce this known tx', function() {
      Transaction().fromBuffer(txbuf).toBuffer().toString('hex').should.equal(txhex);
    });

  });

  describe('#toBufferWriter', function() {

    it('should produce this known tx', function() {
      Transaction().fromBuffer(txbuf).toBufferWriter().concat().toString('hex').should.equal(txhex);
    });

  });

  describe('#sighash', function() {

    it('should has this transaction', function() {
      tx.sighash(0, 0, Script('')).length.should.equal(32);
    });

  });

  describe('#hash', function() {

    it('should correctly calculate the hash of this known transaction', function() {
      var tx = Transaction().fromBuffer(tx2buf);
      var txhashbuf = new Buffer(Array.apply([], new Buffer(tx2idhex, 'hex')).reverse());
      tx.hash().toString('hex').should.equal(txhashbuf.toString('hex'));
    });

  });

  describe('#id', function() {

    it('should correctly calculate the id of this known transaction', function() {
      var tx = Transaction().fromBuffer(tx2buf);
      tx.id().toString('hex').should.equal(tx2idhex);
    });

  });

  describe('#addTxin', function() {

    it('should add an input', function() {
      var txin = Txin();
      var tx = Transaction();
      tx.txinsvi.toNumber().should.equal(0);
      tx.addTxin(txin);
      tx.txinsvi.toNumber().should.equal(1);
      tx.txins.length.should.equal(1);
    });

  });

  describe('#addTxout', function() {

    it('should add an output', function() {
      var txout = Txout();
      var tx = Transaction();
      tx.txoutsvi.toNumber().should.equal(0);
      tx.addTxout(txout);
      tx.txoutsvi.toNumber().should.equal(1);
      tx.txouts.length.should.equal(1);
    });

  });

});
<commit_msg>test for SIGHASH_SINGLE bug<commit_after>var Varint = require('../lib/varint');
var Transaction = require('../lib/transaction');
var Txin = require('../lib/txin');
var Txout = require('../lib/txout');
var should = require('chai').should();
var BufferReader = require('../lib/bufferreader');
var BufferWriter = require('../lib/bufferwriter');
var vectors = require('./vectors/bitcoind/sighash');
var Script = require('../lib/script');
var Signature = require('../lib/signature');

describe('Transaction', function() {

  var txin = Txin().fromBuffer(new Buffer('00000000000000000000000000000000000000000000000000000000000000000000000001ae00000000', 'hex'));
  var txout = Txout().fromBuffer(new Buffer('050000000000000001ae', 'hex'));
  var tx = Transaction().set({
    version: 0,
    txinsvi: Varint(1),
    txins: [txin],
    txoutsvi: Varint(1),
    txouts: [txout],
    nlocktime: 0
  });
  var txhex = '000000000100000000000000000000000000000000000000000000000000000000000000000000000001ae0000000001050000000000000001ae00000000';
  var txbuf = new Buffer(txhex, 'hex');

  var tx2idhex = '8c9aa966d35bfeaf031409e0001b90ccdafd8d859799eb945a3c515b8260bcf2';
  var tx2hex = '01000000029e8d016a7b0dc49a325922d05da1f916d1e4d4f0cb840c9727f3d22ce8d1363f000000008c493046022100e9318720bee5425378b4763b0427158b1051eec8b08442ce3fbfbf7b30202a44022100d4172239ebd701dae2fbaaccd9f038e7ca166707333427e3fb2a2865b19a7f27014104510c67f46d2cbb29476d1f0b794be4cb549ea59ab9cc1e731969a7bf5be95f7ad5e7f904e5ccf50a9dc1714df00fbeb794aa27aaff33260c1032d931a75c56f2ffffffffa3195e7a1ab665473ff717814f6881485dc8759bebe97e31c301ffe7933a656f020000008b48304502201c282f35f3e02a1f32d2089265ad4b561f07ea3c288169dedcf2f785e6065efa022100e8db18aadacb382eed13ee04708f00ba0a9c40e3b21cf91da8859d0f7d99e0c50141042b409e1ebbb43875be5edde9c452c82c01e3903d38fa4fd89f3887a52cb8aea9dc8aec7e2c9d5b3609c03eb16259a2537135a1bf0f9c5fbbcbdbaf83ba402442ffffffff02206b1000000000001976a91420bb5c3bfaef0231dc05190e7f1c8e22e098991e88acf0ca0100000000001976a9149e3e2d23973a04ec1b02be97c30ab9f2f27c3b2c88ac00000000';
  var tx2buf = new Buffer(tx2hex, 'hex');

  describe('test vectors', function() {
    vectors.forEach(function(vector, i) {
      if (i === 0)
        return;
      it('should pass sighash test vector ' + i, function() {
        var txbuf = new Buffer(vector[0], 'hex');
        var scriptbuf = new Buffer(vector[1], 'hex');
        var subscript = Script(scriptbuf);
        var nin = vector[2];
        var nhashtype = vector[3];
        var sighashbuf = new Buffer(vector[4], 'hex');
        var tx = Transaction().fromBuffer(txbuf);

        //make sure transacion to/from buffer is isomorphic
        tx.toBuffer().toString('hex').should.equal(txbuf.toString('hex'));

        //sighash ought to be correct
        tx.sighash(nhashtype, nin, subscript).toString('hex').should.equal(sighashbuf.toString('hex'))
      });
    });
  });

  it('should make a new transaction', function() {
    var tx = new Transaction();
    should.exist(tx);
    tx = Transaction();
    should.exist(tx);

    Transaction(txbuf).toBuffer().toString('hex').should.equal(txhex);

    //should set known defaults
    tx.version.should.equal(1);
    tx.txinsvi.toNumber().should.equal(0);
    tx.txins.length.should.equal(0);
    tx.txoutsvi.toNumber().should.equal(0);
    tx.txouts.length.should.equal(0);
    tx.nlocktime.should.equal(0xffffffff);
  });

  describe('#initialize', function() {

    it('should set these known defaults', function() {
      var tx = new Transaction();
      tx.initialize();
      tx.version.should.equal(1);
      tx.txinsvi.toNumber().should.equal(0);
      tx.txins.length.should.equal(0);
      tx.txoutsvi.toNumber().should.equal(0);
      tx.txouts.length.should.equal(0);
      tx.nlocktime.should.equal(0xffffffff);
    });

  });

  describe('#set', function() {

    it('should set all the basic parameters', function() {
      var tx = Transaction().set({
        version: 0,
        txinsvi: Varint(1),
        txins: [txin],
        txoutsvi: Varint(1),
        txouts: [txout],
        nlocktime: 0
      });
      should.exist(tx.version);
      should.exist(tx.txinsvi);
      should.exist(tx.txins);
      should.exist(tx.txoutsvi);
      should.exist(tx.txouts);
      should.exist(tx.nlocktime);
    });

  });

  describe('#fromJSON', function() {

    it('should set all the basic parameters', function() {
      var tx = Transaction().fromJSON({
        version: 0,
        txinsvi: Varint(1).toJSON(),
        txins: [txin.toJSON()],
        txoutsvi: Varint(1).toJSON(),
        txouts: [txout.toJSON()],
        nlocktime: 0
      });
      should.exist(tx.version);
      should.exist(tx.txinsvi);
      should.exist(tx.txins);
      should.exist(tx.txoutsvi);
      should.exist(tx.txouts);
      should.exist(tx.nlocktime);
    });

  });

  describe('#toJSON', function() {

    it('should recover all the basic parameters', function() {
      var json = tx.toJSON();
      should.exist(json.version);
      should.exist(json.txinsvi);
      should.exist(json.txins);
      should.exist(json.txoutsvi);
      should.exist(json.txouts);
      should.exist(json.nlocktime);
    });

  });

  describe('#fromBuffer', function() {

    it('should recover from this known tx', function() {
      Transaction().fromBuffer(txbuf).toBuffer().toString('hex').should.equal(txhex);
    });

    it('should recover from this known tx from the blockchain', function() {
      Transaction().fromBuffer(tx2buf).toBuffer().toString('hex').should.equal(tx2hex);
    });

  });

  describe('#fromBufferReader', function() {

    it('should recover from this known tx', function() {
      Transaction().fromBufferReader(BufferReader(txbuf)).toBuffer().toString('hex').should.equal(txhex);
    });

  });

  describe('#toBuffer', function() {

    it('should produce this known tx', function() {
      Transaction().fromBuffer(txbuf).toBuffer().toString('hex').should.equal(txhex);
    });

  });

  describe('#toBufferWriter', function() {

    it('should produce this known tx', function() {
      Transaction().fromBuffer(txbuf).toBufferWriter().concat().toString('hex').should.equal(txhex);
    });

  });

  describe('#sighash', function() {

    it('should hash this transaction', function() {
      tx.sighash(0, 0, Script('')).length.should.equal(32);
    });

    it('should return 1 for the SIGHASH_SINGLE bug', function() {
      var tx = Transaction(tx2buf);
      tx.txouts.length = 1;
      tx.txoutsvi = Varint(1);
      tx.sighash(Signature.SIGHASH_SINGLE, 1, Script('')).toString('hex').should.equal('0000000000000000000000000000000000000000000000000000000000000001');
    });

  });

  describe('#hash', function() {

    it('should correctly calculate the hash of this known transaction', function() {
      var tx = Transaction().fromBuffer(tx2buf);
      var txhashbuf = new Buffer(Array.apply([], new Buffer(tx2idhex, 'hex')).reverse());
      tx.hash().toString('hex').should.equal(txhashbuf.toString('hex'));
    });

  });

  describe('#id', function() {

    it('should correctly calculate the id of this known transaction', function() {
      var tx = Transaction().fromBuffer(tx2buf);
      tx.id().toString('hex').should.equal(tx2idhex);
    });

  });

  describe('#addTxin', function() {

    it('should add an input', function() {
      var txin = Txin();
      var tx = Transaction();
      tx.txinsvi.toNumber().should.equal(0);
      tx.addTxin(txin);
      tx.txinsvi.toNumber().should.equal(1);
      tx.txins.length.should.equal(1);
    });

  });

  describe('#addTxout', function() {

    it('should add an output', function() {
      var txout = Txout();
      var tx = Transaction();
      tx.txoutsvi.toNumber().should.equal(0);
      tx.addTxout(txout);
      tx.txoutsvi.toNumber().should.equal(1);
      tx.txouts.length.should.equal(1);
    });

  });

});
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var clierr = require('../..'),
  define = clierr.define,
  definition = clierr.definition,
  config = clierr.config;

describe('cli-error:', function() {
  beforeEach(function(done) {
    clierr.clear();
    done();
  });
  afterEach(function(done) {
    clierr.clear();
    done();
  });
  it('should define errors', function(done) {
    var errors = clierr.errors;
    var key = 'EARGLENGTH';
    var message = 'too few arguments';
    var def = define(key, message);
    expect(def).to.be.an.instanceof(definition);
    var keys = Object.keys(errors);
    expect(keys.length).to.be.a('number').that.equals(1);
    expect(def.key).to.be.a('string').that.equals(key);
    expect(def.message).to.be.a('string').that.equals(message);
    expect(errors[key]).to.be.an.instanceof(definition).that.equals(def);
    expect(def.code).to.be.a('number').that.equals(config.start);
    done();
  });
})
<commit_msg>Assert on define variants.<commit_after>var expect = require('chai').expect;
var clierr = require('../..'),
  define = clierr.define,
  definition = clierr.definition,
  config = clierr.config;

describe('cli-error:', function() {
  beforeEach(function(done) {
    clierr.clear();
    done();
  });
  afterEach(function(done) {
    clierr.clear();
    done();
  });
  it('should define errors', function(done) {
    var errors = clierr.errors;
    var key = 'EARGLENGTH';
    var message = 'too few arguments';
    var def = define(key, message);
    expect(def).to.be.an.instanceof(definition);
    var keys = Object.keys(errors);
    expect(keys.length).to.be.a('number').that.equals(1);
    expect(def.key).to.be.a('string').that.equals(key);
    expect(def.message).to.be.a('string').that.equals(message);
    expect(errors[key]).to.be.an.instanceof(definition).that.equals(def);
    expect(def.code).to.be.a('number').that.equals(config.start);
    done();
  });
  it('should define error with specific code (no parameters)', function(done) {
    var errors = clierr.errors;
    var key = 'EARGLENGTH';
    var message = 'too few arguments';
    var def = define(key, message, 256);
    expect(def.code).to.be.a('number').that.equals(256);
    done();
  });
  it('should define error with parameters and code', function(done) {
    var errors = clierr.errors;
    var key = 'EARGLENGTH';
    var message = 'too few arguments, got %s';
    var params = ['-xvf'];
    var def = define(key, message, params, 256);
    expect(def.parameters).to.eql(params);
    expect(def.code).to.be.a('number').that.equals(256);
    done();
  });
})
<|endoftext|>


<commit_before>describe("Filter", function () {
    var catalog = null;
    var $rootScope = null;
    var $compile = null;

    beforeEach(module("gettext"));

    beforeEach(inject(function ($injector, gettextCatalog) {
        $rootScope = $injector.get("$rootScope");
        $compile = $injector.get("$compile");
        catalog = gettextCatalog;
        catalog.setStrings("nl", {
            Hello: "Hallo",
            "Hello {{name}}!": "Hallo {{name}}!",
            "One boat": ["Een boot", "{{count}} boten"]
        });
        catalog.setStrings("pt-BR", {
            Hello: [{ Bull: "Olé", Person: "Olá" }]
        });
    }));

    it("Should have a translate filter", function () {
        var el = $compile("
{{\"Hello!\"|translate}}
")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hello!");
    });

    it("Should translate known strings", function () {
        catalog.currentLanguage = "nl";
        var el = $compile("{{\"Hello\"|translate}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hallo");
    });

    it("Should translate known strings according to translate context", function () {
        catalog.currentLanguage = "pt-BR";
        var el = $compile("{{\"Hello\"|translate:{translateContext:'Bull'}}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Olé");
        el = $compile("{{\"Hello\"|translate:{translateContext:'Person'}}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Olá");
        el = $compile("{{\"Hello\"|translate}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hello");
    });

    it("Can use filter in attribute values", function () {
        catalog.currentLanguage = "nl";
        var el = $compile("<input type=\"text\" placeholder=\"{{'Hello'|translate}}\" />")($rootScope);
        $rootScope.$digest();
        assert.equal(el.attr("placeholder"), "Hallo");
    });
});
<commit_msg>space to separate angular expression delimiters from filter argument object<commit_after>describe("Filter", function () {
    var catalog = null;
    var $rootScope = null;
    var $compile = null;

    beforeEach(module("gettext"));

    beforeEach(inject(function ($injector, gettextCatalog) {
        $rootScope = $injector.get("$rootScope");
        $compile = $injector.get("$compile");
        catalog = gettextCatalog;
        catalog.setStrings("nl", {
            Hello: "Hallo",
            "Hello {{name}}!": "Hallo {{name}}!",
            "One boat": ["Een boot", "{{count}} boten"]
        });
        catalog.setStrings("pt-BR", {
            Hello: [{ Bull: "Olé", Person: "Olá" }]
        });
    }));

    it("Should have a translate filter", function () {
        var el = $compile("
{{\"Hello!\"|translate}}
")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hello!");
    });

    it("Should translate known strings", function () {
        catalog.currentLanguage = "nl";
        var el = $compile("{{\"Hello\"|translate}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hallo");
    });

    it("Should translate known strings according to translate context", function () {
        catalog.currentLanguage = "pt-BR";
        var el = $compile("{{\"Hello\"|translate:{translateContext:'Bull'} }}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Olé");
        el = $compile("{{\"Hello\"|translate:{translateContext:'Person'} }}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Olá");
        el = $compile("{{\"Hello\"|translate}}")($rootScope);
        $rootScope.$digest();
        assert.equal(el.text(), "Hello");
    });

    it("Can use filter in attribute values", function () {
        catalog.currentLanguage = "nl";
        var el = $compile("<input type=\"text\" placeholder=\"{{'Hello'|translate}}\" />")($rootScope);
        $rootScope.$digest();
        assert.equal(el.attr("placeholder"), "Hallo");
    });
});
<|endoftext|>