<commit_before>// @flow

import { ColorSchemeRegistry, schemeColor } from '../../../base/color-scheme';
import { BoxModel } from '../../../base/styles';
import BaseTheme from '../../../base/ui/components/BaseTheme';

const BUTTON_SIZE = 48;

// Toolbox, toolbar:

/**
 * The style of toolbar buttons.
 */
const toolbarButton = {
    borderRadius: 3,
    borderWidth: 0,
    flex: 0,
    flexDirection: 'row',
    height: BUTTON_SIZE,
    justifyContent: 'center',
    marginHorizontal: 6,
    marginTop: 6,
    width: BUTTON_SIZE
};

/**
 * The icon style of the toolbar buttons.
 */
const toolbarButtonIcon = {
    alignSelf: 'center',
    color: BaseTheme.palette.icon04,
    fontSize: 24
};

/**
 * The icon style of toolbar buttons which display white icons.
 */
const whiteToolbarButtonIcon = {
    ...toolbarButtonIcon,
    color: BaseTheme.palette.icon01
};

/**
 * The style of reaction buttons.
 */
const reactionButton = {
    ...toolbarButton,
    backgroundColor: 'transparent',
    alignItems: 'center',
    marginTop: 0,
    marginHorizontal: 0
};

/**
 * The style of the emoji on the reaction buttons.
 */
const reactionEmoji = {
    fontSize: 20,
    color: BaseTheme.palette.icon01
};

const reactionMenu = {
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: BaseTheme.palette.bottomSheet,
    padding: 16
};

/**
 * The Toolbox and toolbar related styles.
 */
const styles = {

    sheetGestureRecognizer: {
        alignItems: 'stretch',
        flexDirection: 'column'
    },

    /**
     * The style of the toolbar.
     */
    toolbox: {
        alignItems: 'center',
        backgroundColor: BaseTheme.palette.uiBackground,
        borderTopLeftRadius: 3,
        borderTopRightRadius: 3,
        flexDirection: 'row',
        flexGrow: 0,
        justifyContent: 'space-between',
        paddingHorizontal: BoxModel.margin,
        paddingVertical: 8
    },

    /**
     * The style of the root/top-level container of {@link Toolbox}.
     */
    toolboxContainer: {
        flexDirection: 'column',
        flexGrow: 0,
        width: '100%',
        maxWidth: 580,
        marginLeft: 'auto',
        marginRight: 'auto'
    }
};

export default styles;

/**
 * Color schemed styles for the @{Toolbox} component.
 */
ColorSchemeRegistry.register('Toolbox', {
    /**
     * Styles for buttons in the toolbar.
     */
    buttonStyles: {
        iconStyle: toolbarButtonIcon,
        style: toolbarButton
    },

    buttonStylesBorderless: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton,
            backgroundColor: 'transparent'
        }
    },

    backgroundToggle: {
        backgroundColor: BaseTheme.palette.ui13
    },

    hangupButtonStyles: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton,
            backgroundColor: schemeColor('hangup')
        },
        underlayColor: BaseTheme.palette.underlay01
    },

    reactionDialog: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        backgroundColor: 'transparent'
    },

    overflowReactionMenu: reactionMenu,

    reactionMenu: {
        ...reactionMenu,
        borderRadius: 3,
        width: 360
    },

    reactionRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        marginBottom: 16
    },

    reactionButton: {
        style: reactionButton,
        underlayColor: BaseTheme.palette.ui13,
        emoji: reactionEmoji
    },

    raiseHandButton: {
        style: {
            ...reactionButton,
            backgroundColor: BaseTheme.palette.ui13,
            width: '100%',
            borderRadius: 6
        },
        underlayColor: BaseTheme.palette.ui13,
        emoji: reactionEmoji,
        text: {
            color: BaseTheme.palette.text01,
            fontWeight: '600',
            marginLeft: 8,
            lineHeight: 24
        },
        container: {
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center'
        }
    },

    emojiAnimation: {
        color: BaseTheme.palette.icon01,
        position: 'absolute',
        zIndex: 1001,
        elevation: 2,
        fontSize: 20,
        left: '50%',
        top: '100%'
    },

    /**
     * Styles for toggled buttons in the toolbar.
     */
    toggledButtonStyles: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton
        }
    }
});
<commit_msg>fix(toolbox) fixed toolbox safeareaview on mobile<commit_after>// @flow

import { ColorSchemeRegistry, schemeColor } from '../../../base/color-scheme';
import BaseTheme from '../../../base/ui/components/BaseTheme.native';

const BUTTON_SIZE = 48;

// Toolbox, toolbar:

/**
 * The style of toolbar buttons.
 */
const toolbarButton = {
    borderRadius: 3,
    borderWidth: 0,
    flex: 0,
    flexDirection: 'row',
    height: BUTTON_SIZE,
    justifyContent: 'center',
    marginHorizontal: 6,
    marginTop: 6,
    width: BUTTON_SIZE
};

/**
 * The icon style of the toolbar buttons.
 */
const toolbarButtonIcon = {
    alignSelf: 'center',
    color: BaseTheme.palette.icon04,
    fontSize: 24
};

/**
 * The icon style of toolbar buttons which display white icons.
 */
const whiteToolbarButtonIcon = {
    ...toolbarButtonIcon,
    color: BaseTheme.palette.icon01
};

/**
 * The style of reaction buttons.
 */
const reactionButton = {
    ...toolbarButton,
    backgroundColor: 'transparent',
    alignItems: 'center',
    marginTop: 0,
    marginHorizontal: 0
};

/**
 * The style of the emoji on the reaction buttons.
 */
const reactionEmoji = {
    fontSize: 20,
    color: BaseTheme.palette.icon01
};

const reactionMenu = {
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: BaseTheme.palette.bottomSheet,
    padding: BaseTheme.spacing[3]
};

/**
 * The Toolbox and toolbar related styles.
 */
const styles = {

    sheetGestureRecognizer: {
        alignItems: 'stretch',
        flexDirection: 'column'
    },

    /**
     * The style of the toolbar.
     */
    toolbox: {
        alignItems: 'center',
        backgroundColor: BaseTheme.palette.uiBackground,
        borderTopLeftRadius: 3,
        borderTopRightRadius: 3,
        flexDirection: 'row',
        flexGrow: 0,
        justifyContent: 'space-between',
        margin: BaseTheme.spacing[2]
    },

    /**
     * The style of the root/top-level container of {@link Toolbox}.
     */
    toolboxContainer: {
        backgroundColor: BaseTheme.palette.uiBackground,
        flexDirection: 'column',
        flexGrow: 0,
        height: '100%',
        width: '100%',
        maxHeight: 80,
        maxWidth: 580,
        marginLeft: 'auto',
        marginRight: 'auto'
    }
};

export default styles;

/**
 * Color schemed styles for the @{Toolbox} component.
 */
ColorSchemeRegistry.register('Toolbox', {
    /**
     * Styles for buttons in the toolbar.
     */
    buttonStyles: {
        iconStyle: toolbarButtonIcon,
        style: toolbarButton
    },

    buttonStylesBorderless: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton,
            backgroundColor: 'transparent'
        }
    },

    backgroundToggle: {
        backgroundColor: BaseTheme.palette.ui13
    },

    hangupButtonStyles: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton,
            backgroundColor: schemeColor('hangup')
        },
        underlayColor: BaseTheme.palette.underlay01
    },

    reactionDialog: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        backgroundColor: 'transparent'
    },

    overflowReactionMenu: reactionMenu,

    reactionMenu: {
        ...reactionMenu,
        borderRadius: 3,
        width: 360
    },

    reactionRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        marginBottom: 16
    },

    reactionButton: {
        style: reactionButton,
        underlayColor: BaseTheme.palette.ui13,
        emoji: reactionEmoji
    },

    raiseHandButton: {
        style: {
            ...reactionButton,
            backgroundColor: BaseTheme.palette.ui13,
            width: '100%',
            borderRadius: 6
        },
        underlayColor: BaseTheme.palette.ui13,
        emoji: reactionEmoji,
        text: {
            color: BaseTheme.palette.text01,
            fontWeight: '600',
            marginLeft: 8,
            lineHeight: 24
        },
        container: {
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center'
        }
    },

    emojiAnimation: {
        color: BaseTheme.palette.icon01,
        position: 'absolute',
        zIndex: 1001,
        elevation: 2,
        fontSize: 20,
        left: '50%',
        top: '100%'
    },

    /**
     * Styles for toggled buttons in the toolbar.
     */
    toggledButtonStyles: {
        iconStyle: whiteToolbarButtonIcon,
        style: {
            ...toolbarButton
        }
    }
});
<|endoftext|>


<commit_before>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

;
(function($) {

    // Use this variable to set up the common and page specific functions. If you
    // rename this variable, you will also need to rename the namespace below.
    var Sage = {
        // All pages
        'common': {
            init: function() {
                $(' .page-title.inverted').flowtype({
                    maximum: 800,
                    minFont: 27,
                    fontRatio: 7
                });
            },
            finalize: function() {
                // JavaScript to be fired on all pages, after page specific JS is fired
            }
        },
        // Home page
        'home': {
            init: function() {
                $('.brand-form-submit').click(function(event) {
                    $('#gform_submit_button_3').click();
                });

            },
            finalize: function() {
                // JavaScript to be fired on the home page, after the init JS
            }
        },
        'single_product': {
            init: function() {
                if ($('.cibo .temperatura').length) {
                    var adjustTemperaturaHeight = function() {
                        var adjusted = false;
                        if ($(window).width() >= 800) {
                            $('.temperatura .attributo-espanso-content').height(function() {
                                $(this).height('auto');
                                return $(this).parent().height() - $('.temperatura .attributo-espanso-title').height();
                            });
                            adjusted = false;
                        } else {
                            if (!adjusted) $('.temperatura .attributo-espanso-content').height('auto');
                            adjusted = true;
                        }

                    };
                    adjustTemperaturaHeight();
                    $(window).resize(adjustTemperaturaHeight);
                }

                $('.tabella-attributi .reset_variations').click(function(event) {
                    event.preventDefault();
                    $('.tabella-attributi select').val('').change();
                    $('.variations_form.cart').trigger('reset_data');
                });
                $('.tabella-attributi select').change(function(e) {
                    var val = $(this).val();
                    var id = e.target.id;
                    $('.buy-container #' + id).val(val).change();
                });
                $("form.cart").on("change", "input.qty", function() {
                    if (this.value === "0")
                        this.value = "1";

                    $(this.form).find(".single_add_to_cart_button[data-quantity]").data("quantity", this.value);
                });
                $(document.body).on("added_to_cart", function() {
                    var val = Number($('.wcmenucart-text>.cart-length').text());

                    $("a.added_to_cart").remove();
                });
            }
        },
        'um_page_account': {
            init: function() {
                (function(original) {
                    jQuery.fn.clone = function() {
                        var result = original.apply(this, arguments),
                            my_textareas = this.find('textarea').add(this.filter('textarea')),
                            result_textareas = result.find('textarea').add(result.filter('textarea')),
                            my_selects = this.find('select').add(this.filter('select')),
                            result_selects = result.find('select').add(result.filter('select'));

                        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
                        for (var i = 0, l = my_selects.length; i < l; ++i) {
                            for (var j = 0, m = my_selects[i].options.length; j < m; ++j) {
                                if (my_selects[i].options[j].selected === true) {
                                    result_selects[i].options[j].selected = true;
                                }
                            }
                        }
                        return result;
                    };
                })(jQuery.fn.clone);
                $('.um-account-main #gform_submit_button_6').on('click', function(event) {
                    event.preventDefault();
                    $('#gform_6 .gform_fields').replaceWith($('.um-account-main .gform_fields').clone())
                    $('#gform_6').submit();
                });
                $('#gform_6').on('submit', function(event) {
                    $('.gforms_confirmation_message').remove();
                })

                if ($('.gform_wrapper').length) {
                    $('.gfield.hidden').hide();

                    var max_rows = $('.gfield_list_group').first().find('option').length;

                    gform.addFilter('gform_list_item_pre_add', function(clone) {

                        clone.find('.datepicker').removeClass('hasDatepicker').removeAttr('id');
                        set_max_rows(clone.find('.gfield_list_icons img'));
                        return clone;
                    });

                    function set_max_rows(buttons) {

                        if (buttons) {
                            buttons.first().attr('onclick', "gformAddListItem(this, " + max_rows + ")");
                            buttons.first().attr('onkeypress', "gformAddListItem(this, " + max_rows + ")");
                            buttons.last().attr('onclick', "gformDeleteListItem(this, " + max_rows + ")");
                            buttons.last().attr('onkeypress', "gformDeleteListItem(this, " + max_rows + ")");
                        }
                    }

                    $('.gfield_list_icons').each(function(index, el) {

                        var buttons = $(el).children('img');
                        set_max_rows(buttons);
                    });

                    function disable_option() {
                        var rows = $('.um-account-tab .gfield_list_group');
                        var options = rows.find('option');
                        var selected = [];
                        var disabled = [];

                        rows.each(function(index, el) {
                            var val = $(this).find('select').val();
                            if (val) selected.push(val);
                        });

                        options.each(function(index) {
                            if ($(this).attr('disabled') === 'disabled') disabled.push($(this).val());
                        });

                        options.each(function(index, el) {
                            if (selected.indexOf($(el).val()) !== -1 && $(el).parent().val() !== $(el).val()) {
                                $(el).attr('disabled', 'disabled');
                            } else if (disabled.indexOf($(el).val()) !== -1) {
                                $(el).attr('disabled', null);
                            }
                        });
                    }

                    disable_option();

                    $('.ginput_list').on('click', '.gfield_list_icons img', function(event) { disable_option(); });
                    $('.ginput_list').on('focus', '.datepicker', function(e) { gformInitDatepicker(); })
                    $('.ginput_list').on('change focus mousedown keydown touchstart', '.gfield_list_group select', function(event) { disable_option(); });
                }
            }
        },
        // About us page, note the change from about-us to about_us.
        'about_us': {
            init: function() {
                // JavaScript to be fired on the about us page
            }
        }
    };

    // The routing fires all common scripts, followed by the page specific scripts.
    // Add additional events for more control over timing e.g. a finalize event
    var UTIL = {
        fire: function(func, funcname, args) {
            var fire;
            var namespace = Sage;
            funcname = (funcname === undefined) ? 'init' : funcname;
            fire = func !== '';
            fire = fire && namespace[func];
            fire = fire && typeof namespace[func][funcname] === 'function';

            if (fire) {
                namespace[func][funcname](args);
            }
        },
        loadEvents: function() {
            // Fire common init JS
            UTIL.fire('common');

            // Fire page-specific init JS, and then finalize JS
            $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
                UTIL.fire(classnm);
                UTIL.fire(classnm, 'finalize');
            });

            // Fire common finalize JS
            UTIL.fire('common', 'finalize');
        }
    };

    // Load Events
    $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<commit_msg>Js lazyload<commit_after>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

;
(function($) {

    // Use this variable to set up the common and page specific functions. If you
    // rename this variable, you will also need to rename the namespace below.
    var Sage = {
        // All pages
        'common': {
            init: function() {
                $(' .page-title.inverted').flowtype({
                    maximum: 800,
                    minFont: 27,
                    fontRatio: 7
                });
                $('img[data-lazy-src]').each(function(i, img) {
                    lazy_load_image(img);
                });
            },
            finalize: function() {
                // JavaScript to be fired on all pages, after page specific JS is fired
            }
        },
        // Home page
        'home': {
            init: function() {
                $('.brand-form-submit').click(function(event) {
                    $('#gform_submit_button_3').click();
                });

            },
            finalize: function() {
                // JavaScript to be fired on the home page, after the init JS
            }
        },
        'single_product': {
            init: function() {
                if ($('.cibo .temperatura').length) {
                    var adjustTemperaturaHeight = function() {
                        var adjusted = false;
                        if ($(window).width() >= 800) {
                            $('.temperatura .attributo-espanso-content').height(function() {
                                $(this).height('auto');
                                return $(this).parent().height() - $('.temperatura .attributo-espanso-title').height();
                            });
                            adjusted = false;
                        } else {
                            if (!adjusted) $('.temperatura .attributo-espanso-content').height('auto');
                            adjusted = true;
                        }

                    };
                    adjustTemperaturaHeight();
                    $(window).resize(adjustTemperaturaHeight);
                }

                $('.tabella-attributi .reset_variations').click(function(event) {
                    event.preventDefault();
                    $('.tabella-attributi select').val('').change();
                    $('.variations_form.cart').trigger('reset_data');
                });
                $('.tabella-attributi select').change(function(e) {
                    var val = $(this).val();
                    var id = e.target.id;
                    $('.buy-container #' + id).val(val).change();
                });
                $("form.cart").on("change", "input.qty", function() {
                    if (this.value === "0")
                        this.value = "1";

                    $(this.form).find(".single_add_to_cart_button[data-quantity]").data("quantity", this.value);
                });
                $(document.body).on("added_to_cart", function() {
                    var val = Number($('.wcmenucart-text>.cart-length').text());

                    $("a.added_to_cart").remove();
                });
            }
        },
        'um_page_account': {
            init: function() {
                (function(original) {
                    jQuery.fn.clone = function() {
                        var result = original.apply(this, arguments),
                            my_textareas = this.find('textarea').add(this.filter('textarea')),
                            result_textareas = result.find('textarea').add(result.filter('textarea')),
                            my_selects = this.find('select').add(this.filter('select')),
                            result_selects = result.find('select').add(result.filter('select'));

                        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
                        for (var i = 0, l = my_selects.length; i < l; ++i) {
                            for (var j = 0, m = my_selects[i].options.length; j < m; ++j) {
                                if (my_selects[i].options[j].selected === true) {
                                    result_selects[i].options[j].selected = true;
                                }
                            }
                        }
                        return result;
                    };
                })(jQuery.fn.clone);
                $('.um-account-main #gform_submit_button_6').on('click', function(event) {
                    event.preventDefault();
                    $('#gform_6 .gform_fields').replaceWith($('.um-account-main .gform_fields').clone())
                    $('#gform_6').submit();
                });
                $('#gform_6').on('submit', function(event) {
                    $('.gforms_confirmation_message').remove();
                })

                if ($('.gform_wrapper').length) {
                    $('.gfield.hidden').hide();

                    var max_rows = $('.gfield_list_group').first().find('option').length;

                    gform.addFilter('gform_list_item_pre_add', function(clone) {

                        clone.find('.datepicker').removeClass('hasDatepicker').removeAttr('id');
                        set_max_rows(clone.find('.gfield_list_icons img'));
                        return clone;
                    });

                    function set_max_rows(buttons) {

                        if (buttons) {
                            buttons.first().attr('onclick', "gformAddListItem(this, " + max_rows + ")");
                            buttons.first().attr('onkeypress', "gformAddListItem(this, " + max_rows + ")");
                            buttons.last().attr('onclick', "gformDeleteListItem(this, " + max_rows + ")");
                            buttons.last().attr('onkeypress', "gformDeleteListItem(this, " + max_rows + ")");
                        }
                    }

                    $('.gfield_list_icons').each(function(index, el) {

                        var buttons = $(el).children('img');
                        set_max_rows(buttons);
                    });

                    function disable_option() {
                        var rows = $('.um-account-tab .gfield_list_group');
                        var options = rows.find('option');
                        var selected = [];
                        var disabled = [];

                        rows.each(function(index, el) {
                            var val = $(this).find('select').val();
                            if (val) selected.push(val);
                        });

                        options.each(function(index) {
                            if ($(this).attr('disabled') === 'disabled') disabled.push($(this).val());
                        });

                        options.each(function(index, el) {
                            if (selected.indexOf($(el).val()) !== -1 && $(el).parent().val() !== $(el).val()) {
                                $(el).attr('disabled', 'disabled');
                            } else if (disabled.indexOf($(el).val()) !== -1) {
                                $(el).attr('disabled', null);
                            }
                        });
                    }

                    disable_option();

                    $('.ginput_list').on('click', '.gfield_list_icons img', function(event) { disable_option(); });
                    $('.ginput_list').on('focus', '.datepicker', function(e) { gformInitDatepicker(); })
                    $('.ginput_list').on('change focus mousedown keydown touchstart', '.gfield_list_group select', function(event) { disable_option(); });
                }
            }
        },
        // About us page, note the change from about-us to about_us.
        'about_us': {
            init: function() {
                // JavaScript to be fired on the about us page
            }
        }
    };

    // The routing fires all common scripts, followed by the page specific scripts.
    // Add additional events for more control over timing e.g. a finalize event
    var UTIL = {
        fire: function(func, funcname, args) {
            var fire;
            var namespace = Sage;
            funcname = (funcname === undefined) ? 'init' : funcname;
            fire = func !== '';
            fire = fire && namespace[func];
            fire = fire && typeof namespace[func][funcname] === 'function';

            if (fire) {
                namespace[func][funcname](args);
            }
        },
        loadEvents: function() {
            // Fire common init JS
            UTIL.fire('common');

            // Fire page-specific init JS, and then finalize JS
            $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
                UTIL.fire(classnm);
                UTIL.fire(classnm, 'finalize');
            });

            // Fire common finalize JS
            UTIL.fire('common', 'finalize');
        }
    };

    // Load Events
    $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<|endoftext|>


<commit_before>// Run this after jslint.js or jshint.js so that JSC can run it.
//
// Adapted from:
// - http://blog.pulletsforever.com/2009/07/09/running_jslint_with_safaris_javascript_core/
// - https://github.com/jshint/jshint/blob/master/env/rhino.js

/*
Copyright (c) 2002 Douglas Crockford (www.JSLint.com) JSC Edition
Copyright (c) 2009 Apple Inc.
*/

/*jslint  eqeqeq:   true,
          immed:    false,
          newcap:   true,
          nomen:    false,
          onevar:   true,
          plusplus: false,
          rhino:    true,
          undef:    true,
          white:    false */
/*global  JSLINT, JSHINT */

(function(args){
  var filename  = args[0],
      options   = args[1],
      linter    = (typeof JSHINT !== 'undefined' ? JSHINT : JSLINT),
      linterOptions = {};

  // Check for JS code
  if(!filename){
    print('Usage: jsc (jslint|jshint).js jsc.js -- "$(cat myFile.js)" ' +
          '[opt1=val1,opt2=val2]');
    quit(1);
  }

  // Parse linter options
  if(options){
    options.split(',').forEach(function(opt){
      var kv = opt.split('='), k = kv[0], v = kv[1];

      linterOptions[k] = (
        // Ew, nested ternaries. Refactor if more complexity is needed.
        v === 'true'  ? true :  // Convert strings to
        v === 'false' ? false : // native booleans
        v
      );
    });
  }

  if(!linter(filename, linterOptions)){
    // Format errors
    (function(){
      var errorsCount = linter.errors.length, i, e;
      for(i = 0; i < errorsCount; i++){
        e = linter.errors[i];
        if(e){
          print('Lint at line ' + (e.line + 1) + ' character ' +
            (e.character + 1) + ': ' + e.reason);
          print((e.evidence || '').replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
          print('');
        }
      }
    }());
    quit(2);
  }else{
    print('No problems found.');
    quit();
  }
}(arguments));
<commit_msg>jsc.js: Cache regexp; don't run `replace` if string is blank<commit_after>// Run this after jslint.js or jshint.js so that JSC can run it.
//
// Adapted from:
// - http://blog.pulletsforever.com/2009/07/09/running_jslint_with_safaris_javascript_core/
// - https://github.com/jshint/jshint/blob/master/env/rhino.js

/*
Copyright (c) 2002 Douglas Crockford (www.JSLint.com) JSC Edition
Copyright (c) 2009 Apple Inc.
*/

/*jslint  eqeqeq:   true,
          immed:    false,
          newcap:   true,
          nomen:    false,
          onevar:   true,
          plusplus: false,
          rhino:    true,
          undef:    true,
          white:    false */
/*global  JSLINT, JSHINT */

(function(args){
  var filename  = args[0],
      options   = args[1],
      linter    = (typeof JSHINT !== 'undefined' ? JSHINT : JSLINT),
      linterOptions = {};

  // Check for JS code
  if(!filename){
    print('Usage: jsc (jslint|jshint).js jsc.js -- "$(cat myFile.js)" ' +
          '[opt1=val1,opt2=val2]');
    quit(1);
  }

  // Parse linter options
  if(options){
    options.split(',').forEach(function(opt){
      var kv = opt.split('='), k = kv[0], v = kv[1];

      linterOptions[k] = (
        // Ew, nested ternaries. Refactor if more complexity is needed.
        v === 'true'  ? true  : // Convert strings to
        v === 'false' ? false : // native booleans
        v
      );
    });
  }

  if(!linter(filename, linterOptions)){
    // Format errors
    (function(){
      var errorsCount = linter.errors.length,
          regexp = /^\s*(\S*(\s+\S+)*)\s*$/,
          i, e;

      for(i = 0; i < errorsCount; i++){
        e = linter.errors[i];
        if(e){
          print('Lint at line ' + (e.line + 1) + ' character ' +
            (e.character + 1) + ': ' + e.reason);
          print(e.evidence ? e.evidence.replace(regexp, "$1") : '');
          print('');
        }
      }
    }());
    quit(2);
  }else{
    print('No problems found.');
    quit();
  }
}(arguments));
<|endoftext|>


<commit_before>import is_integer from 'validator/lib/isInt'
import mongoose from 'mongoose'

export const user_model = mongoose.model('user', new mongoose.Schema({
  vk_id: {
    type: Number,
    required: [true, 'parameter is required'],
    min: [0, 'parameter must be positive'],
    validate: {
      message: 'parameter must be an integer',

      validator(value) {
        return is_integer(value.toString())
      },
    },
  },
}))
<commit_msg>Issue #29: extend the user model<commit_after>import is_integer from 'validator/lib/isInt'
import mongoose from 'mongoose'

export const user_model = mongoose.model('user', new mongoose.Schema({
  vk_id: {
    type: Number,
    required: [true, 'parameter is required'],
    min: [0, 'parameter must be positive'],
    validate: {
      message: 'parameter must be an integer',

      validator(value) {
        return is_integer(value.toString())
      },
    },
  },
  photo: {
    type: String,
  },
  name: {
    type: String,
  },
  screen_name: {
    type: String,
  },
}))
<|endoftext|>


<commit_before>$('.modifyBtns').click(function (evt) {
    evt.stopPropagation();
});
$("#filterButton").click(function() {
    var service = $(this).attr('service');
    swal({
        title: "Filter by Queue",
        text: "Input the queue you would like to view logs for",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        window.location = "/filtered?service="+service+"&queue="+inputValue;
        swal.close();
    });
});
$("#fixAllButton").click(function() {
    swal({
        title: "Fix All",
        text: "Set all logs as fixed for desired queue, no going back",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        $.post('/fixAll/', {
            queue: inputValue
        }, function() {
            location.reload();
        });

        swal.close();
    });
});
$('.retryButton').click(function () {
    var messageId = $(this).attr('messageId');
    var correlationId = $(this).attr('correlationId');
    var text = $(this).attr('text');
    var queue = $(this).attr('queue');
    $.post('/retry/', {
        correlationId: correlationId,
        text: text,
        queue: queue
    }, function() {
        $("#"+messageId).remove();
    });
});
$('.fixButton').click(function () {
    var messageId = $(this).attr('messageId');
    var updateId = $(this).attr('logId');
    var index = $(this).attr('index');
    console.log(index);
    $.post('/fixed/', {
        updateId: updateId,
        index: index
    }, function() {
        $("#"+messageId).remove();
    });
});
$('.changeQueueButton').click(function () {
    var messageId = $(this).attr('messageId');
    var correlationId = $(this).attr('correlationId');
    var text = $(this).attr('text');
    swal({
        title: "Change Queue",
        text: "please input the queue you'd like this document to be sent",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        $.post('/retry/', {
            correlationId: correlationId,
            text: text,
            queue: inputValue
        }, function() {
            $("#"+messageId).remove();
        });
        swal.close();
    });
});
<commit_msg>removed another console.log<commit_after>$('.modifyBtns').click(function (evt) {
    evt.stopPropagation();
});
$("#filterButton").click(function() {
    var service = $(this).attr('service');
    swal({
        title: "Filter by Queue",
        text: "Input the queue you would like to view logs for",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        window.location = "/filtered?service="+service+"&queue="+inputValue;
        swal.close();
    });
});
$("#fixAllButton").click(function() {
    swal({
        title: "Fix All",
        text: "Set all logs as fixed for desired queue, no going back",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        $.post('/fixAll/', {
            queue: inputValue
        }, function() {
            location.reload();
        });

        swal.close();
    });
});
$('.retryButton').click(function () {
    var messageId = $(this).attr('messageId');
    var correlationId = $(this).attr('correlationId');
    var text = $(this).attr('text');
    var queue = $(this).attr('queue');
    $.post('/retry/', {
        correlationId: correlationId,
        text: text,
        queue: queue
    }, function() {
        $("#"+messageId).remove();
    });
});
$('.fixButton').click(function () {
    var messageId = $(this).attr('messageId');
    var updateId = $(this).attr('logId');
    var index = $(this).attr('index');
    $.post('/fixed/', {
        updateId: updateId,
        index: index
    }, function() {
        $("#"+messageId).remove();
    });
});
$('.changeQueueButton').click(function () {
    var messageId = $(this).attr('messageId');
    var correlationId = $(this).attr('correlationId');
    var text = $(this).attr('text');
    swal({
        title: "Change Queue",
        text: "please input the queue you'd like this document to be sent",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "desired queue..."
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to provide a queue");
            return false;
        }
        $.post('/retry/', {
            correlationId: correlationId,
            text: text,
            queue: inputValue
        }, function() {
            $("#"+messageId).remove();
        });
        swal.close();
    });
});
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isProbability = require( '@stdlib/assert/is-probability' ).isPrimitive;
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var geometric0 = require( './geometric.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating geometric distributed random numbers.
*
* @param {Probability} [p] - success probability
* @param {Options} [options] - function options
* @param {*} [options.seed] - pseudorandom number generator seed
* @throws {TypeError} `p` must be a probability
* @throws {TypeError} options argument must be an object
* @returns {Function} pseudorandom number generator
*
* @example
* var geometric = factory( 0.5 );
* var v = geometric();
* // returns <number>
*
* @example
* var geometric = factory( 0.8, {
*     'seed': 297
* });
* var v = geometric();
* // returns <number>
*
* @example
* var geometric = factory();
* var v = geometric( 0.5 );
* // returns <number>
*/
function factory() {
	var opts;
	var rand;
	var prng;
	var p;

	if ( arguments.length === 0 ) {
		rand = randu();
	} else if (
		arguments.length === 1 &&
		isObject( arguments[ 0 ] )
	) {
		rand = randu( arguments[ 0 ] );
	} else {
		p = arguments[ 0 ];
		if ( !isProbability( p ) ) {
			throw new TypeError( 'invalid argument. First argument must be a probability. Value: `' + p + '`.' );
		}
		if ( arguments.length > 1 ) {
			opts = arguments[ 1 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			rand = randu( opts );
		} else {
			rand = randu();
		}
	}
	rand = rand.normalized;

	if ( p === void 0 ) {
		prng = geometric2;
	} else {
		prng = geometric1;
	}
	setReadOnly( prng, 'NAME', 'geometric' );
	setReadOnly( prng, 'seed', rand.seed );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns a pseudorandom number drawn from a geometric distribution with bound parameter `p`.
	*
	* @private
	* @returns {NonNegativeInteger} pseudorandom number
	*
	* @example
	* var v = geometric1();
	* // returns <number>
	*/
	function geometric1() {
		return geometric0( rand, p );
	}

	/**
	* Returns a pseudorandom number drawn from a geometric distribution with parameter `p`.
	*
	* @private
	* @param {Probability} p - success probability
	* @returns {NonNegativeInteger} pseudorandom number
	*
	* @example
	* var v = geometric2( 0.5 );
	* // returns <number>
	*/
	function geometric2( p ) {
		if (
			isnan( p ) ||
			p < 0.0 ||
			p > 1.0
		) {
			return NaN;
		}
		return geometric0( rand, p );
	}
}

// EXPORTS //

module.exports = factory;
<commit_msg>Add support for getting and setting PRNG state<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isProbability = require( '@stdlib/assert/is-probability' ).isPrimitive;
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var geometric0 = require( './geometric.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating geometric distributed random numbers.
*
* @param {Probability} [p] - success probability
* @param {Options} [options] - function options
* @param {(uinteger32|Collection<uinteger32>)} [options.seed] - pseudorandom number generator seed
* @param {Uint32Array} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `p` must be a probability
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {Function} pseudorandom number generator
*
* @example
* var geometric = factory( 0.5 );
* var v = geometric();
* // returns <number>
*
* @example
* var geometric = factory( 0.8, {
*     'seed': 297
* });
* var v = geometric();
* // returns <number>
*
* @example
* var geometric = factory();
* var v = geometric( 0.5 );
* // returns <number>
*/
function factory() {
	var opts;
	var rand;
	var prng;
	var p;

	if ( arguments.length === 0 ) {
		rand = randu();
	} else if (
		arguments.length === 1 &&
		isObject( arguments[ 0 ] )
	) {
		rand = randu( arguments[ 0 ] );
	} else {
		p = arguments[ 0 ];
		if ( !isProbability( p ) ) {
			throw new TypeError( 'invalid argument. First argument must be a probability. Value: `' + p + '`.' );
		}
		if ( arguments.length > 1 ) {
			opts = arguments[ 1 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			rand = randu( opts );
		} else {
			rand = randu();
		}
	}
	rand = rand.normalized;

	if ( p === void 0 ) {
		prng = geometric2;
	} else {
		prng = geometric1;
	}
	setReadOnly( prng, 'NAME', 'geometric' );
	setReadOnlyAccessor( prng, 'seed', getSeed );
	setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
	setReadWriteAccessor( prng, 'state', getState, setState );
	setReadOnlyAccessor( prng, 'stateLength', getStateLength );
	setReadOnlyAccessor( prng, 'byteLength', getStateSize );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns the PRNG seed.
	*
	* @private
	* @returns {Uint32Array} seed
	*/
	function getSeed() {
		return rand.seed;
	}

	/**
	* Returns the PRNG seed length.
	*
	* @private
	* @returns {PositiveInteger} seed length
	*/
	function getSeedLength() {
		return rand.seedLength;
	}

	/**
	* Returns the PRNG state length.
	*
	* @private
	* @returns {PositiveInteger} state length
	*/
	function getStateLength() {
		return rand.stateLength;
	}

	/**
	* Returns the PRNG state size (in bytes).
	*
	* @private
	* @returns {PositiveInteger} state size (in bytes)
	*/
	function getStateSize() {
		return rand.byteLength;
	}

	/**
	* Returns the current pseudorandom number generator state.
	*
	* @private
	* @returns {Uint32Array} current state
	*/
	function getState() {
		return rand.state;
	}

	/**
	* Sets the pseudorandom number generator state.
	*
	* @private
	* @param {Uint32Array} s - generator state
	* @throws {TypeError} must provide a `Uint32Array`
	* @throws {Error} must provide a valid state
	*/
	function setState( s ) {
		rand.state = s;
	}

	/**
	* Returns a pseudorandom number drawn from a geometric distribution with bound parameter `p`.
	*
	* @private
	* @returns {NonNegativeInteger} pseudorandom number
	*
	* @example
	* var v = geometric1();
	* // returns <number>
	*/
	function geometric1() {
		return geometric0( rand, p );
	}

	/**
	* Returns a pseudorandom number drawn from a geometric distribution with parameter `p`.
	*
	* @private
	* @param {Probability} p - success probability
	* @returns {NonNegativeInteger} pseudorandom number
	*
	* @example
	* var v = geometric2( 0.5 );
	* // returns <number>
	*/
	function geometric2( p ) {
		if (
			isnan( p ) ||
			p < 0.0 ||
			p > 1.0
		) {
			return NaN;
		}
		return geometric0( rand, p );
	}
}

// EXPORTS //

module.exports = factory;
<|endoftext|>


<commit_before>/**
 * jspsych-survey-multi-choice
 * a jspsych plugin for multiple choice survey questions
 *
 * Shane Martin
 *
 * documentation: docs.jspsych.org
 *
 */

jsPsych.plugins['survey-multi-choice'] = (function() {
  var plugin = {};

  plugin.info = {
    name: 'survey-multi-choice',
    description: '',
    parameters: {
      questions: {
        type: [jsPsych.plugins.parameterType.STRING],
        array: true,
        default: undefined,
        no_function: false,
        description: ''
      },
      options: {
        type: [jsPsych.plugins.parameterType.STRING],
        array: true,
        default: undefined,
        no_function: false,
        description: ''
      },
      required: {
        type: [jsPsych.plugins.parameterType.BOOL],
        array: true,
        default: false,
        no_function: false,
        description: ''
      },
      horitzontal: {
        type: [jsPsych.plugins.parameterType.BOOL],
        default: false,
        no_function: false,
        description: ''
      },
      preamble: {
        type: [jsPsych.plugins.parameterType.STRING],
        default: '',
        no_function: false,
        description: ''
      }
    }
  }
  plugin.trial = function(display_element, trial) {
    var plugin_id_name = "jspsych-survey-multi-choice";
    var plugin_id_selector = '#' + plugin_id_name;
    var _join = function( /*args*/ ) {
      var arr = Array.prototype.slice.call(arguments, _join.length);
      return arr.join(separator = '-');
    }

    // trial defaults
    trial.preamble = typeof trial.preamble == 'undefined' ? "" : trial.preamble;
    trial.required = typeof trial.required == 'undefined' ? null : trial.required;
    trial.horizontal = typeof trial.required == 'undefined' ? false : trial.horizontal;

    // if any trial variables are functions
    // this evaluates the function and replaces
    // it with the output of the function
    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

    // inject CSS for trial
    var node = display_element.innerHTML += '


<commit_before>'use strict'

import aws from 'aws-sdk'
import awsServerlessExpressMiddleware from 'aws-serverless-express/middleware'
import bodyParser from 'body-parser'
import cors from 'cors'
import express from 'express'
import jwt from 'express-jwt'
import {getAuth0Secret} from './helpers/kmsTools'
import morgan from 'morgan'
import uuid from 'node-uuid'
import _ from 'lodash'
import crypto from 'crypto'

const app = express()
const dynamodb = new aws.DynamoDB({
  region: 'us-west-2'
})
const docClient = new aws.DynamoDB.DocumentClient({
  service: dynamodb
})

function filterUser(user) {
  const copy = _.cloneDeep(user)

  delete copy.exp;
  delete copy.iat;

  copy.userId = crypto.createHmac('sha256', copy.sub).digest('hex')
  delete copy.sub

  return copy
}

function getResp(msg) {
  const resp = _.cloneDeep(msg)
  delete resp.userPrivate
  return resp
}

console.log('App initialized...')

function configure(app, auth0Secret) {
  console.log('Configuring express app...')
  app.use(cors())
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))
  app.use(awsServerlessExpressMiddleware.eventContext())
  app.use(morgan('combined'))

  const router = express.Router()

  router.all('*', jwt({
    secret: new Buffer(auth0Secret, 'base64'),
    issuer: 'https://chickchat.auth0.com/',
    audience: '5mEPvtSaOrH23TKWEebEBZZkHcE4N072',
    credentialsRequired: true,
  }))

  router.get('/', (req, res) => {
    res.json({ msg: 'stuff!'})
  })

  router.get('/message', (req, res) => {
    docClient.scan({
      TableName: 'chickchat',
      ConsistentRead: true,
    }).promise().then((data) => {
      const items = data.Items.map(getResp)
      console.log(items)
      items.sort((a, b) => {
        return a.timestampUtc - b.timestampUtc
      })
      console.log(items)
      res.json({
        messages: items,
        count: items.length,
      })
    }).catch((err) => {
      console.log(err)
      res.status(500).json({ message: err.message })
    })
  })

  router.post('/message', (req, res) => {
    const msg = {
      messageId: uuid.v4(),
      text: req.body.text || null,
      data: req.body.data || null,
      author: filterUser(req.user),
      userPrivate: req.user,
      timestampUtc: Date.now(),
    }

    docClient.put({
      TableName: 'chickchat',
      Item: msg,
    }).promise().then(() => {
      const resp = getResp(msg)
      res.json(resp)
    }).catch((err) => {
      console.log('Failed to put item in DynamoDB.')
      console.log(err)
      res.status(500).json({ msg: err.message })
    })
  })

  app.use('/', router)

  app.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
      res.status(401).json({ msg: err.message })
    }
  })
}

module.exports = new Promise((resolve, reject) => {
  const p = getAuth0Secret().then((data) => {
    configure(app, data)
    resolve(app)
  }).catch((err) => {
    reject(err)
  })
})
<commit_msg>remove unused route<commit_after>'use strict'

import aws from 'aws-sdk'
import awsServerlessExpressMiddleware from 'aws-serverless-express/middleware'
import bodyParser from 'body-parser'
import cors from 'cors'
import express from 'express'
import jwt from 'express-jwt'
import {getAuth0Secret} from './helpers/kmsTools'
import morgan from 'morgan'
import uuid from 'node-uuid'
import _ from 'lodash'
import crypto from 'crypto'

const app = express()
const dynamodb = new aws.DynamoDB({
  region: 'us-west-2'
})
const docClient = new aws.DynamoDB.DocumentClient({
  service: dynamodb
})

function filterUser(user) {
  const copy = _.cloneDeep(user)

  delete copy.exp;
  delete copy.iat;

  copy.userId = crypto.createHmac('sha256', copy.sub).digest('hex')
  delete copy.sub

  return copy
}

function getResp(msg) {
  const resp = _.cloneDeep(msg)
  delete resp.userPrivate
  return resp
}

console.log('App initialized...')

function configure(app, auth0Secret) {
  console.log('Configuring express app...')
  app.use(cors())
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))
  app.use(awsServerlessExpressMiddleware.eventContext())
  app.use(morgan('combined'))

  const router = express.Router()

  router.all('*', jwt({
    secret: new Buffer(auth0Secret, 'base64'),
    issuer: 'https://chickchat.auth0.com/',
    audience: '5mEPvtSaOrH23TKWEebEBZZkHcE4N072',
    credentialsRequired: true,
  }))

  router.get('/message', (req, res) => {
    docClient.scan({
      TableName: 'chickchat',
      ConsistentRead: true,
    }).promise().then((data) => {
      const items = data.Items.map(getResp)
      console.log(items)
      items.sort((a, b) => {
        return a.timestampUtc - b.timestampUtc
      })
      console.log(items)
      res.json({
        messages: items,
        count: items.length,
      })
    }).catch((err) => {
      console.log(err)
      res.status(500).json({ message: err.message })
    })
  })

  router.post('/message', (req, res) => {
    const msg = {
      messageId: uuid.v4(),
      text: req.body.text || null,
      data: req.body.data || null,
      author: filterUser(req.user),
      userPrivate: req.user,
      timestampUtc: Date.now(),
    }

    docClient.put({
      TableName: 'chickchat',
      Item: msg,
    }).promise().then(() => {
      const resp = getResp(msg)
      res.json(resp)
    }).catch((err) => {
      console.log('Failed to put item in DynamoDB.')
      console.log(err)
      res.status(500).json({ msg: err.message })
    })
  })

  app.use('/', router)

  app.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
      res.status(401).json({ msg: err.message })
    }
  })
}

module.exports = new Promise((resolve, reject) => {
  const p = getAuth0Secret().then((data) => {
    configure(app, data)
    resolve(app)
  }).catch((err) => {
    reject(err)
  })
})
<|endoftext|>


<commit_before>'use strict';

angular.module('stormpath')
.controller('SpRegistrationFormCtrl', ['$scope','$user','$auth','$state',function ($scope,$user,$auth,$state) {
  $scope.formModel = (typeof $scope.formModel==='object') ? $scope.formModel : {
    givenName:'',
    surname: '',
    email: '',
    password: ''
  };
  $scope.created = false;
  $scope.enabled = false;
  $scope.creating = false;
  $scope.authenticating = false;
  $scope.submit = function(){
    $scope.creating = true;
    $scope.error = null;
    $user.create($scope.formModel)
      .then(function(enabled){
        $scope.created = true;
        $scope.enabled = enabled;
        if(enabled && $scope.autoLogin){
          $scope.authenticating = true;
          $auth.authenticate({
            username: $scope.formModel.email,
            password: $scope.formModel.password
          })
          .then(function(){
            if($scope.postLoginState){
              $state.go($scope.postLoginState);
            }
          })
          .catch(function(response){
            $scope.error = response.data.errorMessage;
          })
          .finally(function(){
            $scope.authenticating = false;
            $scope.creating = false;
          });
        }else{
          $scope.creating = false;
        }
      })
      .catch(function(response){
        $scope.creating = false;
        $scope.error = response.data.errorMessage;
      });
  };
}])

/**
 * @ngdoc directive
 * @name stormpath.spRegistrationForm:spRegistrationForm
 *
 * @param {boolean} autoLogin Default `false`, automatically authenticate the user
 * after creation.  This makes a call to
 * {@link stormpath.authService.$auth#methods_authenticate $auth.authenticate} which will
 * trigger the event {@link stormpath.authService.$auth#events_$authenticated $authenticated}.
 * This is not
 * possible if the email verification workflow is enabled on the directory that
 * the account is created in.
 *
 * @param {string} postLoginState If using the `autoLogin` option, you can
 * specify the name of a UI state that the user should be redirected to after
 * they successfully register
 *
 * @description
 * This directive will render a pre-built user registration form with the following
 * fields:
 *  * First Name
 *  * Last Name
 *  * Email
 *  * Password
 *
 * If you are using the email verification workflow: this form will tell the user
 * that they need to check their email to complete their registration.
 *
 * If you are NOT using the email verification workflow: you can, optionally,
 * automatically login the user and redirect them to a UI state in your application.
 * See the options below.
 *
 * # Server Interaction
 *
 * This directive makes a call to
 * {@link stormpath.userService.$user#methods_create $user.create()}
 * when it is ready to POST the form to the server, please see that method
 * for more information.
 *
 * @param {string} template-url An alternate template URL, if you want
 * to use your own template for the form.
 *
 * @example
 *

 *
 *

 *

 *

 *
 *
 *

 *

 *

 *

 */
.directive('spRegistrationForm',function(){
  return {
    templateUrl: function(tElemenet,tAttrs){
      return tAttrs.templateUrl || 'spRegistrationForm.tpl.html';
    },
    controller: 'SpRegistrationFormCtrl',
    link: function(scope,element,attrs){
      scope.autoLogin = attrs.autoLogin==='true';
      scope.postLoginState = attrs.postLoginState || '';
    }
  };
});<commit_msg>document how to customize the registration form<commit_after>'use strict';

angular.module('stormpath')
.controller('SpRegistrationFormCtrl', ['$scope','$user','$auth','$state',function ($scope,$user,$auth,$state) {
  $scope.formModel = (typeof $scope.formModel==='object') ? $scope.formModel : {
    givenName:'',
    surname: '',
    email: '',
    password: ''
  };
  $scope.created = false;
  $scope.enabled = false;
  $scope.creating = false;
  $scope.authenticating = false;
  $scope.submit = function(){
    $scope.creating = true;
    $scope.error = null;
    $user.create($scope.formModel)
      .then(function(enabled){
        $scope.created = true;
        $scope.enabled = enabled;
        if(enabled && $scope.autoLogin){
          $scope.authenticating = true;
          $auth.authenticate({
            username: $scope.formModel.email,
            password: $scope.formModel.password
          })
          .then(function(){
            if($scope.postLoginState){
              $state.go($scope.postLoginState);
            }
          })
          .catch(function(response){
            $scope.error = response.data.errorMessage;
          })
          .finally(function(){
            $scope.authenticating = false;
            $scope.creating = false;
          });
        }else{
          $scope.creating = false;
        }
      })
      .catch(function(response){
        $scope.creating = false;
        $scope.error = response.data.errorMessage;
      });
  };
}])

/**
 * @ngdoc directive
 * @name stormpath.spRegistrationForm:spRegistrationForm
 *
 * @param {boolean} autoLogin Default `false`, automatically authenticate the user
 * after creation.  This makes a call to
 * {@link stormpath.authService.$auth#methods_authenticate $auth.authenticate} which will
 * trigger the event {@link stormpath.authService.$auth#events_$authenticated $authenticated}.
 * This is not
 * possible if the email verification workflow is enabled on the directory that
 * the account is created in.
 *
 * @param {string} postLoginState If using the `autoLogin` option, you can
 * specify the name of a UI state that the user should be redirected to after
 * they successfully register
 *
 * @description
 * This directive will render a pre-built user registration form with the following
 * fields:
 *  * First Name
 *  * Last Name
 *  * Email
 *  * Password
 *
 * # Customizing the form
 *
 * If you would like to customize the form:
 *
 * * Create a new view file in your application
 * * Copy our default template into your file, found here:
 * spRegistrationForm.tpl.html
 * * Modify the template to fit your needs, making sure to use `formModel.<FIELD>` as the
 * value for `ng-model`, where `.<FIELD>` is the name of the field you want to set on
 * the new account (such as
 * `middleName`)
 * * Use the `template-url` option on the directive to point to your new view file
 *
 * If you would like to add Custom Data to the new account, you can add form inputs to the template
 * and use `formModel.customData.<FIELD>` as the value for `ng-model`
 *
 * # Email Verification
 *
 * If you are using the email verification workflow the default template has a message
 * which will be shown to the user, telling them that they need to check their email
 * for verification.
 *
 * If you are NOT using the email verification workflow you can, optionally,
 * automatically login the user and redirect them to a UI state in your application.
 * See the options below.
 *
 *
 * # Server Interaction
 *
 * This directive makes a call to
 * {@link stormpath.userService.$user#methods_create $user.create()}
 * when it is ready to POST the form to the server, please see that method
 * for more information.
 *
 * @param {string} template-url An alternate template URL, if you want
 * to use your own template for the form.
 *
 * @example
 *

 *
 *

 *

 *

 *
 *
 *

 *

 *

 *

 */
.directive('spRegistrationForm',function(){
  return {
    templateUrl: function(tElemenet,tAttrs){
      return tAttrs.templateUrl || 'spRegistrationForm.tpl.html';
    },
    controller: 'SpRegistrationFormCtrl',
    link: function(scope,element,attrs){
      scope.autoLogin = attrs.autoLogin==='true';
      scope.postLoginState = attrs.postLoginState || '';
    }
  };
});<|endoftext|>


<commit_before>/**
 * Created by c13lbm on 4/27/16.
 */

var TeacherRecordVideo = React.createClass({
    formDataBuilder: function (blob, fileName) {
            var fd = new FormData();

            var id_array = this.props.idArray;
            var student = this.props.studentArray;

            fd.append("feedbackVideo", blob);
            fd.append('submission', new Blob([JSON.stringify({
                        // Submission data
                        studentID: student[0].studentID,
                        assignmentID: id_array[0].assignmentID,
                        courseID: id_array[0].courseID,

            })], {
                type: "application/json"
            }));

            return fd;
       },
    playVideo: function (fName) {
    },
    render: function () {
        var id_array = this.props.idArray;
        var student = this.props.studentArray;
        var submissionURL = "assignments/" + id_array[0].assignmentID + "/submissions/" + student[0].studentID + "/feedbackvideo/";
        return (

Teacher Recording Video

                        <Recorder playCallback={this.playVideo}
                                  postURL={submissionURL}
                                  formDataBuilder={this.formDataBuilder}
                                  recButtonID="teacherRecordButton"
                                  stopButtonID="teacherStopButton"
                                  fileName="feedback.webm" replay="true"
                                  postButtonID="postTeacherVideo"
                                  siteView="feedback" camOnLoad="true"
                                  contID="teacherRecorder"
                        />

                        <button id="teacherRecordButton" className="recControls">Record</button>
                        <button id="teacherStopButton" className="recControls" disabled>Stop</button>
                        <button id="postTeacherVideo" className="recControls" disabled>POST</button>

        );
    }
});

window.TeacherRecordVideo = TeacherRecordVideo;
<commit_msg>TeacherFeedbackFrontEnd: Removed disabled from stopButton<commit_after>/**
 * Created by c13lbm on 4/27/16.
 */

var TeacherRecordVideo = React.createClass({
    formDataBuilder: function (blob, fileName) {
            var fd = new FormData();
            var id_array = this.props.idArray;
            var student = this.props.studentArray;

            fd.append("feedbackVideo", blob);
            return fd;
       },
    playVideo: function (fName) {
    },
    render: function () {
        var id_array = this.props.idArray;
        var student = this.props.studentArray;
        var submissionURL = "assignments/" + id_array[0].assignmentID + "/submissions/" + student[0].studentID + "/feedbackvideo/";
        return (

Teacher Recording Video

                        <Recorder playCallback={this.playVideo}
                                  postURL={submissionURL}
                                  formDataBuilder={this.formDataBuilder}
                                  recButtonID="teacherRecordButton"
                                  stopButtonID="teacherStopButton"
                                  fileName="feedback.webm" replay="true"
                                  postButtonID="postTeacherVideo"
                                  siteView="feedback" camOnLoad="true"
                                  contID="teacherRecorder"
                        />

                        <button id="teacherRecordButton" className="recControls">Record</button>
                        <button id="teacherStopButton" className="recControls" >Stop</button>
                        <button id="postTeacherVideo" className="recControls" disabled>POST</button>

        );
    }
});

window.TeacherRecordVideo = TeacherRecordVideo;
<|endoftext|>


<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

//============================================================================
// QuickHelp button
//============================================================================

var IPython = (function (IPython) {
    "use strict";

    var platform = IPython.utils.platform;

    var QuickHelp = function (selector) {
    };

    var cmd_ctrl = 'Ctrl-';
    var platform_specific;

    if (platform === 'MacOS') {
        // Mac OS X specific
        cmd_ctrl = 'Cmd-';
        platform_specific = [
            { shortcut: "Cmd-Up",     help:"go to cell start"  },
            { shortcut: "Cmd-Down",   help:"go to cell end"  },
            { shortcut: "Opt-Left",   help:"go one word left"  },
            { shortcut: "Opt-Right",  help:"go one word right"  },
            { shortcut: "Opt-Backspace",      help:"del word before"  },
            { shortcut: "Opt-Delete",         help:"del word after"  },
        ];
    } else {
        // PC specific
        platform_specific = [
            { shortcut: "Ctrl-Home",  help:"go to cell start"  },
            { shortcut: "Ctrl-Up",     help:"go to cell start"  },
            { shortcut: "Ctrl-End",   help:"go to cell end"  },
            { shortcut: "Ctrl-Down",  help:"go to cell end"  },
            { shortcut: "Ctrl-Left",  help:"go one word left"  },
            { shortcut: "Ctrl-Right", help:"go one word right"  },
            { shortcut: "Ctrl-Backspace", help:"del word before"  },
            { shortcut: "Ctrl-Delete",    help:"del word after"  },
        ];
    }

    var cm_shortcuts = [
        { shortcut:"Tab",   help:"code completion or indent" },
        { shortcut:"Shift-Tab",   help:"tooltip" },
        { shortcut: cmd_ctrl + "]",   help:"indent"  },
        { shortcut: cmd_ctrl + "[",   help:"dedent"  },
        { shortcut: cmd_ctrl + "a",   help:"select all"  },
        { shortcut: cmd_ctrl + "z",   help:"undo"  },
        { shortcut: cmd_ctrl + "Shift-z",   help:"redo"  },
        { shortcut: cmd_ctrl + "y",   help:"redo"  },
    ].concat( platform_specific );

    QuickHelp.prototype.show_keyboard_shortcuts = function () {
        // toggles display of keyboard shortcut dialog
        var that = this;
        if ( this.force_rebuild ) {
            this.shortcut_dialog.remove();
            delete(this.shortcut_dialog);
            this.force_rebuild = false;
        }
        if ( this.shortcut_dialog ){
            // if dialog is already shown, close it
            $(this.shortcut_dialog).modal("toggle");
            return;
        }
        var command_shortcuts = IPython.keyboard_manager.command_shortcuts.help();
        var edit_shortcuts = IPython.keyboard_manager.edit_shortcuts.help();
        var help, shortcut;
        var i, half, n;
        var element = $('
');

        // The documentation
        var doc = $('
').addClass('alert');
        doc.append(
            $('<button/>').addClass('close').attr('data-dismiss','alert').html('×')
        ).append(
            'The IPython Notebook has two different keyboard input modes. Edit mode '+
            'allows you to type code/text into a cell and is indicated by a green cell '+
            'border. Command mode binds the keyboard to notebook level actions '+
            'and is indicated by a grey cell border.'
        );
        element.append(doc);

        // Command mode
        var cmd_div = this.build_command_help();
        element.append(cmd_div);

        // Edit mode
        var edit_div = this.build_edit_help(cm_shortcuts);
        element.append(edit_div);

        this.shortcut_dialog = IPython.dialog.modal({
            title : "Keyboard shortcuts",
            body : element,
            destroy : false,
            buttons : {
                Close : {}
            }
        });
        this.shortcut_dialog.addClass("modal_stretch");

        $([IPython.events]).on('rebuild.QuickHelp', function() { that.force_rebuild = true;});
    };

    QuickHelp.prototype.build_command_help = function () {
        var command_shortcuts = IPython.keyboard_manager.command_shortcuts.help();
        return build_div('
Command Mode (press Esc to enable)
', command_shortcuts);
    };

    var special_case = { pageup: "PageUp", pagedown: "Page Down", 'minus': '-' };
    var prettify = function (s) {
        s = s.replace(/-$/, 'minus'); // catch shortcuts using '-' key
        var keys = s.split('-');
        var k, i;
        for (i=0; i < keys.length; i++) {
            k = keys[i];
            if ( k.length == 1 ) {
                keys[i] = "" + k + "";
                continue; // leave individual keys lower-cased
            }
            keys[i] = ( special_case[k] ? special_case[k] : k.charAt(0).toUpperCase() + k.slice(1) );
            keys[i] = "" + keys[i] + "";
        }
        return keys.join('-');

    };

    QuickHelp.prototype.build_edit_help = function (cm_shortcuts) {
        var edit_shortcuts = IPython.keyboard_manager.edit_shortcuts.help();
        jQuery.extend(cm_shortcuts, edit_shortcuts);
        return build_div('
Edit Mode (press Enter to enable)
', cm_shortcuts);
    };

    var build_one = function (s) {
        var help = s.help;
        var shortcut = prettify(s.shortcut);
        return $('
').addClass('quickhelp').
            append($('').addClass('shortcut_key').append($(shortcut))).
            append($('').addClass('shortcut_descr').text(' : ' + help));

    };

    var build_div = function (title, shortcuts) {
        var i, half, n;
        var div = $('
').append($(title));
        var sub_div = $('
').addClass('hbox');
        var col1 = $('
').addClass('box-flex1');
        var col2 = $('
').addClass('box-flex1');
        n = shortcuts.length;
        half = ~~(n/2);  // Truncate :)
        for (i=0; i<half; i++) { col1.append( build_one(shortcuts[i]) ); }
        for (i=half; i<n; i++) { col2.append( build_one(shortcuts[i]) ); }
        sub_div.append(col1).append(col2);
        div.append(sub_div);
        return div;
    };

    // Set module variables
    IPython.QuickHelp = QuickHelp;

    return IPython;

}(IPython));
<commit_msg>Fixing bug #5607<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

//============================================================================
// QuickHelp button
//============================================================================

var IPython = (function (IPython) {
    "use strict";

    var platform = IPython.utils.platform;

    var QuickHelp = function (selector) {
    };

    var cmd_ctrl = 'Ctrl-';
    var platform_specific;

    if (platform === 'MacOS') {
        // Mac OS X specific
        cmd_ctrl = 'Cmd-';
        platform_specific = [
            { shortcut: "Cmd-Up",     help:"go to cell start"  },
            { shortcut: "Cmd-Down",   help:"go to cell end"  },
            { shortcut: "Opt-Left",   help:"go one word left"  },
            { shortcut: "Opt-Right",  help:"go one word right"  },
            { shortcut: "Opt-Backspace",      help:"del word before"  },
            { shortcut: "Opt-Delete",         help:"del word after"  },
        ];
    } else {
        // PC specific
        platform_specific = [
            { shortcut: "Ctrl-Home",  help:"go to cell start"  },
            { shortcut: "Ctrl-Up",     help:"go to cell start"  },
            { shortcut: "Ctrl-End",   help:"go to cell end"  },
            { shortcut: "Ctrl-Down",  help:"go to cell end"  },
            { shortcut: "Ctrl-Left",  help:"go one word left"  },
            { shortcut: "Ctrl-Right", help:"go one word right"  },
            { shortcut: "Ctrl-Backspace", help:"del word before"  },
            { shortcut: "Ctrl-Delete",    help:"del word after"  },
        ];
    }

    var cm_shortcuts = [
        { shortcut:"Tab",   help:"code completion or indent" },
        { shortcut:"Shift-Tab",   help:"tooltip" },
        { shortcut: cmd_ctrl + "]",   help:"indent"  },
        { shortcut: cmd_ctrl + "[",   help:"dedent"  },
        { shortcut: cmd_ctrl + "a",   help:"select all"  },
        { shortcut: cmd_ctrl + "z",   help:"undo"  },
        { shortcut: cmd_ctrl + "Shift-z",   help:"redo"  },
        { shortcut: cmd_ctrl + "y",   help:"redo"  },
    ].concat( platform_specific );

    QuickHelp.prototype.show_keyboard_shortcuts = function () {
        // toggles display of keyboard shortcut dialog
        var that = this;
        if ( this.force_rebuild ) {
            this.shortcut_dialog.remove();
            delete(this.shortcut_dialog);
            this.force_rebuild = false;
        }
        if ( this.shortcut_dialog ){
            // if dialog is already shown, close it
            $(this.shortcut_dialog).modal("toggle");
            return;
        }
        var command_shortcuts = IPython.keyboard_manager.command_shortcuts.help();
        var edit_shortcuts = IPython.keyboard_manager.edit_shortcuts.help();
        var help, shortcut;
        var i, half, n;
        var element = $('
');

        // The documentation
        var doc = $('
').addClass('alert');
        doc.append(
            $('<button/>').addClass('close').attr('data-dismiss','alert').html('×')
        ).append(
            'The IPython Notebook has two different keyboard input modes. Edit mode '+
            'allows you to type code/text into a cell and is indicated by a green cell '+
            'border. Command mode binds the keyboard to notebook level actions '+
            'and is indicated by a grey cell border.'
        );
        element.append(doc);

        // Command mode
        var cmd_div = this.build_command_help();
        element.append(cmd_div);

        // Edit mode
        var edit_div = this.build_edit_help(cm_shortcuts);
        element.append(edit_div);

        this.shortcut_dialog = IPython.dialog.modal({
            title : "Keyboard shortcuts",
            body : element,
            destroy : false,
            buttons : {
                Close : {}
            }
        });
        this.shortcut_dialog.addClass("modal_stretch");

        $([IPython.events]).on('rebuild.QuickHelp', function() { that.force_rebuild = true;});
    };

    QuickHelp.prototype.build_command_help = function () {
        var command_shortcuts = IPython.keyboard_manager.command_shortcuts.help();
        return build_div('
Command Mode (press Esc to enable)
', command_shortcuts);
    };

    var special_case = { pageup: "PageUp", pagedown: "Page Down", 'minus': '-' };
    var prettify = function (s) {
        s = s.replace(/-$/, 'minus'); // catch shortcuts using '-' key
        var keys = s.split('-');
        var k, i;
        for (i=0; i < keys.length; i++) {
            k = keys[i];
            if ( k.length == 1 ) {
                keys[i] = "" + k + "";
                continue; // leave individual keys lower-cased
            }
            keys[i] = ( special_case[k] ? special_case[k] : k.charAt(0).toUpperCase() + k.slice(1) );
            keys[i] = "" + keys[i] + "";
        }
        return keys.join('-');

    };

    QuickHelp.prototype.build_edit_help = function (cm_shortcuts) {
        var edit_shortcuts = IPython.keyboard_manager.edit_shortcuts.help();
        jQuery.merge(cm_shortcuts, edit_shortcuts);
        return build_div('
Edit Mode (press Enter to enable)
', cm_shortcuts);
    };

    var build_one = function (s) {
        var help = s.help;
        var shortcut = prettify(s.shortcut);
        return $('
').addClass('quickhelp').
            append($('').addClass('shortcut_key').append($(shortcut))).
            append($('').addClass('shortcut_descr').text(' : ' + help));

    };

    var build_div = function (title, shortcuts) {
        var i, half, n;
        var div = $('
').append($(title));
        var sub_div = $('
').addClass('hbox');
        var col1 = $('
').addClass('box-flex1');
        var col2 = $('
').addClass('box-flex1');
        n = shortcuts.length;
        half = ~~(n/2);  // Truncate :)
        for (i=0; i<half; i++) { col1.append( build_one(shortcuts[i]) ); }
        for (i=half; i<n; i++) { col2.append( build_one(shortcuts[i]) ); }
        sub_div.append(col1).append(col2);
        div.append(sub_div);
        return div;
    };

    // Set module variables
    IPython.QuickHelp = QuickHelp;

    return IPython;

}(IPython));
<|endoftext|>


<commit_before>(function() {

  'use strict';

  angular
    .module('openlmis.requisitions')
    .factory('ColumnTemplateFactory', columnTemplateFactory);

  columnTemplateFactory.$inject = ['$q', '$resource', 'RequisitionURL', 'Column', 'Source', 'Status'];

  function columnTemplateFactory($q, $resource, RequisitionURL, Column, Source, Status) {
    var resource = $resource(RequisitionURL('/api/requisitionTemplates/search'));

    var nonMandatoryFields = [
      Column.SKIPPED,
      Column.REMARKS,
      Column.TOTAL_LOSSES_AND_ADJUSTMENTS,
      Column.REQUESTED_QUANTITY_EXPLANATION
    ];

    var dependencies = {
      stockOnHand: [
        Column.BEGINNING_BALANCE,
        Column.TOTAL_RECEIVED_QUANTITY,
        Column.TOTAL_CONSUMED_QUANTITY,
        Column.TOTAL_LOSSES_AND_ADJUSTMENTS
      ],
      requestedQuantityExplanation: [
        Column.REQUESTED_QUANTITY
      ]
    };

    var factory = {
      getColumnTemplates: getColumnTemplates
    }
    return factory;

    function getColumnTemplates(requisition) {
      var deferred = $q.defer();

      resource.get({
        program: requisition.program.id
      }).$promise.then(function(response) {
        deferred.resolve(toColumnTemplates(response, requisition));
      }, function(error) {
        deferred.reject(error);
      })

      return deferred.promise;
    }

    function toColumnTemplates(requisitionTemplate, requisition) {
      var columnTemplates = [];
      angular.forEach(requisitionTemplate.columnsMap, function(column) {
        columnTemplates.push(toColumnTemplate(column, requisition));
      });
      return columnTemplates
    }

    function toColumnTemplate(column, requisition) {
      var name = column.name,
          source = column.source;

      return {
        name: name,
        type: column.columnDefinition.columnType,
        source: source,
        label: column.label,
        display: displayColumn(column, requisition),
        displayOrder: column.displayOrder,
        required: (nonMandatoryFields.indexOf(name) === -1 && source == Source.USER_INPUT),
        dependencies: dependencies[name]
      };
    }

    function displayColumn(column, requisition) {
      return column.isDisplayed && (
              [Column.APPROVED_QUANTITY, Column.REMARKS].indexOf(column.name) === -1 ||
              [Status.AUTHORIZED, Status.APPROVED].indexOf(status) > -1);
    }
  }

})();<commit_msg>OLMIS-818: Fixed the condition for displaying columns<commit_after>(function() {

  'use strict';

  angular
    .module('openlmis.requisitions')
    .factory('ColumnTemplateFactory', columnTemplateFactory);

  columnTemplateFactory.$inject = ['$q', '$resource', 'RequisitionURL', 'Column', 'Source', 'Status'];

  function columnTemplateFactory($q, $resource, RequisitionURL, Column, Source, Status) {
    var resource = $resource(RequisitionURL('/api/requisitionTemplates/search'));

    var nonMandatoryFields = [
      Column.SKIPPED,
      Column.REMARKS,
      Column.TOTAL_LOSSES_AND_ADJUSTMENTS,
      Column.REQUESTED_QUANTITY_EXPLANATION
    ];

    var dependencies = {
      stockOnHand: [
        Column.BEGINNING_BALANCE,
        Column.TOTAL_RECEIVED_QUANTITY,
        Column.TOTAL_CONSUMED_QUANTITY,
        Column.TOTAL_LOSSES_AND_ADJUSTMENTS
      ],
      requestedQuantityExplanation: [
        Column.REQUESTED_QUANTITY
      ]
    };

    var factory = {
      getColumnTemplates: getColumnTemplates
    }
    return factory;

    function getColumnTemplates(requisition) {
      var deferred = $q.defer();

      resource.get({
        program: requisition.program.id
      }).$promise.then(function(response) {
        deferred.resolve(toColumnTemplates(response, requisition));
      }, function(error) {
        deferred.reject(error);
      })

      return deferred.promise;
    }

    function toColumnTemplates(requisitionTemplate, requisition) {
      var columnTemplates = [];
      angular.forEach(requisitionTemplate.columnsMap, function(column) {
        columnTemplates.push(toColumnTemplate(column, requisition));
      });
      return columnTemplates
    }

    function toColumnTemplate(column, requisition) {
      var name = column.name,
          source = column.source;

      return {
        name: name,
        type: column.columnDefinition.columnType,
        source: source,
        label: column.label,
        display: displayColumn(column, requisition),
        displayOrder: column.displayOrder,
        required: (nonMandatoryFields.indexOf(name) === -1 && source == Source.USER_INPUT),
        dependencies: dependencies[name]
      };
    }

    function displayColumn(column, requisition) {
      return column.isDisplayed && (
              [Column.APPROVED_QUANTITY, Column.REMARKS].indexOf(column.name) === -1 ||
              [Status.AUTHORIZED, Status.APPROVED].indexOf(requisition.status) > -1);
    }
  }

})();<|endoftext|>