<commit_before>define(['jquery', 'bootstrap'], function ($, _) {
    return function (element, settings) {

        var output = this,
            $outputElement = $(element),
            nextMessageNewEntry = true,
            $previousEntryElement = null,
            previousText = null,
            lineNumber = 1;

        function initialize () {
            settings.getProperty('useWrapMode').bindAction('change', function (value) {
                $outputElement.toggleClass('wrap_lines', value);
            });
        }

        this.addListener = function (eventName, fn) {
            $(output).on(eventName, function (event, args) {
                fn.apply(undefined, args);
            });
        };

        function trigger (eventName, data) {
            var args = Array.prototype.slice.call(arguments).slice(1);
            $(output).trigger(eventName, [args]);
        }

        /**
         * Add an item to the output.
         * @param {string} text
         * @param {object=} metadata
         */
        this.add = function (text, metadata) {
            // Ensure metadata is complete, make a copy for internal use.
            metadata = $.extend({}, metadata); // Supports metadata argument not given (undefined).
            metadata.type = metadata.type || 'other';

            // Identical messages: Skip but increase the counter.
            if (!/input|result/.test(metadata.type) &&
                    nextMessageNewEntry &&
                    text !== '\n' &&
                    text === previousText) {
                increaseCounter($previousEntryElement);
                return;
            }

            // Empty line after puts: Skip and remember to put next message on new entry.
            //
            // Unfortunately SketchUp's stdout and stderr have only one `write` method
            // that prints inline text. To produce new lines (like with `puts`), it sends
            // a single line break afterwards. In that case we receive a `print` with '\n'
            // and later a `print` with the next message (puts or error).
            // So we absorb the line break and let the next message start in a new line.
            if (text === '\n' && /print|error/.test(metadata.type)) {
                // This case actually means "puts follows" or "error follows"
                nextMessageNewEntry = true;
                return;
            }

            // Real print: attach to previous row.
            if (/print/.test(metadata.type) && !nextMessageNewEntry) {
                if (nextMessageNewEntry) {
                    // Previous message required a new row (input, result, error)
                    createNewEntry(text, metadata);
                    previousText = text;
                } else {
                    attachToPreviousEntry(text);
                    previousText += text;
                }
                nextMessageNewEntry = false;
            } else {
                // input, result, puts, warn, error
                createNewEntry(text, metadata);
                previousText = text;
                nextMessageNewEntry = true;
            }
        };

        /**
         * Clears the output.
         */
        this.clear = function () {
            $outputElement.empty();
        };

        /**
         * Insert text to the previous entry.
         * @param {string} text
         * @private
         */
        var attachToPreviousEntry = function (text) {
            $previousEntryElement.append(text);
            // Add line number
            $('.gutter', $previousEntryElement).append(
                $('<div>').text(lineNumber++).addClass('ace_gutter-cell unselectable')
            );
        };

        /**
         * Creates a new entry.
         * @param {string} text
         * @param {object=} data
         * @private
         */
        var createNewEntry = function (text, data) {
            if (typeof text !== 'string') return;
            data.text = text;

            var $entryElement = $('<div>')
            .addClass('message')
            .addClass(data.type)
            //.addClass('ace_scroller ace_text-layer'); // Tweaks for ace. // TODO: Verify that ace_scroller is not
            // needed, it causes ugly drop shadow in ambiance theme.
            .addClass('ace_text-layer'); // Tweaks for ace.

            // Add gutter on the left side to continue the editor's gutter and for message type icons.
            var $gutter = $('<div>')
            .addClass('gutter')
            .addClass('ace_gutter ace_layer ace_gutter-layer ace_folding-enabled'); // Tweaks to style it like ace.
            $entryElement.append($gutter);
            // Add line numbers
            if (/input/.test(data.type)) {
                var lineNumber = data.line_number || 1;
                var lineEnd = lineNumber + text.split(/\r\n|\r|\n/).length;
                for (; lineNumber <= lineEnd; lineNumber++) {
                    $gutter.append(
                        $('<div>').addClass('ace_gutter-cell unselectable').attr('data-text', lineNumber)
                    );
                }
            }

            // Hook for raw text.
            trigger('beforeadded', data);

            // Input / result as highlighted code.
            if (/input|result/.test(data.type)) {
                addCode($entryElement, data);

            // Error details.
            } else if (/error|warn/.test(data.type)) {
                addError($entryElement, data);
                // TODO: if error was in console input, find the input entryElement and highlight the error.

            // Puts / print as text.
            } else { // if (/puts|print/.test(metadata.type))
                addText($entryElement, data);
            }

            // Add counter to combine repeated entries.
            if (!/input|result/.test(data.type)) {
                addCounter($entryElement);
            }

            // Add time stamp.
            addTimeStamp($entryElement, data.time);

            $outputElement.append($entryElement);
            // Hook for div added to output.
            trigger('added', $entryElement[0], text, data);
            $previousEntryElement = $entryElement;
        };

        function addCounter ($entryElement) {
            $('<div>')
            .addClass('counter unselectable')
            .appendTo($entryElement)
            .hide();
        }

        function increaseCounter ($entryElement) {
            var $counter = $entryElement.find('.counter').show();
            var count = parseInt($counter.attr('data-text')) || 1;
            $counter.attr('data-text', count + 1);
        }

        function addTimeStamp ($entryElement, time) {
            $('<div>')
            .addClass('time unselectable')
            .attr('data-text', formatTime(time))
            .appendTo($entryElement);
        }

        function addCode ($entryElement, data) {
            if (typeof output.highlight !== 'function')
                return addText($entryElement, data);
            data.html = output.highlight(data.text);
            $('<code>')
            .addClass('content')
            .html(data.html)
            .appendTo($entryElement);
        }

        function addText ($entryElement, data) {
            $('<code>')
            .addClass('content')
            .text(data.text)
            .appendTo($entryElement);
        }

        function addError ($entryElement, data) {
            var $panel = $('<div>')
            .addClass('content')
            .appendTo($entryElement);

            var $header = $('<div>')
            .text(data.text)
            .addClass('header')
            .appendTo($panel);

            if (data.backtrace) {
                var $content = $('<div>')
                .addClass('backtrace')
                .addClass('collapse')
                .collapse({toggle: false})
                .appendTo($panel);
                $header.on('click', function () {  $(this).next().collapse('toggle'); });

                // Collapse long backtrace.
                $.each(data.backtrace, function (index, trace) {
                    // TODO: make file paths links that open in editor with line number; if file exists (open successful)
                    var fullpath = trace.replace(/\:\d+(?:\:.+)?$/, ''); // Removes the line number suffix from the trace.
                    if (data.backtrace_short) trace = data.backtrace_short[index];

                    var $trace = $('<div>')
                    .attr('title', fullpath)
                    .text(trace)
                    .appendTo($content);
                });
            }
        }

        // Format the time as a string (not including the date).
        // @overload formatTime(date)
        //   @param date {Date} a date object
        //   @returns {string}
        // @overload formatTime(time)
        //   @param time {number} time in seconds
        //   @returns {string}
        function formatTime (time) {
            var d = (time instanceof Date) ? time :
                    (typeof time === 'number') ? new Date(time * 1000) : // JavaScript Date takes milliseconds
                    new Date();
            return stringRjust(d.getHours(),     2, '0') + ':' +
                stringRjust(d.getMinutes(),      2, '0') + ':' +
                stringRjust(d.getSeconds(),      2, '0') + '.' +
                stringRjust(d.getMilliseconds(), 3, '0');
        }

        /**
         * Repeat a string a given number of times.
         * @param   {string} string
         * @param   {number} times   an integer
         * @returns {string} the modified string
         */
        function stringRepeat (string, times) {
            var newString = '';
            for (var i = 0; i < times; i++) {
                newString += string;
            }
            return newString;
        }

        /**
         * Fill up a string to a new width so that the original string is aligned at the right.
         * @param   {string}  string
         * @param   {number}  width     an integer
         * @param   {string} [padding]  a single character to be used as padding, defaults to a whitespace.
         * @returns {string} the modified string
         */
        function stringRjust (string, width, padding) {
            if (typeof string !== 'string') string = String(string);
            padding = padding || ' ';
            padding = padding.substr(0, 1);
            if (string.length < width) {
                return stringRepeat(padding, width - string.length) + string;
            } else {
                return string;
            }
        }

        initialize();
    };
});
<commit_msg>Do not create backtrace panel for empty backtrace.<commit_after>define(['jquery', 'bootstrap'], function ($, _) {
    return function (element, settings) {

        var output = this,
            $outputElement = $(element),
            nextMessageNewEntry = true,
            $previousEntryElement = null,
            previousText = null,
            lineNumber = 1;

        function initialize () {
            settings.getProperty('useWrapMode').bindAction('change', function (value) {
                $outputElement.toggleClass('wrap_lines', value);
            });
        }

        this.addListener = function (eventName, fn) {
            $(output).on(eventName, function (event, args) {
                fn.apply(undefined, args);
            });
        };

        function trigger (eventName, data) {
            var args = Array.prototype.slice.call(arguments).slice(1);
            $(output).trigger(eventName, [args]);
        }

        /**
         * Add an item to the output.
         * @param {string} text
         * @param {object=} metadata
         */
        this.add = function (text, metadata) {
            // Ensure metadata is complete, make a copy for internal use.
            metadata = $.extend({}, metadata); // Supports metadata argument not given (undefined).
            metadata.type = metadata.type || 'other';

            // Identical messages: Skip but increase the counter.
            if (!/input|result/.test(metadata.type) &&
                    nextMessageNewEntry &&
                    text !== '\n' &&
                    text === previousText) {
                increaseCounter($previousEntryElement);
                return;
            }

            // Empty line after puts: Skip and remember to put next message on new entry.
            //
            // Unfortunately SketchUp's stdout and stderr have only one `write` method
            // that prints inline text. To produce new lines (like with `puts`), it sends
            // a single line break afterwards. In that case we receive a `print` with '\n'
            // and later a `print` with the next message (puts or error).
            // So we absorb the line break and let the next message start in a new line.
            if (text === '\n' && /print|error/.test(metadata.type)) {
                // This case actually means "puts follows" or "error follows"
                nextMessageNewEntry = true;
                return;
            }

            // Real print: attach to previous row.
            if (/print/.test(metadata.type) && !nextMessageNewEntry) {
                if (nextMessageNewEntry) {
                    // Previous message required a new row (input, result, error)
                    createNewEntry(text, metadata);
                    previousText = text;
                } else {
                    attachToPreviousEntry(text);
                    previousText += text;
                }
                nextMessageNewEntry = false;
            } else {
                // input, result, puts, warn, error
                createNewEntry(text, metadata);
                previousText = text;
                nextMessageNewEntry = true;
            }
        };

        /**
         * Clears the output.
         */
        this.clear = function () {
            $outputElement.empty();
        };

        /**
         * Insert text to the previous entry.
         * @param {string} text
         * @private
         */
        var attachToPreviousEntry = function (text) {
            $previousEntryElement.append(text);
            // Add line number
            $('.gutter', $previousEntryElement).append(
                $('<div>').text(lineNumber++).addClass('ace_gutter-cell unselectable')
            );
        };

        /**
         * Creates a new entry.
         * @param {string} text
         * @param {object=} data
         * @private
         */
        var createNewEntry = function (text, data) {
            if (typeof text !== 'string') return;
            data.text = text;

            var $entryElement = $('<div>')
            .addClass('message')
            .addClass(data.type)
            //.addClass('ace_scroller ace_text-layer'); // Tweaks for ace. // TODO: Verify that ace_scroller is not
            // needed, it causes ugly drop shadow in ambiance theme.
            .addClass('ace_text-layer'); // Tweaks for ace.

            // Add gutter on the left side to continue the editor's gutter and for message type icons.
            var $gutter = $('<div>')
            .addClass('gutter')
            .addClass('ace_gutter ace_layer ace_gutter-layer ace_folding-enabled'); // Tweaks to style it like ace.
            $entryElement.append($gutter);
            // Add line numbers
            if (/input/.test(data.type)) {
                var lineNumber = data.line_number || 1;
                var lineEnd = lineNumber + text.split(/\r\n|\r|\n/).length;
                for (; lineNumber <= lineEnd; lineNumber++) {
                    $gutter.append(
                        $('<div>').addClass('ace_gutter-cell unselectable').attr('data-text', lineNumber)
                    );
                }
            }

            // Hook for raw text.
            trigger('beforeadded', data);

            // Input / result as highlighted code.
            if (/input|result/.test(data.type)) {
                addCode($entryElement, data);

            // Error details.
            } else if (/error|warn/.test(data.type)) {
                addError($entryElement, data);
                // TODO: if error was in console input, find the input entryElement and highlight the error.

            // Puts / print as text.
            } else { // if (/puts|print/.test(metadata.type))
                addText($entryElement, data);
            }

            // Add counter to combine repeated entries.
            if (!/input|result/.test(data.type)) {
                addCounter($entryElement);
            }

            // Add time stamp.
            addTimeStamp($entryElement, data.time);

            $outputElement.append($entryElement);
            // Hook for div added to output.
            trigger('added', $entryElement[0], text, data);
            $previousEntryElement = $entryElement;
        };

        function addCounter ($entryElement) {
            $('<div>')
            .addClass('counter unselectable')
            .appendTo($entryElement)
            .hide();
        }

        function increaseCounter ($entryElement) {
            var $counter = $entryElement.find('.counter').show();
            var count = parseInt($counter.attr('data-text')) || 1;
            $counter.attr('data-text', count + 1);
        }

        function addTimeStamp ($entryElement, time) {
            $('<div>')
            .addClass('time unselectable')
            .attr('data-text', formatTime(time))
            .appendTo($entryElement);
        }

        function addCode ($entryElement, data) {
            if (typeof output.highlight !== 'function')
                return addText($entryElement, data);
            data.html = output.highlight(data.text);
            $('<code>')
            .addClass('content')
            .html(data.html)
            .appendTo($entryElement);
        }

        function addText ($entryElement, data) {
            $('<code>')
            .addClass('content')
            .text(data.text)
            .appendTo($entryElement);
        }

        function addError ($entryElement, data) {
            var $panel = $('<div>')
            .addClass('content')
            .appendTo($entryElement);

            var $header = $('<div>')
            .text(data.text)
            .addClass('header')
            .appendTo($panel);

            if (data.backtrace && data.backtrace.length > 0) {
                var $content = $('<div>')
                .addClass('backtrace')
                .addClass('collapse')
                .collapse({toggle: false})
                .appendTo($panel);
                $header.on('click', function () {  $(this).next().collapse('toggle'); });

                // Collapse long backtrace.
                $.each(data.backtrace, function (index, trace) {
                    // TODO: make file paths links that open in editor with line number; if file exists (open successful)
                    var fullpath = trace.replace(/\:\d+(?:\:.+)?$/, ''); // Removes the line number suffix from the trace.
                    if (data.backtrace_short) trace = data.backtrace_short[index];

                    var $trace = $('<div>')
                    .attr('title', fullpath)
                    .text(trace)
                    .appendTo($content);
                });
            }
        }

        // Format the time as a string (not including the date).
        // @overload formatTime(date)
        //   @param date {Date} a date object
        //   @returns {string}
        // @overload formatTime(time)
        //   @param time {number} time in seconds
        //   @returns {string}
        function formatTime (time) {
            var d = (time instanceof Date) ? time :
                    (typeof time === 'number') ? new Date(time * 1000) : // JavaScript Date takes milliseconds
                    new Date();
            return stringRjust(d.getHours(),     2, '0') + ':' +
                stringRjust(d.getMinutes(),      2, '0') + ':' +
                stringRjust(d.getSeconds(),      2, '0') + '.' +
                stringRjust(d.getMilliseconds(), 3, '0');
        }

        /**
         * Repeat a string a given number of times.
         * @param   {string} string
         * @param   {number} times   an integer
         * @returns {string} the modified string
         */
        function stringRepeat (string, times) {
            var newString = '';
            for (var i = 0; i < times; i++) {
                newString += string;
            }
            return newString;
        }

        /**
         * Fill up a string to a new width so that the original string is aligned at the right.
         * @param   {string}  string
         * @param   {number}  width     an integer
         * @param   {string} [padding]  a single character to be used as padding, defaults to a whitespace.
         * @returns {string} the modified string
         */
        function stringRjust (string, width, padding) {
            if (typeof string !== 'string') string = String(string);
            padding = padding || ' ';
            padding = padding.substr(0, 1);
            if (string.length < width) {
                return stringRepeat(padding, width - string.length) + string;
            } else {
                return string;
            }
        }

        initialize();
    };
});
<|endoftext|>


<commit_before>'use strict';

import Base from './base.js';

var fs = require('fs');
var path = require('path');

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    let videos = await this.model('video').limit(10).select();

    return this.success({
      videoList: videos
    });

  }

  async uploadAction(){
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('video'));
	let title = this.post('title');
    let create_time = this.post('create_time');
    let longitude = this.post('longitude');
    let latitude = this.post('latitude');
    let address = this.post('address');
    let creator_photo = this.post('creator_photo');
    let creator_name = this.post('creator_name');
    let creator_gender = this.post('creator_gender');
	console.log(create_time);

    var filepath = file.path;
	console.log(file);
	console.log(filepath);

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var uploadPath = think.RESOURCE_PATH + '/static';
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);

    file.path = uploadPath + '/' + basename;

    if(think.isFile(file.path)){
      console.log('is file')
    }else{
      console.log('not exist')
    }

    this.assign('fileInfo', file);
	console.log(file.path);

	var fileUrl = "http://47.93.241.248/static/" + basename;

	let user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	if (think.isEmpty(user)) {
	    let userResult = await this.model('user').add({
            gender: creator_gender,
            account: 'Wx'+creator_name,
            name: creator_name,
            photo_url: creator_photo,
            reg_time: parseInt(new Date().getTime() / 1000)
        });
	    console.log(userResult);
		user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	}

	let news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	if (think.isEmpty(news)) {
	    let newsResult = await this.model('news').add({
            title: title,
            create_time: create_time,
            longitude: longitude,
            latitude: latitude,
            location: address
        });
	    console.log(newsResult);
		news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	}

	let videoResult = await this.model('user').add({
        creator: user[0].id,
		title: title,
        news_id: news[0].id,
        create_time: create_time,
        longitude: longitude,
        latitude: latitude,
		poster_url: '',
        video_url: fileUrl
    });
	console.log(videoResult);

    this.display();
  }
}<commit_msg>Testt<commit_after>'use strict';

import Base from './base.js';

var fs = require('fs');
var path = require('path');

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    let videos = await this.model('video').limit(10).select();

    return this.success({
      videoList: videos
    });

  }

  async uploadAction(){
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('video'));
	let title = this.post('title');
    let create_time = this.post('create_time');
    let longitude = this.post('longitude');
    let latitude = this.post('latitude');
    let address = this.post('address');
    let creator_photo = this.post('creator_photo');
    let creator_name = this.post('creator_name');
    let creator_gender = this.post('creator_gender');
	console.log(create_time);

    var filepath = file.path;
	console.log(file);
	console.log(filepath);

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var uploadPath = think.RESOURCE_PATH + '/static';
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);

    file.path = uploadPath + '/' + basename;

    if(think.isFile(file.path)){
      console.log('is file')
    }else{
      console.log('not exist')
    }

    this.assign('fileInfo', file);
	console.log(file.path);

	var fileUrl = "http://47.93.241.248/static/" + basename;
	console.log(fileUrl);

	let user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	if (think.isEmpty(user)) {
	    let userResult = await this.model('user').add({
            gender: creator_gender,
            account: 'Wx'+creator_name,
            name: creator_name,
            photo_url: creator_photo,
            reg_time: parseInt(new Date().getTime() / 1000)
        });
	    console.log(userResult);
		user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	}
	console.log(user);

	let news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	if (think.isEmpty(news)) {
	    let newsResult = await this.model('news').add({
            title: title,
            create_time: create_time,
            longitude: longitude,
            latitude: latitude,
            location: address
        });
	    console.log(newsResult);
		news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	}
	console.log(news);

	let videoResult = await this.model('user').add({
        creator: user.id,
		title: title,
        news_id: news.id,
        create_time: create_time,
        longitude: longitude,
        latitude: latitude,
		poster_url: 'https://tva3.sinaimg.cn/crop.0.0.1125.1125.180/cc981db8jw8f1oifzwvxqj20v90v941q.jpg',
        video_url: fileUrl
    });
	console.log(videoResult);

    this.display();
  }
}<|endoftext|>


<commit_before>'use strict';

import Base from './base.js';

var fs = require('fs');
var path = require('path');

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    let videos = await this.model('video').limit(10).select();

    return this.success({
      videoList: videos
    });

  }

  async uploadAction(){
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('video'));
	let title = this.post('title');
    let create_time = this.post('create_time');
    let longitude = this.post('longitude');
    let latitude = this.post('latitude');
    let address = this.post('address');
    let creator_photo = this.post('creator_photo');
    let creator_name = this.post('creator_name');
    let creator_gender = this.post('creator_gender');
	console.log(create_time);

    var filepath = file.path;
	console.log(file);
	console.log(filepath);

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var uploadPath = think.RESOURCE_PATH + '/static';
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);

    file.path = uploadPath + '/' + basename;

    if(think.isFile(file.path)){
      console.log('is file')
    }else{
      console.log('not exist')
    }

    this.assign('fileInfo', file);
	console.log(file.path);

	var fileUrl = "http://47.93.241.248/static/" + basename;
	console.log(fileUrl);

	let user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	if (think.isEmpty(user)) {
	    let userResult = await this.model('user').add({
            gender: creator_gender,
            account: 'Wx'+creator_name,
            name: creator_name,
            photo_url: creator_photo,
            reg_time: parseInt(new Date().getTime() / 1000)
        });
	    console.log(userResult);
		user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	}
	console.log(user);

	let news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	if (think.isEmpty(news)) {
	    let newsResult = await this.model('news').add({
            title: title,
            create_time: create_time,
            longitude: longitude,
            latitude: latitude,
            location: address
        });
	    console.log(newsResult);
		news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	}
	console.log(news);

	let videoResult = await this.model('user').add({
        creator: user.id,
		title: title,
        news_id: news.id,
        create_time: create_time,
        longitude: longitude,
        latitude: latitude,
		poster_url: 'https://tva3.sinaimg.cn/crop.0.0.1125.1125.180/cc981db8jw8f1oifzwvxqj20v90v941q.jpg',
        video_url: fileUrl
    });
	console.log(videoResult);

    this.display();
  }
}<commit_msg>Test<commit_after>'use strict';

import Base from './base.js';

var fs = require('fs');
var path = require('path');

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    let videos = await this.model('video').limit(10).select();

    return this.success({
      videoList: videos
    });

  }

  async uploadAction(){
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('video'));
	let title = this.post('title');
    let create_time = this.post('create_time');
    let longitude = this.post('longitude');
    let latitude = this.post('latitude');
    let address = this.post('address');
    let creator_photo = this.post('creator_photo');
    let creator_name = this.post('creator_name');
    let creator_gender = this.post('creator_gender');
	console.log(create_time);

    var filepath = file.path;
	//console.log(file);
	console.log(filepath);

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var uploadPath = think.RESOURCE_PATH + '/static';
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);

    file.path = uploadPath + '/' + basename;

    if(think.isFile(file.path)){
      console.log('is file')
    }else{
      console.log('not exist')
    }

    this.assign('fileInfo', file);
	console.log(file.path);

	var fileUrl = "http://47.93.241.248/static/" + basename;
	console.log(fileUrl);

	let user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	if (think.isEmpty(user)) {
	    let userResult = await this.model('user').add({
            gender: creator_gender,
            account: 'Wx'+creator_name,
            name: creator_name,
            photo_url: creator_photo,
            reg_time: parseInt(new Date().getTime() / 1000)
        });
	    console.log(userResult);
		user = await this.model('user').where({photo_url: creator_photo, name: creator_name}).find();
	}
	//console.log(user);

	let news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	if (think.isEmpty(news)) {
	    let newsResult = await this.model('news').add({
            title: title,
            create_time: create_time,
            longitude: longitude,
            latitude: latitude,
            location: address
        });
	    console.log(newsResult);
		news = await this.model('news').where({latitude: latitude, longitude: longitude}).find();
	}
	//console.log(news);

	let videoResult = await this.model('video').add({
        creator: user.id,
        title: title,
        news_id: news.id,
        create_time: create_time,
		upload_time: parseInt(new Date().getTime() / 1000),
        longitude: longitude,
        latitude: latitude,
		poster_url: 'https://dslb.cdn.krcom.cn/stream/zpUlK5EVJiDJIIrS1kfdgfIVaa4mkEuSjE6sZQ___32768.jpg',
        video_url: fileUrl
    });
	console.log(videoResult);

    this.display();
  }
}<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash');
const async = require('async');
const utils = require('./utils');
const parseOrderbookOrder = require('./parse/orderbook-order');
const validate = utils.common.validate;
const composeAsync = utils.common.composeAsync;

// account is to specify a "perspective", which affects which unfunded offers
// are returned
function getBookOffers(remote, account, ledgerVersion, limit,
    takerGets, takerPays, callback) {
  remote.requestBookOffers(utils.renameCounterpartyToIssuerInOrder({
    taker_gets: takerGets,
    taker_pays: takerPays,
    ledger: ledgerVersion || 'validated',
    limit: limit,
    taker: account
  }), composeAsync((data) => data.offers.map(parseOrderbookOrder), callback));
}

function isSameIssue(a, b) {
  return a.currency === b.currency && a.counterparty === b.counterparty;
}

function orderFilter(issue, direction, order) {
  return isSameIssue(issue, order.specification.quantity)
    && order.specification.direction === direction;
}

function formatBidsAndAsks(orderbook, orders) {
  // the "base" currency is the currency that you are buying or selling
  // the "counter" is the currency that the "base" is priced in
  // a "bid"/"ask" is an order to buy/sell the base, respectively
  const bids = orders.filter(_.partial(orderFilter, orderbook.base, 'buy'));
  const asks = orders.filter(_.partial(orderFilter, orderbook.base, 'sell'));
  return {bids, asks};
}

function getOrderBook(account, orderbook, options, callback) {
  validate.address(account);
  validate.orderbook(orderbook);
  validate.options(options);

  const getter = _.partial(getBookOffers, this.remote, account,
    options.ledgerVersion, options.limit);
  const getOrders = _.partial(getter, orderbook.base, orderbook.counter);
  const getReverseOrders = _.partial(getter, orderbook.counter, orderbook.base);
  async.parallel([getOrders, getReverseOrders],
    composeAsync((data) => formatBidsAndAsks(orderbook, _.flatten(data)),
                 callback));
}

module.exports = utils.wrapCatch(getOrderBook);
<commit_msg>Sort orderbook orders by price<commit_after>'use strict';
const _ = require('lodash');
const async = require('async');
const utils = require('./utils');
const parseOrderbookOrder = require('./parse/orderbook-order');
const validate = utils.common.validate;
const composeAsync = utils.common.composeAsync;

// account is to specify a "perspective", which affects which unfunded offers
// are returned
function getBookOffers(remote, account, ledgerVersion, limit,
    takerGets, takerPays, callback) {
  remote.requestBookOffers(utils.renameCounterpartyToIssuerInOrder({
    taker_gets: takerGets,
    taker_pays: takerPays,
    ledger: ledgerVersion || 'validated',
    limit: limit,
    taker: account
  }), composeAsync(data => data.offers, callback));
}

function isSameIssue(a, b) {
  return a.currency === b.currency && a.counterparty === b.counterparty;
}

function orderFilter(issue, direction, order) {
  return isSameIssue(issue, order.specification.quantity)
    && order.specification.direction === direction;
}

function formatBidsAndAsks(orderbook, offers) {
  // the "base" currency is the currency that you are buying or selling
  // the "counter" is the currency that the "base" is priced in
  // a "bid"/"ask" is an order to buy/sell the base, respectively
  // for bids: takerGets = totalPrice = counter, takerPays = quantity = base
  // for asks: takerGets = quantity = base, takerPays = totalPrice = counter
  // quality = takerPays / takerGets; price = totalPrice / quantity
  // for bids: lowest quality => lowest quantity/totalPrice => highest price
  // for asks: lowest quality => lowest totalPrice/quantity => lowest price
  // for both bids and asks, lowest quality is closest to mid-market
  // we sort the orders so that earlier orders are closer to mid-market
  const orders = _.sortBy(offers, 'quality').map(parseOrderbookOrder);
  const bids = orders.filter(_.partial(orderFilter, orderbook.base, 'buy'));
  const asks = orders.filter(_.partial(orderFilter, orderbook.base, 'sell'));
  return {bids, asks};
}

function getOrderBook(account, orderbook, options, callback) {
  validate.address(account);
  validate.orderbook(orderbook);
  validate.options(options);

  const getter = _.partial(getBookOffers, this.remote, account,
    options.ledgerVersion, options.limit);
  const getOffers = _.partial(getter, orderbook.base, orderbook.counter);
  const getReverseOffers = _.partial(getter, orderbook.counter, orderbook.base);
  async.parallel([getOffers, getReverseOffers],
    composeAsync((data) => formatBidsAndAsks(orderbook, _.flatten(data)),
                 callback));
}

module.exports = utils.wrapCatch(getOrderBook);
<|endoftext|>


<commit_before>import { Router } from 'express'
import Measure from '../models/measure'
import { r } from '../db'
import { densityToBrix } from '../helpers/transformations'

export default ({ config, db }) => {
  let router = Router({ mergeParams: true })

  router.param('measure', (req, resp, next, id) => {
    req.measure = Measure.get(id)
    next()
  })

  router.get('/', async ({ reaction, params }, res) => {
    try {
      res.json((await reaction.getJoin({
        measures: {
          _apply (sequence) {
            return sequence.orderBy(r.desc('time'))
          }
        }})).measures || [])
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.post('/', async ({ reaction, body }, res) => {
    try {
      var measure = {}
      measure.temperature = body.temperature
      measure.time = new Date()
      measure.density = body.density
      measure.ph = body.ph
      const brix = densityToBrix(body.density)
      measure.brix = brix
      measure.alcoholicContents = 46
      await Measure.save(measure)
      res.json(await reaction.addRelation('measures', await measure))
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.delete('/:measure', async ({ reaction, measure }, res) => {
    try {
      res.json(await reaction.removeRelation('measures', await measure))
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.get('/graph', async ({ reaction, params }, res) => {
    try {
      var measuresModel = await reaction.getJoin({
        measures: {
          _apply (sequence) {
            return sequence.orderBy(r.desc('time'))
          }
        }
      })
      var measures = measuresModel.measures
      var brixData = measures.map((measure, index) => {
        return { x: index, y: measure.brix }
      })
      var glData = measures.map((measure, index) => {
        return { x: index, y: measure.alcoholicContents }
      })

      res.json({brixData, glData})
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  return router
}
<commit_msg>Novo maneira de enviar graph data<commit_after>import { Router } from 'express'
import Measure from '../models/measure'
import { r } from '../db'
import { densityToBrix } from '../helpers/transformations'

export default ({ config, db }) => {
  let router = Router({ mergeParams: true })

  router.param('measure', (req, resp, next, id) => {
    req.measure = Measure.get(id)
    next()
  })

  router.get('/', async ({ reaction, params }, res) => {
    try {
      res.json((await reaction.getJoin({
        measures: {
          _apply (sequence) {
            return sequence.orderBy(r.desc('time'))
          }
        }})).measures || [])
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.post('/', async ({ reaction, body }, res) => {
    try {
      var measure = {}
      measure.temperature = body.temperature
      measure.time = new Date()
      measure.density = body.density
      measure.ph = body.ph
      const brix = densityToBrix(body.density)
      measure.brix = brix
      measure.alcoholicContents = 46
      await Measure.save(measure)
      res.json(await reaction.addRelation('measures', await measure))
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.delete('/:measure', async ({ reaction, measure }, res) => {
    try {
      res.json(await reaction.removeRelation('measures', await measure))
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  router.get('/graph', async ({ reaction, params }, res) => {
    try {
      var measuresModel = await reaction.getJoin({
        measures: {
          _apply (sequence) {
            return sequence.orderBy(r.desc('time'))
          }
        }
      })
      var measures = measuresModel.measures
      var brixData = measures.map((measure, index) => {
        return { x: index, y: measure.brix }
      })
      var glData = measures.map((measure, index) => {
        return { x: index, y: measure.alcoholicContents }
      })
      var array = [glData, brixData]
      res.json(array)
    } catch (err) {
      res.status(404).json({ error: err.name + ': ' + err.message })
    }
  })

  return router
}
<|endoftext|>


<commit_before>window.wait(() => {
  window.GPM.on('change:playback', (mode) => {
    switch (mode) {
      case window.GMusic.PlaybackStatus.STOPPED:
        Emitter.fire('playback:isStopped');
        break;
      case window.GMusic.PlaybackStatus.PAUSED:
        Emitter.fire('playback:isPaused');
        break;
      case window.GMusic.PlaybackStatus.PLAYING:
        Emitter.fire('playback:isPlaying');
        break;
      default:
        break;
    }
  });

  let playTime = 0;
  let lastPosition = 0;
  let currentTrack;

  window.GPM.on('change:track', (track) => {
    Logger.debug({
      event: "change:track",
      prev: currentTrack,
      track: track,
    });
    currentTrack = track;
    playTime = 0;
    lastPosition = 0;
    Emitter.fire('change:track', track);
    Emitter.fire('change:rating', window.GPM.rating.getRating());
    if (window.GPM.rating.getRating() === '1' && Settings.get('skipBadSongs')) {
      window.GPM.playback.forward();
    }
  });

  window.GPM.on('change:rating', (rating) => {
    Emitter.fire('change:rating', rating);
  });

  window.GPM.on('change:shuffle', (mode) => {
    Emitter.fire('change:shuffle', mode);
  });
  // DEV: Set inital shuffle value
  setTimeout(() => {
    Emitter.fire('change:shuffle', window.GPM.playback.getShuffle());
  }, 100);

  window.GPM.on('change:repeat', (mode) => {
    Emitter.fire('change:repeat', mode);
  });
  // DEV: Set inital repeat value
  setTimeout(() => {
    Emitter.fire('change:repeat', window.GPM.playback.getRepeat());
  }, 100);

  window.GPM.on('change:playback-time', (playbackInfo) => {
    Emitter.fire('change:playback-time', playbackInfo);

    const progress = playbackInfo.current - lastPosition;
    lastPosition = playbackInfo.current;
    // Update time if slider wasn't moved manually
    if (progress > 0 && progress < 2000) {
      playTime += progress;
    }

    Logger.debug({
      event: "change:playback-time",
      info: playbackInfo,
      progress: progress,
      playTime: playTime,
    });

    // Scrobble if played more than half or 4 minutes
    if (playbackInfo.total !== 0 && (playTime / playbackInfo.total) > 0.5 || playTime > 1000 * 60 * 4) {
      Logger.debug("SCROBBLE EVENT!!!");
      Emitter.fire('change:track:scrobble', {
        title: currentTrack.title,
        artist: currentTrack.artist,
        album: currentTrack.album,
        duration: currentTrack.duration,
        timestamp: Math.round((Date.now() - playTime) / 1000),
      });
      playTime -= playbackInfo.total;
    }
  });

  window.GPM.on('change:volume', (newVolume) => {
    Emitter.fire('change:volume', newVolume);
  });
  Emitter.fire('change:volume', window.GPM.volume.getVolume());
  window.GPM.on('change:playlists', (playlists) => {
    Emitter.fire('change:playlists', playlists);
  });
  window.GPM.on('change:queue', (queue) => {
    Emitter.fire('change:queue', queue);
  });
  window.GPM.on('change:search-results', (results) => {
    Emitter.fire('change:search-results', results);
  });
  window.GPM.on('change:library', (library) => {
    Emitter.fire('change:library', library);
  });
  Emitter.fire('change:library', window.GPM.library.getLibrary());

  Emitter.on('execute:gmusic', (event, cmd) => {
    if (window.GPM && GPM[cmd.namespace] && GPM[cmd.namespace][cmd.method]
      && typeof GPM[cmd.namespace][cmd.method] === 'function') {
      let error;
      let result;
      try {
        result = GPM[cmd.namespace][cmd.method].apply(GPM, cmd.args || []);
      } catch (err) {
        error = err;
      }
      const sendResponse = (response, isError) => {
        Emitter.fire(`execute:gmusic:result_${cmd.requestID}`, {
          namespace: 'result',
          type: isError ? 'error' : 'return',
          value: response,
          requestID: cmd.requestID,
        });
      };
      if (error) {
        sendResponse(error, true);
      } else {
        Promise.resolve(result)
          .then((response) => sendResponse(response, false))
          .catch((err) => sendResponse(err, true));
      }
    }
  });
});
<commit_msg>debug info [2]<commit_after>window.wait(() => {
  window.GPM.on('change:playback', (mode) => {
    switch (mode) {
      case window.GMusic.PlaybackStatus.STOPPED:
        Emitter.fire('playback:isStopped');
        break;
      case window.GMusic.PlaybackStatus.PAUSED:
        Emitter.fire('playback:isPaused');
        break;
      case window.GMusic.PlaybackStatus.PLAYING:
        Emitter.fire('playback:isPlaying');
        break;
      default:
        break;
    }
  });

  let playTime = 0;
  let lastPosition = 0;
  let currentTrack;

  window.GPM.on('change:track', (track) => {
    Logger.debug({
      event: 'change:track',
      prev: currentTrack,
      track,
    });
    currentTrack = track;
    playTime = 0;
    lastPosition = 0;
    Emitter.fire('change:track', track);
    Emitter.fire('change:rating', window.GPM.rating.getRating());
    if (window.GPM.rating.getRating() === '1' && Settings.get('skipBadSongs')) {
      window.GPM.playback.forward();
    }
  });

  window.GPM.on('change:rating', (rating) => {
    Emitter.fire('change:rating', rating);
  });

  window.GPM.on('change:shuffle', (mode) => {
    Emitter.fire('change:shuffle', mode);
  });
  // DEV: Set inital shuffle value
  setTimeout(() => {
    Emitter.fire('change:shuffle', window.GPM.playback.getShuffle());
  }, 100);

  window.GPM.on('change:repeat', (mode) => {
    Emitter.fire('change:repeat', mode);
  });
  // DEV: Set inital repeat value
  setTimeout(() => {
    Emitter.fire('change:repeat', window.GPM.playback.getRepeat());
  }, 100);

  window.GPM.on('change:playback-time', (playbackInfo) => {
    Emitter.fire('change:playback-time', playbackInfo);

    const progress = playbackInfo.current - lastPosition;
    lastPosition = playbackInfo.current;
    // Update time if slider wasn't moved manually
    if (progress > 0 && progress < 2000) {
      playTime += progress;
    }

    Logger.debug({
      event: 'change:playback-time',
      info: playbackInfo,
      progress,
      playTime,
    });

    // Scrobble if played more than half or 4 minutes
    if (playbackInfo.total !== 0 && (playTime / playbackInfo.total) > 0.5 || playTime > 1000 * 60 * 4) {
      Logger.debug('SCROBBLE EVENT!!!');
      Emitter.fire('change:track:scrobble', {
        title: currentTrack.title,
        artist: currentTrack.artist,
        album: currentTrack.album,
        duration: currentTrack.duration,
        timestamp: Math.round((Date.now() - playTime) / 1000),
      });
      playTime -= playbackInfo.total;
    }
  });

  window.GPM.on('change:volume', (newVolume) => {
    Emitter.fire('change:volume', newVolume);
  });
  Emitter.fire('change:volume', window.GPM.volume.getVolume());
  window.GPM.on('change:playlists', (playlists) => {
    Emitter.fire('change:playlists', playlists);
  });
  window.GPM.on('change:queue', (queue) => {
    Emitter.fire('change:queue', queue);
  });
  window.GPM.on('change:search-results', (results) => {
    Emitter.fire('change:search-results', results);
  });
  window.GPM.on('change:library', (library) => {
    Emitter.fire('change:library', library);
  });
  Emitter.fire('change:library', window.GPM.library.getLibrary());

  Emitter.on('execute:gmusic', (event, cmd) => {
    if (window.GPM && GPM[cmd.namespace] && GPM[cmd.namespace][cmd.method]
      && typeof GPM[cmd.namespace][cmd.method] === 'function') {
      let error;
      let result;
      try {
        result = GPM[cmd.namespace][cmd.method].apply(GPM, cmd.args || []);
      } catch (err) {
        error = err;
      }
      const sendResponse = (response, isError) => {
        Emitter.fire(`execute:gmusic:result_${cmd.requestID}`, {
          namespace: 'result',
          type: isError ? 'error' : 'return',
          value: response,
          requestID: cmd.requestID,
        });
      };
      if (error) {
        sendResponse(error, true);
      } else {
        Promise.resolve(result)
          .then((response) => sendResponse(response, false))
          .catch((err) => sendResponse(err, true));
      }
    }
  });
});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define(["./library", "sap/ui/base/ManagedObject", "sap/base/Log"],
function (coreLibrary, ManagedObject, Log) {
	"use strict";

	var oInstance;

	var InvisibleMessageMode = coreLibrary.InvisibleMessageMode;

	/**
	 * @class
	 *
	 * The InvisibleMessage provides a way to programmaticaly expose dynamic content changes in a way that can be announced by screen readers.
	 *
	 *
Overview

	 * This class is a singleton. The class instance can be retrieved via the static method sap.ui.core.InvisibleMessage.getInstance().
	 *
	 * Note: Keep in mind that according to the ARIA standard, the live regions should be presented and should be empty.
	 * Thus, we recommend to instantiate  InvisibleMessage via sap.ui.core.InvisibleMessage.getInstance() as early as possible in the application logic – with the Component initialization, with the main Controller initialization, after Core initialization, ect.
	 * Then, you should specify the text, that has to be announced by the screen reader, and the live region’s mode using the announce method.
	 *
	 * @extends sap.ui.core.ManagedObject
	 *
	 * @author SAP SE
	 * @version ${version}
	 * @hideconstructor
	 * @public
	 * @experimental Since 1.78. This class is experimental and the API might be changed in future.
	 * @since 1.78
	 * @alias sap.ui.core.InvisibleMessage
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */

	var InvisibleMessage = ManagedObject.extend("sap.ui.core.InvisibleMessage", /** @lends sap.ui.core.InvisibleMessage.prototype */ {

		constructor: function () {
			if (oInstance) {
				Log.warning('This is a singleton, therefore you are not able to create another instance of this class.');

				return oInstance;
			}

			oInstance = this;

			ManagedObject.apply(this, arguments);
		}
	});

	/**
	 * Returns the instance of the class.
	 * @return {sap.ui.core.InvisibleMessage} oInstance
	 * @static
	 * @public
	 */
	InvisibleMessage.getInstance = function () {
		if (!oInstance) {
			oInstance = new InvisibleMessage("__invisiblemessage",{});
		}

		return oInstance;
	};

	InvisibleMessage.prototype.init = function () {
		var oCore = sap.ui.getCore(),
			oStatic = oCore.getStaticAreaRef();

		oStatic.insertAdjacentHTML("beforeend", this.getPoliteInstance());
		oStatic.insertAdjacentHTML("beforeend", this.getAssertiveInstance());
	};

	/**
	 * Inserts the string into the respective span, depending on the mode provided.
	 *
	 * @param {string} sText String to be announced by the screen reader.
	 * @param {sap.ui.core.InvisibleMessageMode} sMode The mode to be inserted in the aria-live attribute.
	 * @public
	 */
	InvisibleMessage.prototype.announce = function (sText, sMode) {
		var oCore = sap.ui.getCore(),
			oStatic = oCore.getStaticAreaRef(),
			oPoliteMarkup = oStatic.querySelector(".sapUiInvisibleMessagePolite"),
			oAssertiveMarkup = oStatic.querySelector(".sapUiInvisibleMessageAssertive");

		if (!oPoliteMarkup || !oAssertiveMarkup) {
			return;
		}

		var oNode = sMode === InvisibleMessageMode.Assertive ? oAssertiveMarkup : oPoliteMarkup;

		// Set textContent to empty string in order to trigger screen reader's announce.
		oNode.textContent = "";
		oNode.textContent = sText;

		if (sMode !== InvisibleMessageMode.Assertive && sMode !== InvisibleMessageMode.Polite) {
			Log.info('You have entered an invalid mode. Valid values are: ' + '"Polite" ' + 'and "Assertive". The framework will automatically set the mode to "Polite".');
		}
	};

	/**
	 * @return {string} Returns the span to be rendered for the polite instance.
	 * @private
	 * @function
	 */
	InvisibleMessage.prototype.getPoliteInstance = function() {
		var sId = this.getId();
		return '' +
				'';
	};

	/**
	 * @return {string} Returns the span to be rendered for the assertive instance.
	 * @private
	 * @function
	 */
	InvisibleMessage.prototype.getAssertiveInstance = function() {
		var sId = this.getId();
		return '' +
				'';
	};

	return InvisibleMessage;

});<commit_msg>[INTERNAL] sap.ui.core.InvisibleMessage: Documentation adjusted<commit_after>/*!
 * ${copyright}
 */

sap.ui.define(["./library", "sap/ui/base/ManagedObject", "sap/base/Log"],
function (coreLibrary, ManagedObject, Log) {
	"use strict";

	var oInstance;

	var InvisibleMessageMode = coreLibrary.InvisibleMessageMode;

	/**
	 * @class
	 *
	 * The InvisibleMessage provides a way to programmaticaly expose dynamic content changes in a way that can be announced by screen readers.
	 *
	 *
Overview

	 * This class is a singleton. The class instance can be retrieved via the static method sap.ui.core.InvisibleMessage.getInstance().
	 *
	 * Note: Keep in mind that according to the ARIA standard, the live regions should be presented and should be empty.
	 * Thus, we recommend to instantiate  InvisibleMessage via sap.ui.core.InvisibleMessage.getInstance() as early as possible in the application logic – with the Component initialization, with the main Controller initialization, after Core initialization, ect.
	 * Then, you should specify the text, that has to be announced by the screen reader, and the live region’s mode using the announce method.
	 *
	 * @extends sap.ui.core.ManagedObject
	 *
	 * @author SAP SE
	 * @version ${version}
	 * @hideconstructor
	 * @public
	 * @experimental Since 1.78. This class is experimental and the API might be changed in future.
	 * @since 1.78
	 * @alias sap.ui.core.InvisibleMessage
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */

	var InvisibleMessage = ManagedObject.extend("sap.ui.core.InvisibleMessage", /** @lends sap.ui.core.InvisibleMessage.prototype */ {

		constructor: function () {
			if (oInstance) {
				Log.warning('This is a singleton, therefore you are not able to create another instance of this class.');

				return oInstance;
			}

			oInstance = this;

			ManagedObject.apply(this, arguments);
		}
	});

	/**
	 * Returns the instance of the class.
	 * @return {sap.ui.core.InvisibleMessage} oInstance
	 * @static
	 * @public
	 */
	InvisibleMessage.getInstance = function () {
		if (!oInstance) {
			oInstance = new InvisibleMessage("__invisiblemessage",{});
		}

		return oInstance;
	};

	InvisibleMessage.prototype.init = function () {
		var oCore = sap.ui.getCore(),
			oStatic = oCore.getStaticAreaRef();

		oStatic.insertAdjacentHTML("beforeend", this.getPoliteInstance());
		oStatic.insertAdjacentHTML("beforeend", this.getAssertiveInstance());
	};

	/**
	 * Inserts the string into the respective span, depending on the mode provided.
	 *
	 * @param {string} sText String to be announced by the screen reader.
	 * @param {sap.ui.core.InvisibleMessageMode} sMode The mode to be inserted in the aria-live attribute.
	 * @public
	 */
	InvisibleMessage.prototype.announce = function (sText, sMode) {
		var oCore = sap.ui.getCore(),
			oStatic = oCore.getStaticAreaRef(),
			oPoliteMarkup = oStatic.querySelector(".sapUiInvisibleMessagePolite"),
			oAssertiveMarkup = oStatic.querySelector(".sapUiInvisibleMessageAssertive");

		if (!oPoliteMarkup || !oAssertiveMarkup) {
			return;
		}

		var oNode = sMode === InvisibleMessageMode.Assertive ? oAssertiveMarkup : oPoliteMarkup;

		// Set textContent to empty string in order to trigger screen reader's announce.
		oNode.textContent = "";
		oNode.textContent = sText;

		if (sMode !== InvisibleMessageMode.Assertive && sMode !== InvisibleMessageMode.Polite) {
			Log.info('You have entered an invalid mode. Valid values are: ' + '"Polite" ' + 'and "Assertive". The framework will automatically set the mode to "Polite".');
		}
	};

	/**
	 * @return {string} Returns the span to be rendered for the polite instance.
	 * @private
	 * @function
	 */
	InvisibleMessage.prototype.getPoliteInstance = function() {
		var sId = this.getId();
		return '' +
				'';
	};

	/**
	 * @return {string} Returns the span to be rendered for the assertive instance.
	 * @private
	 * @function
	 */
	InvisibleMessage.prototype.getAssertiveInstance = function() {
		var sId = this.getId();
		return '' +
				'';
	};

	return InvisibleMessage;

});<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: UndoManager.js                                                       \\
// Module: DataStore                                                          \\
// Requires: Core, Foundation                                                 \\
// Author: Neil Jenkins                                                       \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed.                       \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

/**
    Class: O.UndoManager
*/

var UndoManager = NS.Class({

    Extends: NS.Object,

    init: function ( mixin ) {
        this._undoStack = [];
        this._redoStack = [];

        this._isInUndoState = false;

        this.canUndo = false;
        this.canRedo = false;

        this.maxUndoCount = 1;

        UndoManager.parent.init.call( this, mixin );
    },

    _pushState: function ( stack, data ) {
        stack.push( data );
        while ( stack.length > this.maxUndoCount ) {
            stack.shift();
        }
        this._isInUndoState = true;
    },

    dataDidChange: function () {
        this._isInUndoState = false;
        this._redoStack.length = 0;
        this.set( 'canRedo', false )
            .set( 'canUndo', true );
        return this;
    },

    saveUndoCheckpoint: function () {
        if ( !this._isInUndoState ) {
            var data = this.getUndoData();
            if ( data !== null ) {
                this._pushState( this._undoStack, data );
            } else {
                this._isInUndoState = true;
                this.set( 'canUndo', !!this._undoStack.length );
            }
        }
        return this;
    },

    undo: function () {
        if ( this.get( 'canUndo' ) ) {
            if ( !this._isInUndoState ) {
                this.saveUndoCheckpoint();
                return this.undo();
            } else {
                this._pushState( this._redoStack,
                    this.applyChange( this._undoStack.pop(), false )
                );
                this.set( 'canUndo', !!this._undoStack.length )
                    .set( 'canRedo', true );
            }
        }
        return this;
    },

    redo: function () {
        if ( this.get( 'canRedo' ) ) {
            this._pushState( this._undoStack,
                this.applyChange( this._redoStack.pop(), true )
            );
            this.set( 'canUndo', true )
                .set( 'canRedo', !!this._redoStack.length );
        }
        return this;
    },

    getUndoData: function () {},

    applyChange: function (/* data, isRedo */) {}
});

var StoreUndoManager = NS.Class({

    Extends: UndoManager,

    init: function ( mixin ) {
        var store = mixin.store;
        store.on( 'willCommit', this, 'saveUndoCheckpoint' )
             .on( 'record:user:create', this, 'dataDidChange' )
             .on( 'record:user:update', this, 'dataDidChange' )
             .on( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.init.call( this, mixin );
    },

    destroy: function () {
        this.store.off( 'willCommit', this, 'saveUndoCheckpoint' )
                  .off( 'record:user:create', this, 'dataDidChange' )
                  .off( 'record:user:update', this, 'dataDidChange' )
                  .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    getUndoData: function () {
        var store = this.store;
        return store.hasChanges() ? store.getInverseChanges() : null;
    },

    applyChange: function ( data ) {
        var store = this.store,
            inverse;
        store.applyChanges( data );
        inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    }
});

NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;

}( O ) );
<commit_msg>Fire input, undo and redo events in UndoManager.<commit_after>// -------------------------------------------------------------------------- \\
// File: UndoManager.js                                                       \\
// Module: DataStore                                                          \\
// Requires: Core, Foundation                                                 \\
// Author: Neil Jenkins                                                       \\
// License: © 2010-2014 FastMail Pty Ltd. MIT Licensed.                       \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

/**
    Class: O.UndoManager
*/

var UndoManager = NS.Class({

    Extends: NS.Object,

    init: function ( mixin ) {
        this._undoStack = [];
        this._redoStack = [];

        this._isInUndoState = false;

        this.canUndo = false;
        this.canRedo = false;

        this.maxUndoCount = 1;

        UndoManager.parent.init.call( this, mixin );
    },

    _pushState: function ( stack, data ) {
        stack.push( data );
        while ( stack.length > this.maxUndoCount ) {
            stack.shift();
        }
        this._isInUndoState = true;
    },

    dataDidChange: function () {
        this._isInUndoState = false;
        this._redoStack.length = 0;
        this.set( 'canRedo', false )
            .set( 'canUndo', true )
            .fire( 'input' );
        return this;
    },

    saveUndoCheckpoint: function () {
        if ( !this._isInUndoState ) {
            var data = this.getUndoData();
            if ( data !== null ) {
                this._pushState( this._undoStack, data );
            } else {
                this._isInUndoState = true;
                this.set( 'canUndo', !!this._undoStack.length );
            }
        }
        return this;
    },

    undo: function () {
        if ( this.get( 'canUndo' ) ) {
            if ( !this._isInUndoState ) {
                this.saveUndoCheckpoint();
                this.undo();
            } else {
                this._pushState( this._redoStack,
                    this.applyChange( this._undoStack.pop(), false )
                );
                this.set( 'canUndo', !!this._undoStack.length )
                    .set( 'canRedo', true )
                    .fire( 'undo' );
            }
        }
        return this;
    },

    redo: function () {
        if ( this.get( 'canRedo' ) ) {
            this._pushState( this._undoStack,
                this.applyChange( this._redoStack.pop(), true )
            );
            this.set( 'canUndo', true )
                .set( 'canRedo', !!this._redoStack.length )
                .fire( 'redo' );
        }
        return this;
    },

    getUndoData: function () {},

    applyChange: function (/* data, isRedo */) {}
});

var StoreUndoManager = NS.Class({

    Extends: UndoManager,

    init: function ( mixin ) {
        var store = mixin.store;
        store.on( 'willCommit', this, 'saveUndoCheckpoint' )
             .on( 'record:user:create', this, 'dataDidChange' )
             .on( 'record:user:update', this, 'dataDidChange' )
             .on( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.init.call( this, mixin );
    },

    destroy: function () {
        this.store.off( 'willCommit', this, 'saveUndoCheckpoint' )
                  .off( 'record:user:create', this, 'dataDidChange' )
                  .off( 'record:user:update', this, 'dataDidChange' )
                  .off( 'record:user:destroy', this, 'dataDidChange' );
        StoreUndoManager.parent.destroy.call( this );
    },

    getUndoData: function () {
        var store = this.store;
        return store.hasChanges() ? store.getInverseChanges() : null;
    },

    applyChange: function ( data ) {
        var store = this.store,
            inverse;
        store.applyChanges( data );
        inverse = store.getInverseChanges();
        store.commitChanges();
        return inverse;
    }
});

NS.UndoManager = UndoManager;
NS.StoreUndoManager = StoreUndoManager;

}( O ) );
<|endoftext|>


<commit_before>'use strict';

(function axePatch(window) {
  const axe = window.axe;
  const dpubRoles = {
    'doc-abstract': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-acknowledgments': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-afterword': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-appendix': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-backlink': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author', 'contents'],
      context: null,
    },
    'doc-biblioentry': {
      type: 'listitem',
      attributes: {
        allowed: ['aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize'],
      },
      owned: null,
      nameFrom: ['author'],
      context: ['doc-bibliography'],
    },
    'doc-bibliography': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-biblioref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author', 'contents'],
      context: null,
    },
    'doc-chapter': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-colophon': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-conclusion': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-cover': {
      type: 'img',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-credit': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-credits': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-dedication': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-endnote': {
      type: 'listitem',
      attributes: {
        allowed: ['aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize'],
      },
      owned: null,
      namefrom: ['author'],
      context: ['doc-endnotes'],
    },
    'doc-endnotes': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: ['doc-endnote'],
      namefrom: ['author'],
      context: null,
    },
    'doc-epigraph': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-epilogue': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-errata': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-example': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-footnote': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-foreword': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-glossary': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: ['term', 'definition'],
      namefrom: ['author'],
      context: null,
    },
    'doc-glossref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author', 'contents'],
      context: null,
    },
    'doc-index': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-introduction': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-noteref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author', 'contents'],
      context: null,
    },
    'doc-notice': {
      type: 'note',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pagebreak': {
      type: 'separator',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pagelist': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-part': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-preface': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-prologue': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pullquote': {
      type: 'none',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-qna': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-subtitle': {
      type: 'sectionhead',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-tip': {
      type: 'note',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-toc': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
  };

  Object.assign(axe.commons.aria._lut.role, dpubRoles);
}(window));
<commit_msg>fix(rule): ensure DPUB ARIA roles are accepted by aXe 2.6<commit_after>'use strict';

(function axePatch(window) {
  const axe = window.axe;
  const dpubRoles = {
    'doc-abstract': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-acknowledgments': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-afterword': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-appendix': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-backlink': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author', 'contents'],
      context: null,
    },
    'doc-biblioentry': {
      type: 'listitem',
      attributes: {
        allowed: ['aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize'],
      },
      owned: null,
      nameFrom: ['author'],
      context: ['doc-bibliography'],
    },
    'doc-bibliography': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author'],
      context: null,
    },
    'doc-biblioref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      nameFrom: ['author', 'contents'],
      context: null,
    },
    'doc-chapter': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-colophon': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-conclusion': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-cover': {
      type: 'img',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-credit': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-credits': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-dedication': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-endnote': {
      type: 'listitem',
      attributes: {
        allowed: ['aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize'],
      },
      owned: null,
      namefrom: ['author'],
      context: ['doc-endnotes'],
    },
    'doc-endnotes': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: ['doc-endnote'],
      namefrom: ['author'],
      context: null,
    },
    'doc-epigraph': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-epilogue': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-errata': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-example': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-footnote': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-foreword': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-glossary': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: ['term', 'definition'],
      namefrom: ['author'],
      context: null,
    },
    'doc-glossref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author', 'contents'],
      context: null,
    },
    'doc-index': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-introduction': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-noteref': {
      type: 'link',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author', 'contents'],
      context: null,
    },
    'doc-notice': {
      type: 'note',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pagebreak': {
      type: 'separator',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pagelist': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-part': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-preface': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-prologue': {
      type: 'landmark',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-pullquote': {
      type: 'none',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-qna': {
      type: 'section',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-subtitle': {
      type: 'sectionhead',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-tip': {
      type: 'note',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
    'doc-toc': {
      type: 'navigation',
      attributes: {
        allowed: ['aria-expanded'],
      },
      owned: null,
      namefrom: ['author'],
      context: null,
    },
  };

  Object.assign(axe.commons.aria.lookupTable.role, dpubRoles);
}(window));
<|endoftext|>


<commit_before>// Source Server Stats
// File: sourcestats/webpack/components/Graph.js
// Desc: displays the graphs around the site

import _ from 'lodash';
import moment from 'moment';
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import MG from 'metrics-graphics';

export const GRAPH_OPTIONS = {
    x_accessor: 'date',
    y_accessor: 'value',
    height: 200,
    full_width: true,
    right: 0,
    show_secondary_x_label: false
};

export default class Graph extends React.Component {
    static PropTypes = {
        fetch: PropTypes.func.isRequired,
        data: PropTypes.object.isRequired
    }

    filters = {
        since: moment().utc().subtract(1, 'days').toISOString().split('.')[0]
    }

    componentDidMount() {
        this.fetchData();
    }

    componentDidUpdate() {
        if (this.props.data.length > 0) {
            MG.data_graphic(_.extend(_.clone(GRAPH_OPTIONS), {
                data: this.props.data,
                target: ReactDOM.findDOMNode(this).querySelector('.graph')
            }));
        }
    }

    fetchData() {
        this.props.fetch(this.filters);
    }

    setTimePeriod(period) {
        let since = moment().utc();

        if (period === '7-day') {
            since = since.subtract(7, 'days');
        } else if (period === '30-day') {
            since = since.subtract(30, 'days');
        } else {
            since = since.subtract(1, 'days');
        }

        const iso = since.toISOString();
        this.filters.since = iso.split('.')[0];
        this.fetchData();
    }

    render() {
        return (

                {this.props.title}

                <select
                    className='right'
                    onChange={(e) => this.setTimePeriod(e.target.value)}
                >
                    <option value='1-day' default>1 day</option>
                    <option value='7-day'>7 days</option>
                    <option value='30-day'>30 days</option>
                </select>

);
    }
}
<commit_msg>Add missing_is_hidden to graphs.<commit_after>// Source Server Stats
// File: sourcestats/webpack/components/Graph.js
// Desc: displays the graphs around the site

import _ from 'lodash';
import moment from 'moment';
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import MG from 'metrics-graphics';

export const GRAPH_OPTIONS = {
    x_accessor: 'date',
    y_accessor: 'value',
    height: 200,
    full_width: true,
    right: 0,
    show_secondary_x_label: false,
    missing_is_hidden: true
};

export default class Graph extends React.Component {
    static PropTypes = {
        fetch: PropTypes.func.isRequired,
        data: PropTypes.object.isRequired
    }

    filters = {
        since: moment().utc().subtract(1, 'days').toISOString().split('.')[0]
    }

    componentDidMount() {
        this.fetchData();
    }

    componentDidUpdate() {
        if (this.props.data.length > 0) {
            MG.data_graphic(_.extend(_.clone(GRAPH_OPTIONS), {
                data: this.props.data,
                target: ReactDOM.findDOMNode(this).querySelector('.graph')
            }));
        }
    }

    fetchData() {
        this.props.fetch(this.filters);
    }

    setTimePeriod(period) {
        let since = moment().utc();

        if (period === '7-day') {
            since = since.subtract(7, 'days');
        } else if (period === '30-day') {
            since = since.subtract(30, 'days');
        } else {
            since = since.subtract(1, 'days');
        }

        const iso = since.toISOString();
        this.filters.since = iso.split('.')[0];
        this.fetchData();
    }

    render() {
        return (

                {this.props.title}

                <select
                    className='right'
                    onChange={(e) => this.setTimePeriod(e.target.value)}
                >
                    <option value='1-day' default>1 day</option>
                    <option value='7-day'>7 days</option>
                    <option value='30-day'>30 days</option>
                </select>

);
    }
}
<|endoftext|>


<commit_before>/**
  @module ember-data
*/

var get = Ember.get;
var set = Ember.set;

/**
  A `ManyArray` is a `RecordArray` that represents the contents of a has-many
  relationship.

  The `ManyArray` is instantiated lazily the first time the relationship is
  requested.

  ### Inverses

  Often, the relationships in Ember Data applications will have
  an inverse. For example, imagine the following models are
  defined:

  ```javascript
  App.Post = DS.Model.extend({
    comments: DS.hasMany('comment')
  });

  App.Comment = DS.Model.extend({
    post: DS.belongsTo('post')
  });
  ```

  If you created a new instance of `App.Post` and added
  a `App.Comment` record to its `comments` has-many
  relationship, you would expect the comment's `post`
  property to be set to the post that contained
  the has-many.

  We call the record to which a relationship belongs the
  relationship's _owner_.

  @class ManyArray
  @namespace DS
  @extends Ember.Object
  @uses Ember.MutableArray, Ember.Evented
*/
export default Ember.Object.extend(Ember.MutableArray, Ember.Evented, {
  init: function() {
    this.currentState = Ember.A([]);
    this.diff = [];
  },

  record: null,

  canonicalState: null,
  currentState: null,

  diff: null,

  length: 0,

  objectAt: function(index) {
    if (this.currentState[index]) {
      return this.currentState[index];
    } else {
      return this.canonicalState[index];
    }
  },

  flushCanonical: function() {
    //TODO make this smarter, currently its plenty stupid
    var toSet = this.canonicalState.slice(0);
    //a hack for not removing new records
    //TODO remove once we have proper diffing
    var newRecords = this.currentState.filter(function(record) {
      return record.get('isNew');
    });
    toSet = toSet.concat(newRecords);
    this.arrayContentWillChange(0, this.length, this.length);
    this.set('length', toSet.length);
    this.currentState = toSet;
    this.arrayContentDidChange(0, this.length, this.length);
    //TODO Figure out to notify only on additions and maybe only if unloaded
    this.relationship.notifyHasManyChanged();
    this.record.updateRecordArrays();
  },
  /**
    `true` if the relationship is polymorphic, `false` otherwise.

    @property {Boolean} isPolymorphic
    @private
  */
  isPolymorphic: false,

  /**
    The loading state of this array

    @property {Boolean} isLoaded
  */
  isLoaded: false,

   /**
     The relationship which manages this array.

     @property {ManyRelationship} relationship
     @private
   */
  relationship: null,

  internalReplace: function(idx, amt, objects) {
    if (!objects) {
      objects = [];
    }
    this.arrayContentWillChange(idx, amt, objects.length);
    this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
    this.set('length', this.currentState.length);
    this.arrayContentDidChange(idx, amt, objects.length);
    if (objects) {
      //TODO(Igor) probably needed only for unloaded records
      this.relationship.notifyHasManyChanged();
    }
    this.record.updateRecordArrays();
  },

  //TODO(Igor) optimize
  internalRemoveRecords: function(records) {
    var index;
    for (var i=0; i < records.length; i++) {
      index = this.currentState.indexOf(records[i]);
      this.internalReplace(index, 1);
    }
  },

  //TODO(Igor) optimize
  internalAddRecords: function(records, idx) {
    if (idx === undefined) {
      idx = this.currentState.length;
    }
    this.internalReplace(idx, 0, records);
  },

  replace: function(idx, amt, objects) {
    var records;
    if (amt > 0) {
      records = this.currentState.slice(idx, idx+amt);
      this.get('relationship').removeRecords(records);
    }
    if (objects) {
      this.get('relationship').addRecords(objects, idx);
    }
  },
  /**
    Used for async `hasMany` arrays
    to keep track of when they will resolve.

    @property {Ember.RSVP.Promise} promise
    @private
  */
  promise: null,

  /**
    @method loadingRecordsCount
    @param {Number} count
    @private
  */
  loadingRecordsCount: function(count) {
    this.loadingRecordsCount = count;
  },

  /**
    @method loadedRecord
    @private
  */
  loadedRecord: function() {
    this.loadingRecordsCount--;
    if (this.loadingRecordsCount === 0) {
      set(this, 'isLoaded', true);
      this.trigger('didLoad');
    }
  },

  /**
    @method reload
    @public
  */
  reload: function() {
    return this.relationship.reload();
  },

  /**
    Create a child record within the owner

    @method createRecord
    @private
    @param {Object} hash
    @return {DS.Model} record
  */
  createRecord: function(hash) {
    var store = get(this, 'store');
    var type = get(this, 'type');
    var record;

    Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));

    record = store.createRecord(type, hash);
    this.pushObject(record);

    return record;
  },

  /**
    @method addRecord
    @param {DS.Model} record
    @deprecated Use `addObject()` instead
  */
  addRecord: function(record) {
    Ember.deprecate('Using manyArray.addRecord() has been deprecated. You should use manyArray.addObject() instead.');
    this.addObject(record);
  },

  /**
    @method removeRecord
    @param {DS.Model} record
    @deprecated Use `removeObject()` instead
  */
  removeRecord: function(record) {
    Ember.deprecate('Using manyArray.removeRecord() has been deprecated. You should use manyArray.removeObject() instead.');
    this.removeObject(record);
  }
});
<commit_msg>remove unused code.<commit_after>/**
  @module ember-data
*/

var get = Ember.get;
var set = Ember.set;

/**
  A `ManyArray` is a `RecordArray` that represents the contents of a has-many
  relationship.

  The `ManyArray` is instantiated lazily the first time the relationship is
  requested.

  ### Inverses

  Often, the relationships in Ember Data applications will have
  an inverse. For example, imagine the following models are
  defined:

  ```javascript
  App.Post = DS.Model.extend({
    comments: DS.hasMany('comment')
  });

  App.Comment = DS.Model.extend({
    post: DS.belongsTo('post')
  });
  ```

  If you created a new instance of `App.Post` and added
  a `App.Comment` record to its `comments` has-many
  relationship, you would expect the comment's `post`
  property to be set to the post that contained
  the has-many.

  We call the record to which a relationship belongs the
  relationship's _owner_.

  @class ManyArray
  @namespace DS
  @extends Ember.Object
  @uses Ember.MutableArray, Ember.Evented
*/
export default Ember.Object.extend(Ember.MutableArray, Ember.Evented, {
  init: function() {
    this.currentState = Ember.A([]);
  },

  record: null,

  canonicalState: null,
  currentState: null,

  length: 0,

  objectAt: function(index) {
    if (this.currentState[index]) {
      return this.currentState[index];
    } else {
      return this.canonicalState[index];
    }
  },

  flushCanonical: function() {
    //TODO make this smarter, currently its plenty stupid
    var toSet = this.canonicalState.slice(0);
    //a hack for not removing new records
    //TODO remove once we have proper diffing
    var newRecords = this.currentState.filter(function(record) {
      return record.get('isNew');
    });
    toSet = toSet.concat(newRecords);
    this.arrayContentWillChange(0, this.length, this.length);
    this.set('length', toSet.length);
    this.currentState = toSet;
    this.arrayContentDidChange(0, this.length, this.length);
    //TODO Figure out to notify only on additions and maybe only if unloaded
    this.relationship.notifyHasManyChanged();
    this.record.updateRecordArrays();
  },
  /**
    `true` if the relationship is polymorphic, `false` otherwise.

    @property {Boolean} isPolymorphic
    @private
  */
  isPolymorphic: false,

  /**
    The loading state of this array

    @property {Boolean} isLoaded
  */
  isLoaded: false,

   /**
     The relationship which manages this array.

     @property {ManyRelationship} relationship
     @private
   */
  relationship: null,

  internalReplace: function(idx, amt, objects) {
    if (!objects) {
      objects = [];
    }
    this.arrayContentWillChange(idx, amt, objects.length);
    this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
    this.set('length', this.currentState.length);
    this.arrayContentDidChange(idx, amt, objects.length);
    if (objects) {
      //TODO(Igor) probably needed only for unloaded records
      this.relationship.notifyHasManyChanged();
    }
    this.record.updateRecordArrays();
  },

  //TODO(Igor) optimize
  internalRemoveRecords: function(records) {
    var index;
    for (var i=0; i < records.length; i++) {
      index = this.currentState.indexOf(records[i]);
      this.internalReplace(index, 1);
    }
  },

  //TODO(Igor) optimize
  internalAddRecords: function(records, idx) {
    if (idx === undefined) {
      idx = this.currentState.length;
    }
    this.internalReplace(idx, 0, records);
  },

  replace: function(idx, amt, objects) {
    var records;
    if (amt > 0) {
      records = this.currentState.slice(idx, idx+amt);
      this.get('relationship').removeRecords(records);
    }
    if (objects) {
      this.get('relationship').addRecords(objects, idx);
    }
  },
  /**
    Used for async `hasMany` arrays
    to keep track of when they will resolve.

    @property {Ember.RSVP.Promise} promise
    @private
  */
  promise: null,

  /**
    @method loadingRecordsCount
    @param {Number} count
    @private
  */
  loadingRecordsCount: function(count) {
    this.loadingRecordsCount = count;
  },

  /**
    @method loadedRecord
    @private
  */
  loadedRecord: function() {
    this.loadingRecordsCount--;
    if (this.loadingRecordsCount === 0) {
      set(this, 'isLoaded', true);
      this.trigger('didLoad');
    }
  },

  /**
    @method reload
    @public
  */
  reload: function() {
    return this.relationship.reload();
  },

  /**
    Create a child record within the owner

    @method createRecord
    @private
    @param {Object} hash
    @return {DS.Model} record
  */
  createRecord: function(hash) {
    var store = get(this, 'store');
    var type = get(this, 'type');
    var record;

    Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));

    record = store.createRecord(type, hash);
    this.pushObject(record);

    return record;
  },

  /**
    @method addRecord
    @param {DS.Model} record
    @deprecated Use `addObject()` instead
  */
  addRecord: function(record) {
    Ember.deprecate('Using manyArray.addRecord() has been deprecated. You should use manyArray.addObject() instead.');
    this.addObject(record);
  },

  /**
    @method removeRecord
    @param {DS.Model} record
    @deprecated Use `removeObject()` instead
  */
  removeRecord: function(record) {
    Ember.deprecate('Using manyArray.removeRecord() has been deprecated. You should use manyArray.removeObject() instead.');
    this.removeObject(record);
  }
});
<|endoftext|>