<commit_before>"use strict";
var React = require("react");

function Action(owner) {
    this.owner = owner;
    this.comments = [];
    this.done = false;
}

Action.prototype.addComment = function(comment) {
    this.comments.push(comment);
};

Action.prototype.addComments = function(comments) {
    var self = this;
    comments.forEach(function(c) {
        self.addComment(c);
    });
};

Action.prototype.isDone = function() {
    return this.done;
};

Action.prototype.setDone = function(done) {
    this.done = done;
};

Action.prototype.getHeadComment = function() {
    return this.comments[0];
};

Action.prototype.getComments = function() {
    return this.comments;
};

/**
 * Convert a list of LineComments into a list of Actions.
 * @param {LineComment[]} cmts A list of line comments
 * @return {Action[]} A list of actions or an empty list
 */
Action.fromLineComments = function(cmts) {
    // Create a new Action for each set of line comments on the same line.
    var actions = [];
    var comments = cmts;
    for (var i = 0; i < comments.length; i++) {
        var currentComment = comments[i];
        var relatedComments = [];
        var lastComment = null;
        for (var j = i + 1; j < comments.length; j++) {
            var testComment = comments[j];
            if (currentComment.matches(testComment)) {
                comments.splice(j--, 1); // remove the matching comment
                relatedComments.push(testComment);
                lastComment = testComment;
            }
        }
        var action = new Action(currentComment.getComment().getUser());
        action.addComment(currentComment);
        action.addComments(relatedComments);
        if (lastComment) {
            // see if we can mark it as done
            var body = lastComment.getComment().getBody();
            if (/^done\b/i.test(body)) {
                action.setDone(true);
            }
        }
        actions.push(action);
    }
    console.log("Action.fromLineComments => %s => %s actions", cmts.length, actions.length);
    return actions;
};

module.exports = Action;
<commit_msg>Done markers: Match done on newline, and fixed<commit_after>"use strict";
var React = require("react");

function Action(owner) {
    this.owner = owner;
    this.comments = [];
    this.done = false;
}

Action.prototype.addComment = function(comment) {
    this.comments.push(comment);
};

Action.prototype.addComments = function(comments) {
    var self = this;
    comments.forEach(function(c) {
        self.addComment(c);
    });
};

Action.prototype.isDone = function() {
    return this.done;
};

Action.prototype.setDone = function(done) {
    this.done = done;
};

Action.prototype.getHeadComment = function() {
    return this.comments[0];
};

Action.prototype.getComments = function() {
    return this.comments;
};

/**
 * Convert a list of LineComments into a list of Actions.
 * @param {LineComment[]} cmts A list of line comments
 * @return {Action[]} A list of actions or an empty list
 */
Action.fromLineComments = function(cmts) {
    // Create a new Action for each set of line comments on the same line.
    var actions = [];
    var comments = cmts;
    for (var i = 0; i < comments.length; i++) {
        var currentComment = comments[i];
        var relatedComments = [];
        var lastComment = null;
        for (var j = i + 1; j < comments.length; j++) {
            var testComment = comments[j];
            if (currentComment.matches(testComment)) {
                comments.splice(j--, 1); // remove the matching comment
                relatedComments.push(testComment);
                lastComment = testComment;
            }
        }
        var action = new Action(currentComment.getComment().getUser());
        action.addComment(currentComment);
        action.addComments(relatedComments);
        if (lastComment) {
            // see if we can mark it as done
            var body = lastComment.getComment().getBody();
            if (/^([^\n]*\n)*done\b/i.test(body) || /^([^\n]*\n)*fixed\b/i.test(body)) {
                action.setDone(true);
            }
        }
        actions.push(action);
    }
    console.log("Action.fromLineComments => %s => %s actions", cmts.length, actions.length);
    return actions;
};

module.exports = Action;
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'

import './ContentContainer.scss'

export default class ContentContainer extends PureComponent {
  render () {
    return (

        {this.props.children}

    )
  }
}

ContentContainer.propTypes = {
  children: PropTypes.any
}
<commit_msg>ContentContainer is needs deep comparison<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'

import './ContentContainer.scss'

export default class ContentContainer extends Component {
  render () {
    return (

        {this.props.children}

    )
  }
}

ContentContainer.propTypes = {
  children: PropTypes.any
}
<|endoftext|>


<commit_before>function getAliveSharks () {
  return Array.from(document.querySelectorAll('.shark:not(.dead)'))
}

// Variables
var randomWords = require('random-words')
var inputField = document.getElementById('playerField')
document.getElementById('score').textContent = 0

// Create the shark words
function generateWords () {
  getAliveSharks().forEach(shark =>
    shark.appendChild(
      document.createTextNode(randomWords(1))
    )
)
  document.getElementById('sharkOne').style.marginLeft = Math.random() * 50 + 'vw'
  document.getElementById('sharkTwo').style.marginLeft = Math.random() * 80 + 'vw'
  document.getElementById('sharkThree').style.marginLeft = Math.random() * 100 + 'vw'
  document.getElementById('sharkFour').style.marginLeft = Math.random() * 30 + 'vw'
  document.querySelector('ul').classList.add('school')
}
generateWords()

// Check words (number 13 refers to Enter key)
inputField.addEventListener('keydown', checkWords)
inputField.addEventListener('keydown', clearField)

function checkWords (event) {
  getAliveSharks().forEach(shark => {
    if (shark.innerText === inputField.value && event.keyCode === 13) {
      shark.classList.add('dead')
      shark.textContent = ''
      document.getElementById('score').textContent = parseInt((document.getElementById('score').textContent), 10) + 1
      end()
    }
  })
}

// Clear the input box
function clearField (event) {
  if (event.keyCode === 13) {
    inputField.value = ''
  }
}
// End the round
function end () {
  if (getAliveSharks().length === 0) {
    Array.from(document.querySelectorAll('li')).forEach(shark => shark.className = 'shark')
    document.querySelector('ul').classList.remove('school')
    setTimeout(function () {
      document.querySelector('ul').classList.add('school')
      generateWords()
    }, 1000)
  }
}

// things to do:
// 1) add the filter function and split up the checkWords function
// 2) change the input to a form so don't have to requure keyCode 13
// 3) can check if animation is paused then restart game
<commit_msg>working version<commit_after>function getAliveSharks () {
  return Array.from(document.querySelectorAll('.shark:not(.dead)'))
}

// Variables
var randomWords = require('random-words')
var inputField = document.getElementById('playerField')
document.getElementById('score').textContent = 0

// Create the shark words
function generateWords () {
  getAliveSharks().forEach(shark =>
    shark.appendChild(
      document.createTextNode(randomWords(1))
    )
)
  document.getElementById('sharkOne').style.marginLeft = Math.random() * 50 + 'vw'
  document.getElementById('sharkTwo').style.marginLeft = Math.random() * 80 + 'vw'
  document.getElementById('sharkThree').style.marginLeft = Math.random() * 100 + 'vw'
  document.getElementById('sharkFour').style.marginLeft = Math.random() * 30 + 'vw'
  document.querySelector('ul').classList.add('school')
}
generateWords()

// Check words (number 13 refers to Enter key)
inputField.addEventListener('keydown', checkWords)
inputField.addEventListener('keydown', clearField)

function checkWords (event) {
  getAliveSharks().forEach(shark => {
    if (shark.innerText === inputField.value && event.keyCode === 13) {
      shark.classList.add('dead')
      shark.textContent = ''
      document.getElementById('score').textContent = parseInt((document.getElementById('score').textContent), 10) + 1
      end()
    }
  })
}

// Clear the input box
function clearField (event) {
  if (event.keyCode === 13) {
    inputField.value = ''
  }
}
// End the round
function end () {
  if (getAliveSharks().length === 0) {
    Array.from(document.querySelectorAll('li')).forEach(shark => shark.className = 'shark')
    document.querySelector('ul').classList.remove('school')
    setTimeout(function () {
      document.querySelector('ul').classList.add('school')
      generateWords()
    }, 500)
  }
}

// things to do:
// 1) add the filter function and split up the checkWords function
// 2) change the input to a form so don't have to requure keyCode 13
// 3) can check if animation is paused then restart game
<|endoftext|>


<commit_before>import Slider, { speedUp } from '../mixin/slider';
import SliderReactive from '../mixin/internal/slider-reactive';
import TransitionerPlugin from './internal/slider-transitioner';
import ParallaxPlugin from './internal/slider-parallax';

function plugin(UIkit) {

    if (plugin.installed) {
        return;
    }

    UIkit.use(Slider);

    var {mixin} = UIkit;
    var {$, $$, addClass, css, data, includes, isNumeric, isUndefined, toggleClass, toFloat} = UIkit.util;
    var Transitioner = TransitionerPlugin(UIkit);

    UIkit.component('slider-parallax', ParallaxPlugin(UIkit, 'slider'));

    UIkit.component('slider', {

        mixins: [mixin.class, mixin.slider, SliderReactive(UIkit)],

        props: {
            center: Boolean,
            sets: Boolean,
        },

        defaults: {
            center: false,
            sets: false,
            attrItem: 'uk-slider-item',
            selList: '.uk-slider-items',
            selNav: '.uk-slider-nav',
            clsContainer: 'uk-slider-container',
            Transitioner
        },

        computed: {

            avgWidth() {
                return Transitioner.getWidth(this.list) / this.length;
            },

            finite({finite}) {
                return finite || Transitioner.getWidth(this.list) < this.list.offsetWidth + Transitioner.getMaxWidth(this.list) + this.center;
            },

            maxIndex() {

                if (!this.finite || this.center && !this.sets) {
                    return this.length - 1;
                }

                if (this.center) {
                    return this.sets[this.sets.length - 1];
                }

                css(this.slides, 'order', '');

                var max = Transitioner.getMax(this.list), i = this.length;

                while (i--) {
                    if (Transitioner.getElLeft(this.list.children[i], this.list) < max) {
                        return Math.min(i + 1, this.length - 1);
                    }
                }

                return 0;
            },

            sets({sets}) {

                var width = this.list.offsetWidth / (this.center ? 2 : 1),
                    left = 0,
                    leftCenter = width;

                css(this.slides, 'order', '');

                sets = sets && this.slides.reduce((sets, slide, i) => {

                    var slideWidth = slide.offsetWidth,
                        slideLeft = Transitioner.getElLeft(slide, this.list),
                        slideRight = slideLeft + slideWidth;

                    if (slideRight > left) {

                        if (!this.center && i > this.maxIndex) {
                            i = this.maxIndex;
                        }

                        if (!includes(sets, i)) {

                            var cmp = this.slides[i + 1];
                            if (this.center && cmp && slideWidth < leftCenter - cmp.offsetWidth / 2) {
                                leftCenter -= slideWidth;
                            } else {
                                leftCenter = width;
                                sets.push(i);
                                left = slideLeft + width + (this.center ? slideWidth / 2 : 0);
                            }

                        }
                    }

                    return sets;

                }, []);

                return sets && sets.length && sets;

            },

            transitionOptions() {
                return {
                    center: this.center,
                    list: this.list
                };
            }

        },

        connected() {
            toggleClass(this.$el, this.clsContainer, !$(`.${this.clsContainer}`, this.$el));
        },

        update: {

            write() {

                $$(`[${this.attrItem}],[data-${this.attrItem}]`, this.$el).forEach(el => {
                    var index = data(el, this.attrItem);
                    this.maxIndex && toggleClass(el, 'uk-hidden', isNumeric(index) && (this.sets && !includes(this.sets, toFloat(index)) || index > this.maxIndex));
                });

            },

            events: ['load', 'resize']

        },

        events: {

            beforeitemshow(e) {

                if (!this.dragging && this.sets && this.stack.length < 2 && !includes(this.sets, this.index)) {
                    this.index = this.getValidIndex();
                }

                var diff = Math.abs(this.index + (this.dir > 0
                    ? this.index < this.prevIndex ? this.maxIndex + 1 : 0
                    : this.index > this.prevIndex ? -this.maxIndex : 0
                ) - this.prevIndex);

                if (!this.dragging && diff > 1) {

                    for (var i = 0; i < diff; i++) {
                        this.stack.splice(1, 0, this.dir > 0 ? 'next' : 'previous');
                    }

                    e.preventDefault();
                    return;
                }

                this.duration = speedUp(this.avgWidth / this.velocity)
                    * ((
                        this.dir < 0 || !this.slides[this.prevIndex]
                            ? this.slides[this.index]
                            : this.slides[this.prevIndex]
                    ).offsetWidth / this.avgWidth);

                this.reorder();

            },

            itemshow() {
                !isUndefined(this.prevIndex) && addClass(this._getTransitioner().getItemIn(), this.clsActive);
            },

            itemshown() {
                var actives = this._getTransitioner(this.index).getActives();
                this.slides.forEach(slide => toggleClass(slide, this.clsActive, this.clsActivated, includes(actives, slide)));
            }

        },

        methods: {

            reorder() {

                css(this.slides, 'order', '');

                if (this.finite) {
                    return;
                }

                this.slides.forEach((slide, i) =>
                    css(slide, 'order', this.dir > 0 && i < this.prevIndex
                        ? 1
                        : this.dir < 0 && i >= this.index
                            ? -1
                            : ''
                    )
                );

                if (!this.center) {
                    return;
                }

                var index = this.dir > 0 && this.slides[this.prevIndex] ? this.prevIndex : this.index,
                    next = this.slides[index],
                    width = this.list.offsetWidth / 2 - next.offsetWidth / 2,
                    j = 0;

                while (width >= 0) {
                    var slideIndex = this.getIndex(--j + index, index),
                        slide = this.slides[slideIndex];

                    css(slide, 'order', slideIndex > index ? -2 : -1);
                    width -= slide.offsetWidth;
                }

            },

            getValidIndex(index = this.index, prevIndex = this.prevIndex) {

                index = this.getIndex(index, prevIndex);

                if (!this.sets) {
                    return index;
                }

                var prev;

                do {

                    if (includes(this.sets, index)) {
                        return index;
                    }

                    prev = index;
                    index = this.getIndex(index + this.dir, prevIndex);

                } while (index !== prev);

                return index;
            }

        }

    });

}

if (!BUNDLED && typeof window !== 'undefined' && window.UIkit) {
    window.UIkit.use(plugin);
}

export default plugin;
<commit_msg>delay clsActivated for sets mode fix navigating to the left for sets over edge<commit_after>import Slider, { speedUp } from '../mixin/slider';
import SliderReactive from '../mixin/internal/slider-reactive';
import TransitionerPlugin from './internal/slider-transitioner';
import ParallaxPlugin from './internal/slider-parallax';

function plugin(UIkit) {

    if (plugin.installed) {
        return;
    }

    UIkit.use(Slider);

    var {mixin} = UIkit;
    var {$, $$, addClass, css, data, includes, isNumeric, isUndefined, toggleClass, toFloat} = UIkit.util;
    var Transitioner = TransitionerPlugin(UIkit);

    UIkit.component('slider-parallax', ParallaxPlugin(UIkit, 'slider'));

    UIkit.component('slider', {

        mixins: [mixin.class, mixin.slider, SliderReactive(UIkit)],

        props: {
            center: Boolean,
            sets: Boolean,
        },

        defaults: {
            center: false,
            sets: false,
            attrItem: 'uk-slider-item',
            selList: '.uk-slider-items',
            selNav: '.uk-slider-nav',
            clsContainer: 'uk-slider-container',
            Transitioner
        },

        computed: {

            avgWidth() {
                return Transitioner.getWidth(this.list) / this.length;
            },

            finite({finite}) {
                return finite || Transitioner.getWidth(this.list) < this.list.offsetWidth + Transitioner.getMaxWidth(this.list) + this.center;
            },

            maxIndex() {

                if (!this.finite || this.center && !this.sets) {
                    return this.length - 1;
                }

                if (this.center) {
                    return this.sets[this.sets.length - 1];
                }

                css(this.slides, 'order', '');

                var max = Transitioner.getMax(this.list), i = this.length;

                while (i--) {
                    if (Transitioner.getElLeft(this.list.children[i], this.list) < max) {
                        return Math.min(i + 1, this.length - 1);
                    }
                }

                return 0;
            },

            sets({sets}) {

                var width = this.list.offsetWidth / (this.center ? 2 : 1),
                    left = 0,
                    leftCenter = width;

                css(this.slides, 'order', '');

                sets = sets && this.slides.reduce((sets, slide, i) => {

                    var slideWidth = slide.offsetWidth,
                        slideLeft = Transitioner.getElLeft(slide, this.list),
                        slideRight = slideLeft + slideWidth;

                    if (slideRight > left) {

                        if (!this.center && i > this.maxIndex) {
                            i = this.maxIndex;
                        }

                        if (!includes(sets, i)) {

                            var cmp = this.slides[i + 1];
                            if (this.center && cmp && slideWidth < leftCenter - cmp.offsetWidth / 2) {
                                leftCenter -= slideWidth;
                            } else {
                                leftCenter = width;
                                sets.push(i);
                                left = slideLeft + width + (this.center ? slideWidth / 2 : 0);
                            }

                        }
                    }

                    return sets;

                }, []);

                return sets && sets.length && sets;

            },

            transitionOptions() {
                return {
                    center: this.center,
                    list: this.list
                };
            }

        },

        connected() {
            toggleClass(this.$el, this.clsContainer, !$(`.${this.clsContainer}`, this.$el));
        },

        update: {

            write() {

                $$(`[${this.attrItem}],[data-${this.attrItem}]`, this.$el).forEach(el => {
                    var index = data(el, this.attrItem);
                    this.maxIndex && toggleClass(el, 'uk-hidden', isNumeric(index) && (this.sets && !includes(this.sets, toFloat(index)) || index > this.maxIndex));
                });

            },

            events: ['load', 'resize']

        },

        events: {

            beforeitemshow(e) {

                if (!this.dragging && this.sets && this.stack.length < 2 && !includes(this.sets, this.index)) {
                    this.index = this.getValidIndex();
                }

                var diff = Math.abs(
                    this.index
                    - this.prevIndex
                    + (this.dir > 0 && this.index < this.prevIndex || this.dir < 0 && this.index > this.prevIndex ? (this.maxIndex + 1) * this.dir : 0)
                );

                if (!this.dragging && diff > 1) {

                    for (var i = 0; i < diff; i++) {
                        this.stack.splice(1, 0, this.dir > 0 ? 'next' : 'previous');
                    }

                    e.preventDefault();
                    return;
                }

                this.duration = speedUp(this.avgWidth / this.velocity)
                    * ((
                        this.dir < 0 || !this.slides[this.prevIndex]
                            ? this.slides[this.index]
                            : this.slides[this.prevIndex]
                    ).offsetWidth / this.avgWidth);

                this.reorder();

            },

            itemshow() {
                !isUndefined(this.prevIndex) && addClass(this._getTransitioner().getItemIn(), this.clsActive);
            },

            itemshown() {
                var actives = this._getTransitioner(this.index).getActives();
                this.slides.forEach(slide => toggleClass(slide, this.clsActive, includes(actives, slide)));
                (!this.sets || includes(this.sets, toFloat(this.index))) && this.slides.forEach(slide => toggleClass(slide, this.clsActivated, includes(actives, slide)));
            }

        },

        methods: {

            reorder() {

                css(this.slides, 'order', '');

                if (this.finite) {
                    return;
                }

                this.slides.forEach((slide, i) =>
                    css(slide, 'order', this.dir > 0 && i < this.prevIndex
                        ? 1
                        : this.dir < 0 && i >= this.index
                            ? -1
                            : ''
                    )
                );

                if (!this.center) {
                    return;
                }

                var index = this.dir > 0 && this.slides[this.prevIndex] ? this.prevIndex : this.index,
                    next = this.slides[index],
                    width = this.list.offsetWidth / 2 - next.offsetWidth / 2,
                    j = 0;

                while (width >= 0) {
                    var slideIndex = this.getIndex(--j + index, index),
                        slide = this.slides[slideIndex];

                    css(slide, 'order', slideIndex > index ? -2 : -1);
                    width -= slide.offsetWidth;
                }

            },

            getValidIndex(index = this.index, prevIndex = this.prevIndex) {

                index = this.getIndex(index, prevIndex);

                if (!this.sets) {
                    return index;
                }

                var prev;

                do {

                    if (includes(this.sets, index)) {
                        return index;
                    }

                    prev = index;
                    index = this.getIndex(index + this.dir, prevIndex);

                } while (index !== prev);

                return index;
            }

        }

    });

}

if (!BUNDLED && typeof window !== 'undefined' && window.UIkit) {
    window.UIkit.use(plugin);
}

export default plugin;
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/ember-remodal';

const {
  inject,
  computed,
  computed: { reads },
  on,
  RSVP: { Promise },
  run: { next, scheduleOnce },
  sendEvent,
  Component
} = Ember;

export default Component.extend({
  layout,
  remodal: inject.service(),
  attributeBindings: ['dataTestId:data-test-id'],
  classNames: ['remodal-component'],
  tagName: 'span',
  name: 'modal',
  modifier: '',
  modal: null,
  options: null,
  closeOnEscape: true,
  closeOnCancel: true,
  closeOnConfirm: true,
  hashTracking: false,
  closeOnOutsideClick: true,
  forService: false,
  disableForeground: false,
  disableAnimation: false,
  disableNativeClose: reads('disableForeground'),
  erOpenButton: false,
  erCancelButton: false,
  erConfirmButton: false,

  didInitAttrs() {
    let opts = this.get('options');

    if (opts) {
      this.setProperties(opts);
    }

    if (this.get('forService')) {
      this.get('remodal').set(this.get('name'), this);
    }

    scheduleOnce('afterRender', this, '_registerObservers');
    scheduleOnce('afterRender', this, '_checkForDeprecations');
  },

  willDestroy() {
    scheduleOnce('afterRender', this, '_deregisterObservers');
  },

  modalId: computed('elementId', {
    get() {
      return `[data-remodal-id=${this.get('elementId')}]`;
    }
  }),

  animationState: computed('disableAnimation', {
    get() {
      if (this.get('disableAnimation')) {
        return 'disable-animation';
      } else {
        return '';
      }
    }
  }),

  openDidFire: on('opened', function() {
    this.sendAction('onOpen');
  }),

  closeDidFire: on('closed', function() {
    this.sendAction('onClose');
  }),

  open() {
    return this._promiseAction('open');
  },

  close() {
    return this._promiseAction('close');
  },

  _promiseAction(action) {
    let modal = this.get('modalId');

    this.send(action);

    return new Promise((resolve) => {
      Ember.$(document).one(`${action}ed`, modal, () => resolve(this));
    });
  },

  _registerObservers() {
    let modal = this.get('modalId');
    Ember.$(document).on('opened', modal, () => sendEvent(this, 'opened'));
    Ember.$(document).on('closed', modal, () => sendEvent(this, 'closed'));
  },

  _deregisterObservers() {
    let modal = this.get('modalId');
    Ember.$(document).off('opened', modal);
    Ember.$(document).off('closed', modal);
  },

  _createInstanceAndOpen() {
    let modal = Ember.$(this.get('modalId')).remodal({
      hashTracking: this.get('hashTracking'),
      closeOnOutsideClick: this.get('closeOnOutsideClick'),
      closeOnEscape: this.get('closeOnEscape'),
      modifier: this.get('modifier')
    });

    this.set('modal', modal);
    this.send('open');
  },

  _checkForDeprecations() {
    // Deprecations go here
  },

  _openModal() {
    this.get('modal').open();
  },

  _closeModal() {
    this.get('modal').close();
  },

  _closeOnCondition(condition) {
    this.sendAction(`on${condition}`);

    if (this.get(`closeOn${condition}`)) {
      this.send('close');
    }
  },

  actions: {
    confirm() {
      this._closeOnCondition('Confirm');
    },

    cancel() {
      this._closeOnCondition('Cancel');
    },

    open() {
      if (this.get('modal')) {
        scheduleOnce('afterRender', this, '_openModal');
      } else {
        scheduleOnce('afterRender', this, '_createInstanceAndOpen');
      }
    },

    close() {
      next(this, '_closeModal');
    }
  }
});
<commit_msg>fix 'closed' observer was being set as 'closeed'<commit_after>import Ember from 'ember';
import layout from '../templates/components/ember-remodal';

const {
  inject,
  computed,
  computed: { reads },
  on,
  RSVP: { Promise },
  run: { next, scheduleOnce },
  sendEvent,
  Component
} = Ember;

export default Component.extend({
  layout,
  remodal: inject.service(),
  attributeBindings: ['dataTestId:data-test-id'],
  classNames: ['remodal-component'],
  tagName: 'span',
  name: 'modal',
  modifier: '',
  modal: null,
  options: null,
  closeOnEscape: true,
  closeOnCancel: true,
  closeOnConfirm: true,
  hashTracking: false,
  closeOnOutsideClick: true,
  forService: false,
  disableForeground: false,
  disableAnimation: false,
  disableNativeClose: reads('disableForeground'),
  erOpenButton: false,
  erCancelButton: false,
  erConfirmButton: false,

  didInitAttrs() {
    let opts = this.get('options');

    if (opts) {
      this.setProperties(opts);
    }

    if (this.get('forService')) {
      this.get('remodal').set(this.get('name'), this);
    }

    scheduleOnce('afterRender', this, '_registerObservers');
    scheduleOnce('afterRender', this, '_checkForDeprecations');
  },

  willDestroy() {
    scheduleOnce('afterRender', this, '_deregisterObservers');
  },

  modalId: computed('elementId', {
    get() {
      return `[data-remodal-id=${this.get('elementId')}]`;
    }
  }),

  animationState: computed('disableAnimation', {
    get() {
      if (this.get('disableAnimation')) {
        return 'disable-animation';
      } else {
        return '';
      }
    }
  }),

  openDidFire: on('opened', function() {
    this.sendAction('onOpen');
  }),

  closeDidFire: on('closed', function() {
    this.sendAction('onClose');
  }),

  open() {
    return this._promiseAction('open');
  },

  close() {
    return this._promiseAction('close');
  },

  _promiseAction(action) {
    let modal = this.get('modalId');
    let actionName = this._pastTense(action);

    this.send(action);

    return new Promise((resolve) => {
      Ember.$(document).one(actionName, modal, () => resolve(this));
    });
  },

  _pastTense(action) {
    if (action[action.length - 1] === 'e') {
      return `${action}d`;
    } else {
      return `${action}ed`;
    }
  },

  _registerObservers() {
    let modal = this.get('modalId');
    Ember.$(document).on('opened', modal, () => sendEvent(this, 'opened'));
    Ember.$(document).on('closed', modal, () => sendEvent(this, 'closed'));
  },

  _deregisterObservers() {
    let modal = this.get('modalId');
    Ember.$(document).off('opened', modal);
    Ember.$(document).off('closed', modal);
  },

  _createInstanceAndOpen() {
    let modal = Ember.$(this.get('modalId')).remodal({
      hashTracking: this.get('hashTracking'),
      closeOnOutsideClick: this.get('closeOnOutsideClick'),
      closeOnEscape: this.get('closeOnEscape'),
      modifier: this.get('modifier')
    });

    this.set('modal', modal);
    this.send('open');
  },

  _checkForDeprecations() {
    // Deprecations go here
  },

  _openModal() {
    this.get('modal').open();
  },

  _closeModal() {
    this.get('modal').close();
  },

  _closeOnCondition(condition) {
    this.sendAction(`on${condition}`);

    if (this.get(`closeOn${condition}`)) {
      this.send('close');
    }
  },

  actions: {
    confirm() {
      this._closeOnCondition('Confirm');
    },

    cancel() {
      this._closeOnCondition('Cancel');
    },

    open() {
      if (this.get('modal')) {
        scheduleOnce('afterRender', this, '_openModal');
      } else {
        scheduleOnce('afterRender', this, '_createInstanceAndOpen');
      }
    },

    close() {
      next(this, '_closeModal');
    }
  }
});
<|endoftext|>


<commit_before>const npmApi = require('./registry');
const versions = require('../../workers/package/versions');

module.exports = {
  getPackageUpdates,
};

async function getPackageUpdates(config) {
  let results = [];
  if (!versions.isValidVersion(config.currentVersion)) {
    results.push({
      depName: config.depName,
      type: 'warning',
      message: `Dependency uses tag "\`${
        config.currentVersion
      }\`" as its version so that will never be changed by Renovate`,
    });
    logger.debug(results[0].message);
    return results;
  }
  const npmDep = await npmApi.getDependency(config.depName);
  if (npmDep) {
    results = await versions.determineUpgrades(npmDep, config);
    if (results.length > 0) {
      logger.info(
        { dependency: config.depName },
        `${results.length} result(s): ${results.map(
          upgrade => upgrade.newVersion
        )}`
      );
    }
  } else {
    // If dependency lookup fails then warn and return
    const result = {
      type: 'warning',
      message: 'Failed to look up dependency',
    };
    if (config.yarnLock || config.packageLock) {
      result.message +=
        '. This will block *all* dependencies from being updated due to presence of lock file.';
    }
    results = [result];
    logger.info(result.message);
  }
  for (const result of results) {
    result.repositoryUrl =
      npmDep && npmDep.repositoryUrl && npmDep.repositoryUrl.length
        ? npmDep.repositoryUrl
        : null;
  }
  return results;
}
<commit_msg>refactor: log dependency name when lookups are blocking<commit_after>const npmApi = require('./registry');
const versions = require('../../workers/package/versions');

module.exports = {
  getPackageUpdates,
};

async function getPackageUpdates(config) {
  let results = [];
  if (!versions.isValidVersion(config.currentVersion)) {
    results.push({
      depName: config.depName,
      type: 'warning',
      message: `Dependency uses tag "\`${
        config.currentVersion
      }\`" as its version so that will never be changed by Renovate`,
    });
    logger.debug(results[0].message);
    return results;
  }
  const npmDep = await npmApi.getDependency(config.depName);
  if (npmDep) {
    results = await versions.determineUpgrades(npmDep, config);
    if (results.length > 0) {
      logger.info(
        { dependency: config.depName },
        `${results.length} result(s): ${results.map(
          upgrade => upgrade.newVersion
        )}`
      );
    }
  } else {
    // If dependency lookup fails then warn and return
    const result = {
      type: 'warning',
      message: 'Failed to look up dependency',
    };
    if (config.yarnLock || config.packageLock) {
      result.message +=
        '. This will block *all* dependencies from being updated due to presence of lock file.';
    }
    results = [result];
    logger.info({ dependency: config.depName }, result.message);
  }
  for (const result of results) {
    result.repositoryUrl =
      npmDep && npmDep.repositoryUrl && npmDep.repositoryUrl.length
        ? npmDep.repositoryUrl
        : null;
  }
  return results;
}
<|endoftext|>


<commit_before>/**
 * @fileOverview Error & Success handlers tests
 */
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');

var tester = require('../lib/tester.lib');

var crude = require('../../');

describe('Error and Success Handlers', function () {
  beforeEach(function () {
    this.ctrl = tester.controller();
    this.crude = crude('/test', this.ctrl);
    this.reqres = tester.reqres();
  });

  describe('Error Handler', function () {
    beforeEach(function () {
      this.err = new Error('yum');
      this.ctrl.readLimit.throws(this.err);
    });

    it('should call the built-in error handler', function () {
      var handleStub = sinon.stub(this.crude.opts, 'onError');
      return this.crude.readList(this.reqres.req, this.reqres.res)
        .bind(this)
        .then(function() {
          expect(handleStub).to.have.been.calledOnce;
          expect(handleStub.args[0][0]).to.equal(this.reqres.req);
          expect(handleStub.args[0][1]).to.equal(this.reqres.res);
          expect(handleStub.args[0][2]).to.equal('paginate');
          expect(handleStub.args[0][3]).to.equal(500);
          expect(handleStub.args[0][4]).to.equal(this.err);
          handleStub.restore();
        });
    });

    it('should call the custom error handler', function (done) {
      this.spy = sinon.mock();
      this.crude.onError(this.spy);
      return this.crude.readList(this.reqres.req, this.reqres.res)
        .bind(this)
        .then(function() {
          expect(this.spy).to.have.been.calledOnce;
          expect(this.spy).to.have.been.calledWith(this.reqres.req, this.reqres.res,
            'paginate', 500, this.err);
        }).then(done, done);
    });
  });
});
<commit_msg>expand handler test to all OPs<commit_after>/**
 * @fileOverview Error & Success handlers tests
 */
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');

var tester = require('../lib/tester.lib');

var crude = require('../../');

describe('Error and Success Handlers', function () {
  beforeEach(function () {
    this.ctrl = tester.controller();
    this.crude = crude('/test', this.ctrl);
    this.reqres = tester.reqres();
  });

  describe('Error Handler', function () {
    beforeEach(function () {
      this.err = new Error('yum');
    });
    afterEach(function () {
    });

    describe('Built-in Handler', function () {
      beforeEach(function () {
        this.handleStub = sinon.stub(this.crude.opts, 'onError');
      });
      afterEach(function () {
        this.handleStub.restore();
      });

      function runAssert(operation) {
        return function () {
          expect(this.handleStub).to.have.been.calledOnce;
          expect(this.handleStub).to.have.been.calledWith(this.reqres.req,
            this.reqres.res, operation, 500, this.err);
        };
      }

      it('should work on pagination', function (done) {
        this.ctrl.readLimit.throws(this.err);
        return this.crude.readList(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('paginate'))
          .then(done, done);

      });
      it('should work on read all', function (done) {
        this.ctrl.read.throws(this.err);
        this.crude.config({pagination: false});
        return this.crude.readList(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('read'))
          .then(done, done);
      });
      it('should work on read one', function (done) {
        this.ctrl.readOne.throws(this.err);
        return this.crude.readOne(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('readOne'))
          .then(done, done);
      });
      it('should work on update', function (done) {
        this.ctrl.readOne.throws(this.err);
        return this.crude.update(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('update'))
          .then(done, done);
      });
      it('should work on delete', function (done) {
        this.ctrl.delete.throws(this.err);
        return this.crude.delete(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('delete'))
          .then(done, done);
      });
      it('should work on create', function (done) {
        this.ctrl.create.throws(this.err);
        return this.crude.create(this.reqres.req, this.reqres.res)
          .bind(this)
          .then(runAssert('create'))
          .then(done, done);
      });

    });

    it('should call the custom error handler', function (done) {
      this.spy = sinon.spy();
      this.crude.onError(this.spy);
      return this.crude.readList(this.reqres.req, this.reqres.res)
        .bind(this)
        .then(function() {
          expect(this.spy).to.have.been.calledOnce;
          expect(this.spy).to.have.been.calledWith(this.reqres.req, this.reqres.res,
            'paginate', 500, this.err);
        }).then(done, done);
    });
  });
});
<|endoftext|>


<commit_before>define([
    '/common/rpc.js',
], function (Rpc) {
    var create = function (network, proxy, cb) {
        if (!network) {
            setTimeout(function () {
                cb('INVALID_NETWORK');
            });
            return;
        }
        if (!proxy) {
            setTimeout(function () {
                cb('INVALID_PROXY');
            });
            return;
        }

        var edPrivate = proxy.edPrivate;
        var edPublic = proxy.edPublic;

        if (!(edPrivate && edPublic)) {
            setTimeout(function () {
                cb('INVALID_KEYS');
            });
            return;
        }

        Rpc.create(network, edPrivate, edPublic, function (e, rpc) {
            if (e) { return void cb(e); }

            var exp = {};

            // expose the supplied publicKey as an identifier
            exp.publicKey = edPublic;

            // expose the RPC module's raw 'send' command
            exp.send = rpc.send;

            // you can ask the server to pin a particular channel for you
            exp.pin = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('PIN', channels, cb);
            };

            // you can also ask to unpin a particular channel
            exp.unpin = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('UNPIN', channels, cb);
            };

            // Get data for the admin panel
            exp.adminRpc = function (obj, cb) {
                if (!obj.cmd) {
                    setTimeout(function () {
                        cb('[TypeError] admin rpc expects a command');
                    });
                    return;
                }
                var params = [obj.cmd, obj.data];
                rpc.send('ADMIN', params, cb);
            };

            // ask the server what it thinks your hash is
            exp.getServerHash = function (cb) {
                rpc.send('GET_HASH', edPublic, function (e, hash) {
                    if (!(hash && hash[0])) {
                        return void cb('NO_HASH_RETURNED');
                    }
                    cb(e, hash[0]);
                });
            };

            // if local and remote hashes don't match, send a reset
            exp.reset = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('RESET', channels, function (e, response) {
                    if (e) {
                        return void cb(e);
                    }
                    if (!response.length) {
                        console.log(response);
                        return void cb('INVALID_RESPONSE');
                    }
                    cb(e, response[0]);
                });
            };

            // get the total stored size of a channel's patches (in bytes)
            exp.getFileSize = function (file, cb) {
                rpc.send('GET_FILE_SIZE', file, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === 'number') {
                        return void cb(void 0, response[0]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            // get the combined size of all channels (in bytes) for all the
            // channels which the server has pinned for your publicKey
            exp.getFileListSize = function (cb) {
                rpc.send('GET_TOTAL_SIZE', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === 'number') {
                        cb(void 0, response[0]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            // Update the limit value for all the users and return the limit for your publicKey
            exp.updatePinLimits = function (cb) {
                rpc.send('UPDATE_LIMITS', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === "number") {
                        cb (void 0, response[0], response[1], response[2]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };
            // Get the storage limit associated with your publicKey
            exp.getLimit = function (cb) {
                rpc.send('GET_LIMIT', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === "number") {
                        cb (void 0, response[0], response[1], response[2]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.clearOwnedChannel = function (channel, cb) {
                if (typeof(channel) !== 'string' || channel.length !== 32) {
                    return void cb('INVALID_ARGUMENTS');
                }
                rpc.send('CLEAR_OWNED_CHANNEL', channel, function (e) {
                    if (e) { return cb(e); }
                    cb();
                });
            };

            exp.removeOwnedChannel = function (channel, cb) {
                if (typeof(channel) !== 'string' || [32,48].indexOf(channel.length) === -1) {
                    // can't use this on files because files can't be owned...
                    return void cb('INVALID_ARGUMENTS');
                }
                rpc.send('REMOVE_OWNED_CHANNEL', channel, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && response[0] === "OK") {
                        cb();
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.removePins = function (cb) {
                rpc.send('REMOVE_PINS', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && response[0] === "OK") {
                        cb();
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.uploadComplete = function (id, cb) {
                rpc.send('UPLOAD_COMPLETE', id, function (e, res) {
                    if (e) { return void cb(e); }
                    var id = res[0];
                    if (typeof(id) !== 'string') {
                        return void cb('INVALID_ID');
                    }
                    cb(void 0, id);
                });
            };

            exp.ownedUploadComplete = function (id, cb) {
                rpc.send('OWNED_UPLOAD_COMPLETE', id, function (e, res) {
                    if (e) { return void cb(e); }
                    var id = res[0];
                    if (typeof(id) !== 'string') {
                        return void cb('INVALID_ID');
                    }
                    cb(void 0, id);
                });
            };

            exp.uploadStatus = function (size, cb) {
                if (typeof(size) !== 'number') {
                    return void setTimeout(function () {
                        cb('INVALID_SIZE');
                    });
                }
                rpc.send('UPLOAD_STATUS', size, function (e, res) {
                    if (e) { return void cb(e); }
                    var pending = res[0];
                    if (typeof(pending) !== 'boolean') {
                        return void cb('INVALID_RESPONSE');
                    }
                    cb(void 0, pending);
                });
            };

            exp.uploadCancel = function (size, cb) {
                rpc.send('UPLOAD_CANCEL', size, function (e) {
                    if (e) { return void cb(e); }
                    cb();
                });
            };

            exp.writeLoginBlock = function (data, cb) {
                if (!data) { return void cb('NO_DATA'); }
                if (!data.publicKey || !data.signature || !data.ciphertext) {
                    console.log(data);
                    return void cb("MISSING_PARAMETERS");
                }

                rpc.send('WRITE_LOGIN_BLOCK', [
                    data.publicKey,
                    data.signature,
                    data.ciphertext
                ], function (e) {
                    cb(e);
                });
            };

            exp.removeLoginBlock = function (data, cb) {
                if (!data) { return void cb('NO_DATA'); }
                if (!data.publicKey || !data.signature) {
                    console.log(data);
                    return void cb("MISSING_PARAMETERS");
                }

                rpc.send('REMOVE_LOGIN_BLOCK', [
                    data.publicKey, // publicKey
                    data.signature, // signature
                ], function (e) {
                    cb(e);
                });
            };

            // Get data for the admin panel
            exp.setMetadata = function (obj, cb) {
                rpc.send('SET_METADATA', {
                    channel: obj.channel,
                    command: obj.command,
                    value: obj.value
                }, cb);
            };

            cb(e, exp);
        });
    };

    return { create: create };
});
<commit_msg>add nodejs support to pinpad.js<commit_after>(function () {
var factory = function (Util, Rpc) {
    var create = function (network, proxy, _cb) {
        if (typeof(_cb) !== 'function') { throw new Error("Expected callback"); }
        var cb = Util.once(Util.mkAsync(_cb));

        if (!network) { return void cb('INVALID_NETWORK'); }
        if (!proxy) { return void cb('INVALID_PROXY'); }

        var edPrivate = proxy.edPrivate;
        var edPublic = proxy.edPublic;

        if (!(edPrivate && edPublic)) { return void cb('INVALID_KEYS'); }

        Rpc.create(network, edPrivate, edPublic, function (e, rpc) {
            if (e) { return void cb(e); }

            var exp = {};

            // expose the supplied publicKey as an identifier
            exp.publicKey = edPublic;

            // expose the RPC module's raw 'send' command
            exp.send = rpc.send;

            // you can ask the server to pin a particular channel for you
            exp.pin = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('PIN', channels, cb);
            };

            // you can also ask to unpin a particular channel
            exp.unpin = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('UNPIN', channels, cb);
            };

            // Get data for the admin panel
            exp.adminRpc = function (obj, cb) {
                if (!obj.cmd) {
                    setTimeout(function () {
                        cb('[TypeError] admin rpc expects a command');
                    });
                    return;
                }
                var params = [obj.cmd, obj.data];
                rpc.send('ADMIN', params, cb);
            };

            // ask the server what it thinks your hash is
            exp.getServerHash = function (cb) {
                rpc.send('GET_HASH', edPublic, function (e, hash) {
                    if (!(hash && hash[0])) {
                        return void cb('NO_HASH_RETURNED');
                    }
                    cb(e, Array.isArray(hash) && hash[0] || undefined);
                });
            };

            // if local and remote hashes don't match, send a reset
            exp.reset = function (channels, cb) {
                if (!Array.isArray(channels)) {
                    setTimeout(function () {
                        cb('[TypeError] pin expects an array');
                    });
                    return;
                }
                rpc.send('RESET', channels, function (e, response) {
                    if (e) {
                        return void cb(e);
                    }
                    if (!response.length) {
                        console.log(response);
                        return void cb('INVALID_RESPONSE');
                    }
                    cb(e, response[0]);
                });
            };

            // get the total stored size of a channel's patches (in bytes)
            exp.getFileSize = function (file, cb) {
                rpc.send('GET_FILE_SIZE', file, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === 'number') {
                        return void cb(void 0, response[0]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            // get the combined size of all channels (in bytes) for all the
            // channels which the server has pinned for your publicKey
            exp.getFileListSize = function (cb) {
                rpc.send('GET_TOTAL_SIZE', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === 'number') {
                        cb(void 0, response[0]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            // Update the limit value for all the users and return the limit for your publicKey
            exp.updatePinLimits = function (cb) {
                rpc.send('UPDATE_LIMITS', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === "number") {
                        cb (void 0, response[0], response[1], response[2]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };
            // Get the storage limit associated with your publicKey
            exp.getLimit = function (cb) {
                rpc.send('GET_LIMIT', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && typeof(response[0]) === "number") {
                        cb (void 0, response[0], response[1], response[2]);
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.clearOwnedChannel = function (channel, cb) {
                if (typeof(channel) !== 'string' || channel.length !== 32) {
                    return void cb('INVALID_ARGUMENTS');
                }
                rpc.send('CLEAR_OWNED_CHANNEL', channel, function (e) {
                    if (e) { return cb(e); }
                    cb();
                });
            };

            exp.removeOwnedChannel = function (channel, cb) {
                if (typeof(channel) !== 'string' || [32,48].indexOf(channel.length) === -1) {
                    // can't use this on files because files can't be owned...
                    return void cb('INVALID_ARGUMENTS');
                }
                rpc.send('REMOVE_OWNED_CHANNEL', channel, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && response[0] === "OK") {
                        cb();
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.removePins = function (cb) {
                rpc.send('REMOVE_PINS', undefined, function (e, response) {
                    if (e) { return void cb(e); }
                    if (response && response.length && response[0] === "OK") {
                        cb();
                    } else {
                        cb('INVALID_RESPONSE');
                    }
                });
            };

            exp.uploadComplete = function (id, cb) {
                rpc.send('UPLOAD_COMPLETE', id, function (e, res) {
                    if (e) { return void cb(e); }
                    var id = res[0];
                    if (typeof(id) !== 'string') {
                        return void cb('INVALID_ID');
                    }
                    cb(void 0, id);
                });
            };

            exp.ownedUploadComplete = function (id, cb) {
                rpc.send('OWNED_UPLOAD_COMPLETE', id, function (e, res) {
                    if (e) { return void cb(e); }
                    var id = res[0];
                    if (typeof(id) !== 'string') {
                        return void cb('INVALID_ID');
                    }
                    cb(void 0, id);
                });
            };

            exp.uploadStatus = function (size, cb) {
                if (typeof(size) !== 'number') {
                    return void setTimeout(function () {
                        cb('INVALID_SIZE');
                    });
                }
                rpc.send('UPLOAD_STATUS', size, function (e, res) {
                    if (e) { return void cb(e); }
                    var pending = res[0];
                    if (typeof(pending) !== 'boolean') {
                        return void cb('INVALID_RESPONSE');
                    }
                    cb(void 0, pending);
                });
            };

            exp.uploadCancel = function (size, cb) {
                rpc.send('UPLOAD_CANCEL', size, function (e) {
                    if (e) { return void cb(e); }
                    cb();
                });
            };

            exp.writeLoginBlock = function (data, cb) {
                if (!data) { return void cb('NO_DATA'); }
                if (!data.publicKey || !data.signature || !data.ciphertext) {
                    console.log(data);
                    return void cb("MISSING_PARAMETERS");
                }

                rpc.send('WRITE_LOGIN_BLOCK', [
                    data.publicKey,
                    data.signature,
                    data.ciphertext
                ], function (e) {
                    cb(e);
                });
            };

            exp.removeLoginBlock = function (data, cb) {
                if (!data) { return void cb('NO_DATA'); }
                if (!data.publicKey || !data.signature) {
                    console.log(data);
                    return void cb("MISSING_PARAMETERS");
                }

                rpc.send('REMOVE_LOGIN_BLOCK', [
                    data.publicKey, // publicKey
                    data.signature, // signature
                ], function (e) {
                    cb(e);
                });
            };

            // Get data for the admin panel
            exp.setMetadata = function (obj, cb) {
                rpc.send('SET_METADATA', {
                    channel: obj.channel,
                    command: obj.command,
                    value: obj.value
                }, cb);
            };

            cb(e, exp);
        });
    };

    return { create: create };
};
    if (typeof(module) !== 'undefined' && module.exports) {
        module.exports = factory(require('./common-util'), require("./rpc"));
    } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
        define([ '/common/common-util.js', '/common/rpc.js', ], function (Util, Rpc) { return factory(Util, Rpc); });
    }
}());
<|endoftext|>


<commit_before>import express from 'express';
let app = express();

import controllers from './controllers';
import middlewares from './middlewares';
// const controllers = require('./controllers');
// const middlewares = require('./middlewares');
// const errorHandlers = require('./errorHandlers');

// middlewares
app.use(middlewares(app));

// controllers
app.use(controllers(app));

// errorHandles
// app.use(errorHandlers(app));

module.exports = app;<commit_msg>debug<commit_after>let express = require('express');
let app = express();

// import controllers from './controllers';
// import middlewares from './middlewares';
const controllers = require('./controllers');
const middlewares = require('./middlewares');
// const errorHandlers = require('./errorHandlers');

// middlewares
app.use(middlewares(app));

// controllers
app.use(controllers(app));

// errorHandles
// app.use(errorHandlers(app));

module.exports = app;<|endoftext|>


<commit_before>import './styles.css'
import Inferno from 'inferno' // eslint-disable-line

function getTime (date) {
  const hours = String(date.getHours()).length === 2 ? date.getHours() : '0' + date.getHours()
  const minutes = String(date.getMinutes()).length === 2 ? date.getMinutes() : '0' + date.getMinutes()
  const seconds = String(date.getSeconds()).length === 2 ? date.getSeconds() : '0' + date.getSeconds()
  return hours + ':' + minutes + ':' + seconds
}

function extractPaths (changes) {
  if (!changes) {
    return []
  }

  return changes.reduce((paths, change) => {
    return paths.concat(change.path.join('.'))
  }, [])
}

function unique (array) {
  return array.reduce((newArray, item) => {
    if (newArray.indexOf(item) === -1) {
      return newArray.concat(item)
    }

    return newArray
  }, [])
}

export default function Renders (props) {
  return (

        {props.renders.filter((render) => {
          return props.filter ? extractPaths(render.changes).reduce((hasPath, path) => {
            return hasPath || path.indexOf(props.filter) >= 0
          }, false) : true
        }).map((render, index) => {
          const date = new Date(render.start)

          return (

                {getTime(date)} - {render.duration}ms

Paths changed

                    {extractPaths(render.changes).map((path, index) => {
                      return (

                          {path}

                      )
                    })}

Components rendered

{unique(render.components).join(', ')}

          )
        })}

  )
}
<commit_msg>Extract filter render by path function.<commit_after>import './styles.css'
import Inferno from 'inferno' // eslint-disable-line

function getTime (date) {
  const hours = String(date.getHours()).length === 2 ? date.getHours() : '0' + date.getHours()
  const minutes = String(date.getMinutes()).length === 2 ? date.getMinutes() : '0' + date.getMinutes()
  const seconds = String(date.getSeconds()).length === 2 ? date.getSeconds() : '0' + date.getSeconds()
  return hours + ':' + minutes + ':' + seconds
}

function extractPaths (changes) {
  if (!changes) {
    return []
  }

  return changes.reduce((paths, change) => {
    return paths.concat(change.path.join('.'))
  }, [])
}

function unique (array) {
  return array.reduce((newArray, item) => {
    if (newArray.indexOf(item) === -1) {
      return newArray.concat(item)
    }

    return newArray
  }, [])
}

function filterRenderByPath(pathFilter, render) {
  if (pathFilter) {
    return extractPaths(render.changes).reduce((hasPath, path) => hasPath || path.indexOf(pathFilter) >= 0, false)
  } else {
    return true
  }
}

export default function Renders (props) {
  return (

        {props.renders.filter((render) => filterRenderByPath(props.filter, render)).map((render, index) => {
          const date = new Date(render.start)

          return (

                {getTime(date)} - {render.duration}ms

Paths changed

                    {extractPaths(render.changes).map((path, index) => {
                      return (

                          {path}

                      )
                    })}

Components rendered

{unique(render.components).join(', ')}

          )
        })}

  )
}
<|endoftext|>


<commit_before>'use strict';

function classDirective(name, selector) {
  name = 'ngClass' + name;
  return ['$animate', function($animate) {
    return {
      restrict: 'AC',
      link: function(scope, element, attr) {
        var oldVal;

        scope.$watch(attr[name], ngClassWatchAction, true);

        attr.$observe('class', function(value) {
          ngClassWatchAction(scope.$eval(attr[name]));
        });

        if (name !== 'ngClass') {
          scope.$watch('$index', function($index, old$index) {
            // jshint bitwise: false
            var mod = $index & 1;
            if (mod !== (old$index & 1)) {
              var classes = arrayClasses(scope.$eval(attr[name]));
              mod === selector ?
                addClasses(classes) :
                removeClasses(classes);
            }
          });
        }

        function addClasses(classes) {
          var newClasses = digestClassCounts(classes, 1);
          attr.$addClass(newClasses);
        }

        function removeClasses(classes) {
          var newClasses = digestClassCounts(classes, -1);
          attr.$removeClass(newClasses);
        }

        function digestClassCounts(classes, count) {
          var classCounts = element.data('$classCounts') || {};
          var classesToUpdate = [];
          forEach(classes, function(className) {
            if (count > 0 || classCounts[className]) {
              classCounts[className] = (classCounts[className] || 0) + count;
              if (classCounts[className] === +(count > 0)) {
                classesToUpdate.push(className);
              }
            }
          });
          element.data('$classCounts', classCounts);
          return classesToUpdate.join(' ');
        }

        function updateClasses(oldClasses, newClasses) {
          var toAdd = arrayDifference(newClasses, oldClasses);
          var toRemove = arrayDifference(oldClasses, newClasses);
          toAdd = digestClassCounts(toAdd, 1);
          toRemove = digestClassCounts(toRemove, -1);
          if (toAdd && toAdd.length) {
            $animate.addClass(element, toAdd);
          }
          if (toRemove && toRemove.length) {
            $animate.removeClass(element, toRemove);
          }
        }

        function ngClassWatchAction(newVal) {
          if (selector === true || scope.$index % 2 === selector) {
            var newClasses = arrayClasses(newVal || []);
            if (!oldVal) {
              addClasses(newClasses);
            } else if (!equals(newVal,oldVal)) {
              var oldClasses = arrayClasses(oldVal);
              updateClasses(oldClasses, newClasses);
            }
          }
          oldVal = shallowCopy(newVal);
        }
      }
    };

    function arrayDifference(tokens1, tokens2) {
      var values = [];

      outer:
      for (var i = 0; i < tokens1.length; i++) {
        var token = tokens1[i];
        for (var j = 0; j < tokens2.length; j++) {
          if (token == tokens2[j]) continue outer;
        }
        values.push(token);
      }
      return values;
    }

    function arrayClasses(classVal) {
      if (isArray(classVal)) {
        return classVal.join(' ').split(' ');
      } else if (isString(classVal)) {
        return classVal.split(' ');
      } else if (isObject(classVal)) {
        var classes = [];
        forEach(classVal, function(v, k) {
          if (v) {
            classes = classes.concat(k.split(' '));
          }
        });
        return classes;
      }
      return classVal;
    }
  }];
}

/**
 * @ngdoc directive
 * @name ngClass
 * @restrict AC
 *
 * @description
 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
 * an expression that represents all classes to be added.
 *
 * The directive operates in three different ways, depending on which of three types the expression
 * evaluates to:
 *
 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
 * names.
 *
 * 2. If the expression evaluates to an array, each element of the array should be a string that is
 * one or more space-delimited class names.
 *
 * 3. If the expression evaluates to an object, then for each key-value pair of the
 * object with a truthy value the corresponding key is used as a class name.
 *
 * The directive won't add duplicate classes if a particular class was already set.
 *
 * When the expression changes, the previously added classes are removed and only then the
 * new classes are added.
 *
 * @animations
 * add - happens just before the class is applied to the element
 *
 * remove - happens just before the class is removed from the element
 *
 * @element ANY
 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class
 *   names, an array, or a map of class names to boolean values. In the case of a map, the
 *   names of the properties whose values are truthy will be added as css classes to the
 *   element.
 *
 * @example Example that demonstrates basic bindings via ngClass directive.
   <example>
     <file name="index.html">

Map Syntax Example

       <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)

       <input type="checkbox" ng-model="important"> important (apply "bold" class)

       <input type="checkbox" ng-model="error"> error (apply "red" class)

Using String Syntax

       <input type="text" ng-model="style" placeholder="Type: bold strike red">

Using Array Syntax

       <input ng-model="style1" placeholder="Type: bold, strike or red">

       <input ng-model="style2" placeholder="Type: bold, strike or red">

       <input ng-model="style3" placeholder="Type: bold, strike or red">

     </file>
     <file name="style.css">
       .strike {
         text-decoration: line-through;
       }
       .bold {
           font-weight: bold;
       }
       .red {
           color: red;
       }
     </file>
     <file name="protractor.js" type="protractor">
       var ps = element.all(by.css('p'));

       it('should let you toggle the class', function() {

         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
         expect(ps.first().getAttribute('class')).not.toMatch(/red/);

         element(by.model('important')).click();
         expect(ps.first().getAttribute('class')).toMatch(/bold/);

         element(by.model('error')).click();
         expect(ps.first().getAttribute('class')).toMatch(/red/);
       });

       it('should let you toggle string example', function() {
         expect(ps.get(1).getAttribute('class')).toBe('');
         element(by.model('style')).clear();
         element(by.model('style')).sendKeys('red');
         expect(ps.get(1).getAttribute('class')).toBe('red');
       });

       it('array example should have 3 classes', function() {
         expect(ps.last().getAttribute('class')).toBe('');
         element(by.model('style1')).sendKeys('bold');
         element(by.model('style2')).sendKeys('strike');
         element(by.model('style3')).sendKeys('red');
         expect(ps.last().getAttribute('class')).toBe('bold strike red');
       });
     </file>
   </example>

   ## Animations

   The example below demonstrates how to perform animations using ngClass.

   <example module="ngAnimate" deps="angular-animate.js" animations="true">
     <file name="index.html">
      <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
      <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">

      Sample Text
     </file>
     <file name="style.css">
       .base-class {
         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
       }

       .base-class.my-class {
         color: red;
         font-size:3em;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class', function() {
         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);

         element(by.id('setbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).
           toMatch(/my-class/);

         element(by.id('clearbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);
       });
     </file>
   </example>

   ## ngClass and pre-existing CSS3 Transitions/Animations
   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
   to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
   {@link ng.$animate#removeClass $animate.removeClass}.
 */
var ngClassDirective = classDirective('', true);

/**
 * @ngdoc directive
 * @name ngClassOdd
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">

             {{name}}

     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassOddDirective = classDirective('Odd', 0);

/**
 * @ngdoc directive
 * @name ngClassEven
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
 *   result of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">

             {{name}}

     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassEvenDirective = classDirective('Even', 1);
<commit_msg>docs(ngClass): fix jscs style errors<commit_after>'use strict';

function classDirective(name, selector) {
  name = 'ngClass' + name;
  return ['$animate', function($animate) {
    return {
      restrict: 'AC',
      link: function(scope, element, attr) {
        var oldVal;

        scope.$watch(attr[name], ngClassWatchAction, true);

        attr.$observe('class', function(value) {
          ngClassWatchAction(scope.$eval(attr[name]));
        });

        if (name !== 'ngClass') {
          scope.$watch('$index', function($index, old$index) {
            // jshint bitwise: false
            var mod = $index & 1;
            if (mod !== (old$index & 1)) {
              var classes = arrayClasses(scope.$eval(attr[name]));
              mod === selector ?
                addClasses(classes) :
                removeClasses(classes);
            }
          });
        }

        function addClasses(classes) {
          var newClasses = digestClassCounts(classes, 1);
          attr.$addClass(newClasses);
        }

        function removeClasses(classes) {
          var newClasses = digestClassCounts(classes, -1);
          attr.$removeClass(newClasses);
        }

        function digestClassCounts(classes, count) {
          var classCounts = element.data('$classCounts') || {};
          var classesToUpdate = [];
          forEach(classes, function(className) {
            if (count > 0 || classCounts[className]) {
              classCounts[className] = (classCounts[className] || 0) + count;
              if (classCounts[className] === +(count > 0)) {
                classesToUpdate.push(className);
              }
            }
          });
          element.data('$classCounts', classCounts);
          return classesToUpdate.join(' ');
        }

        function updateClasses(oldClasses, newClasses) {
          var toAdd = arrayDifference(newClasses, oldClasses);
          var toRemove = arrayDifference(oldClasses, newClasses);
          toAdd = digestClassCounts(toAdd, 1);
          toRemove = digestClassCounts(toRemove, -1);
          if (toAdd && toAdd.length) {
            $animate.addClass(element, toAdd);
          }
          if (toRemove && toRemove.length) {
            $animate.removeClass(element, toRemove);
          }
        }

        function ngClassWatchAction(newVal) {
          if (selector === true || scope.$index % 2 === selector) {
            var newClasses = arrayClasses(newVal || []);
            if (!oldVal) {
              addClasses(newClasses);
            } else if (!equals(newVal,oldVal)) {
              var oldClasses = arrayClasses(oldVal);
              updateClasses(oldClasses, newClasses);
            }
          }
          oldVal = shallowCopy(newVal);
        }
      }
    };

    function arrayDifference(tokens1, tokens2) {
      var values = [];

      outer:
      for (var i = 0; i < tokens1.length; i++) {
        var token = tokens1[i];
        for (var j = 0; j < tokens2.length; j++) {
          if (token == tokens2[j]) continue outer;
        }
        values.push(token);
      }
      return values;
    }

    function arrayClasses(classVal) {
      if (isArray(classVal)) {
        return classVal.join(' ').split(' ');
      } else if (isString(classVal)) {
        return classVal.split(' ');
      } else if (isObject(classVal)) {
        var classes = [];
        forEach(classVal, function(v, k) {
          if (v) {
            classes = classes.concat(k.split(' '));
          }
        });
        return classes;
      }
      return classVal;
    }
  }];
}

/**
 * @ngdoc directive
 * @name ngClass
 * @restrict AC
 *
 * @description
 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
 * an expression that represents all classes to be added.
 *
 * The directive operates in three different ways, depending on which of three types the expression
 * evaluates to:
 *
 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
 * names.
 *
 * 2. If the expression evaluates to an array, each element of the array should be a string that is
 * one or more space-delimited class names.
 *
 * 3. If the expression evaluates to an object, then for each key-value pair of the
 * object with a truthy value the corresponding key is used as a class name.
 *
 * The directive won't add duplicate classes if a particular class was already set.
 *
 * When the expression changes, the previously added classes are removed and only then the
 * new classes are added.
 *
 * @animations
 * **add** - happens just before the class is applied to the elements
 *
 * **remove** - happens just before the class is removed from the element
 *
 * @element ANY
 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class
 *   names, an array, or a map of class names to boolean values. In the case of a map, the
 *   names of the properties whose values are truthy will be added as css classes to the
 *   element.
 *
 * @example Example that demonstrates basic bindings via ngClass directive.
   <example>
     <file name="index.html">

Map Syntax Example

       <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)

       <input type="checkbox" ng-model="important"> important (apply "bold" class)

       <input type="checkbox" ng-model="error"> error (apply "red" class)

Using String Syntax

       <input type="text" ng-model="style" placeholder="Type: bold strike red">

Using Array Syntax

       <input ng-model="style1" placeholder="Type: bold, strike or red">

       <input ng-model="style2" placeholder="Type: bold, strike or red">

       <input ng-model="style3" placeholder="Type: bold, strike or red">

     </file>
     <file name="style.css">
       .strike {
         text-decoration: line-through;
       }
       .bold {
           font-weight: bold;
       }
       .red {
           color: red;
       }
     </file>
     <file name="protractor.js" type="protractor">
       var ps = element.all(by.css('p'));

       it('should let you toggle the class', function() {

         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
         expect(ps.first().getAttribute('class')).not.toMatch(/red/);

         element(by.model('important')).click();
         expect(ps.first().getAttribute('class')).toMatch(/bold/);

         element(by.model('error')).click();
         expect(ps.first().getAttribute('class')).toMatch(/red/);
       });

       it('should let you toggle string example', function() {
         expect(ps.get(1).getAttribute('class')).toBe('');
         element(by.model('style')).clear();
         element(by.model('style')).sendKeys('red');
         expect(ps.get(1).getAttribute('class')).toBe('red');
       });

       it('array example should have 3 classes', function() {
         expect(ps.last().getAttribute('class')).toBe('');
         element(by.model('style1')).sendKeys('bold');
         element(by.model('style2')).sendKeys('strike');
         element(by.model('style3')).sendKeys('red');
         expect(ps.last().getAttribute('class')).toBe('bold strike red');
       });
     </file>
   </example>

   ## Animations

   The example below demonstrates how to perform animations using ngClass.

   <example module="ngAnimate" deps="angular-animate.js" animations="true">
     <file name="index.html">
      <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
      <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">

      Sample Text
     </file>
     <file name="style.css">
       .base-class {
         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
       }

       .base-class.my-class {
         color: red;
         font-size:3em;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class', function() {
         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);

         element(by.id('setbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).
           toMatch(/my-class/);

         element(by.id('clearbtn')).click();

         expect(element(by.css('.base-class')).getAttribute('class')).not.
           toMatch(/my-class/);
       });
     </file>
   </example>

   ## ngClass and pre-existing CSS3 Transitions/Animations
   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
   to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
   {@link ng.$animate#removeClass $animate.removeClass}.
 */
var ngClassDirective = classDirective('', true);

/**
 * @ngdoc directive
 * @name ngClassOdd
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
 *   of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">

             {{name}}

     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassOddDirective = classDirective('Odd', 0);

/**
 * @ngdoc directive
 * @name ngClassEven
 * @restrict AC
 *
 * @description
 * The `ngClassOdd` and `ngClassEven` directives work exactly as
 * {@link ng.directive:ngClass ngClass}, except they work in
 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
 *
 * This directive can be applied only within the scope of an
 * {@link ng.directive:ngRepeat ngRepeat}.
 *
 * @element ANY
 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
 *   result of the evaluation can be a string representing space delimited class names or an array.
 *
 * @example
   <example>
     <file name="index.html">

             {{name}}

     </file>
     <file name="style.css">
       .odd {
         color: red;
       }
       .even {
         color: blue;
       }
     </file>
     <file name="protractor.js" type="protractor">
       it('should check ng-class-odd and ng-class-even', function() {
         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
           toMatch(/odd/);
         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
           toMatch(/even/);
       });
     </file>
   </example>
 */
var ngClassEvenDirective = classDirective('Even', 1);
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/froala-editor';
const { isFunction, proxy } = Ember.$;

export default Ember.Component.extend({
    layout: layout,

    tagName: 'div',
    _froala: null,
    params: {},
    value: null,
    eventNames: [
      'blur',
      'buttons.refresh',
      'charCounter.exceeded',
      'charCounter.update',
      'commands.after',
      'commands.before',
      'contentChanged',
      'destroy',
      'file.beforeUpload',
      'file.inserted',
      'file.unlink',
      'file.uploaded',
      'file.uploadedToS3',
      'focus',
      'html.afterGet',
      'html.beforeGet',
      'html.get',
      'html.set',
      'image.beforePasteUpload',
      'image.beforeRemove',
      'image.beforeUpload',
      'image.error',
      'image.inserted',
      'image.loaded',
      'image.removed',
      'image.replaced',
      'image.resize',
      'image.resizeEnd',
      'image.uploaded',
      'image.uploadedToS3',
      'imageManager.beforeDeleteImage',
      'imageManager.error',
      'imageManager.imageDeleted',
      'imageManager.imageLoaded',
      'imageManager.imagesLoaded',
      'initialized',
      'link.bad',
      'paste.after',
      'paste.afterCleanup',
      'paste.before',
      'paste.beforeCleanup',
      'popups.hide.[id]',
      'save.after',
      'save.before',
      'save.error',
      'snapshot.after',
      'snapshot.before',
      'toolbar.hide',
      'toolbar.show',
      'video.codeError',
      'video.inserted',
      'video.linkError',
      'video.removed',
      'video.beforeRemove'
    ],

    didInsertElement: function() {
        var froala = this.$().froalaEditor(this.get('params')),
            events = this.get('eventNames');

        const froalaElement = this.$();
        froalaElement.froalaEditor('html.set', this.get('value') || '', false);

        events.forEach((key) => {
          if(this.attrs[key]) {
            froalaElement.on('froalaEditor.' + key, proxy(this.handleFroalaEvent, this));
          }
        });

        this.set('_froala', froala);
    },

    handleFroalaEvent: function(event, editor) {
      const eventName = event.namespace;
      const actionHandler = this.attrs[eventName];
      if(isFunction(actionHandler)) {
        actionHandler(event, editor);
      } else {
        this.sendAction(eventName, event, editor);
      }
    },

    willDestroyElement: function() {
        if (this.get('_froala')) {
            this.$().froalaEditor('destroy');
        }
    }
});

<commit_msg>Update froala-editor.js<commit_after>import Ember from 'ember';
import layout from '../templates/components/froala-editor';
const { isFunction, proxy } = Ember.$;

export default Ember.Component.extend({
    layout: layout,

    tagName: 'div',
    _froala: null,
    params: {},
    value: null,
    eventNames: [
      {'blur':'blur'},
      {'buttonsRefresh':'buttons.refresh'},
      {'charCounterExceeded':'charCounter.exceeded'},
      {'charCounterUpdate':'charCounter.update'},
      {'commandsAfter':'commands.after'},
      {'commandsBefore':'commands.before'},
      {'contentChanged':'contentChanged'},
      {'destroy':'destroy'},
      {'fileBeforeUpload':'file.beforeUpload'},
      {'fileInserted':'file.inserted'},
      {'fileUnlink':'file.unlink'},
      {'fileUploaded':'file.uploaded'},
      {'fileUploadedToS3':'file.uploadedToS3'},
      {'focus':'focus'},
      {'htmlAfterGet':'html.afterGet'},
      {'htmlBeforeGet':'html.beforeGet'},
      {'htmlGet':'html.get'},
      {'htmlSet':'html.set'},
      {'imageBeforePasteUpload':'image.beforePasteUpload'},
      {'imageBeforeRemove':'image.beforeRemove'},
      {'imageBeforeUpload':'image.beforeUpload'},
      {'imageError':'image.error'},
      {'imageInserted':'image.inserted'},
      {'imageLoaded':'image.loaded'},
      {'imageRemoved':'image.removed'},
      {'imageReplaced':'image.replaced'},
      {'imageResize':'image.resize'},
      {'imageResizeEnd':'image.resizeEnd'},
      {'imageUploaded':'image.uploaded'},
      {'imageUploadedToS3':'image.uploadedToS3'},
      {'imageManagerBeforeDeleteImage':'imageManager.beforeDeleteImage'},
      {'imageManagerError':'imageManager.error'},
      {'imageManagerImageDeleted':'imageManager.imageDeleted'},
      {'imageManagerImageLoaded':'imageManager.imageLoaded'},
      {'imageManagerImagesLoaded':'imageManager.imagesLoaded'},
      {'initialized':'initialized'},
      {'linkBad':'link.bad'},
      {'pasteAfter':'paste.after'},
      {'pasteAfterCleanup':'paste.afterCleanup'},
      {'pasteBefore':'paste.before'},
      {'pasteBeforeCleanup':'paste.beforeCleanup'},
      {'popupsHide_[key]':'popups.hide.[id]'},//need to be a dynamic property
      {'saveAfter':'save.after'},
      {'saveBefore':'save.before'},
      {'saveError':'save.error'},
      {'snapshotAfter':'snapshot.after'},
      {'snapshotBefore':'snapshot.before'},
      {'toolbarHide':'toolbar.hide'},
      {'toolbarShow':'toolbar.show'},
      {'videoCodeError':'video.codeError'},
      {'videoInserted':'video.inserted'},
      {'videoLinkError':'video.linkError'},
      {'videoRemoved':'video.removed'},
      {'videoBeforeRemove':'video.beforeRemove'}
    ],

    didInsertElement: function() {
        var froala = this.$().froalaEditor(this.get('params')),
            events = this.get('eventNames');

        const froalaElement = this.$();
        froalaElement.froalaEditor('html.set', this.get('value') || '', false);

        events.forEach((key) => {
          for(var option in key){
            if(this.attrs[option]) {
              froalaElement.on('froalaEditor.' + key[option], proxy(this.handleFroalaEvent, this));
            }
          }
        });

        this.set('_froala', froala);
    },

    handleFroalaEvent: function(event, editor) {
      var events = this.get('eventNames');
      const eventName = event.namespace;
      events.forEach((key) => {
        for(var option in key){
          if(this.attrs[option]) {
            if(eventName===key[option]){
              const actionHandler = this.attrs[option];
              if(isFunction(actionHandler)) {
                actionHandler(event, editor);
              } else {
                this.sendAction(option, event, editor);
              }
            }
          }
        }
      });
    },

    willDestroyElement: function() {
        if (this.get('_froala')) {
            this.$().froalaEditor('destroy');
        }
    }
});

<|endoftext|>