<commit_before>define(["dojo/_base/html", "dojo/_base/declare", "dojo/on", "dojo/aspect", "./TextEdit", "dojo/has", "dojo/has!touch?./TouchScroll", "cssx/css!./css/d-list.css"], function(dojo, declare, listen, aspect, TextEdit, has, TouchScroll){
	// allow for custom CSS class definitions
	// TODO: figure out what to depend for this
	var byId = function(id){
		return document.getElementById(id);
	};
	var create = dojo.create;
	function Row(id, object, element){
		this.id = id;
		this.data = object;
		this.element = element;
	}
	return declare(TouchScroll ? [TouchScroll] : [], {
		constructor: function(params, srcNodeRef){
		var self = this;
		if(typeof params == "function"){
			// mixins/plugins are being provided, we will mix then into the instance
			var i = 0, mixin;
			while(typeof (mixin = arguments[i++]) == "function"){
				dojo.safeMixin(this, mixin.prototype);
			}
			// shift the arguments to get the params and srcNodeRef for the new instantiation
			params = arguments[i - 1];
			srcNodeRef = arguments[i];
		}
		// summary:
		//		The set of observers for the data
		this.observers = [];
		this._listeners = [];
		this._rowIdToObject = {};
	/* TODO: Implement this to hide (detach from DOM) out-of-sight nodes to improve performance
	 * clearTop = function(){
		var scrollNode = self.bodyNode;
		var transform = self.contentNode.style.webkitTransform;
		var visibleTop = scrollNode.scrollTop + (transform ? -transform.match(/translate[\w]*\(.*?,(.*?)px/)[1] : 0);

		var elements = self.contentNode.childNodes;
		for(var i = 0; i < elements.length; i++){
			if(elements[i].offsetTop > visibleTop){
				break;
			}
		}
		self.otherNode = create("div", {
		});
		var last = elements[i];
		for(; i > 0; i--){
			self.otherNode.appendChild(elements[i -1]);
		}
		var node = create("div", {
			style: {
				height: visibleTop + "px"
			}
		});
		self.contentNode.insertBefore(node, last);
	};*/
			this.create(params, srcNodeRef);
		},
		minRowsPerPage: 25,
		maxRowsPerPage: 100,
		maxEmptySpace: 10000,
		queryOptions: {},
		query: {},
		createNode: create,
		rowHeight: 0,
		create: function(params, srcNodeRef){
			var domNode = this.domNode = srcNodeRef.nodeType ? srcNodeRef : byId(srcNodeRef);
			if(!this.id){
				this.id = domNode.id;
			}
			this.tabIndex = domNode.getAttribute("tabindex") || 0;
			domNode.role = "grid";
			if(params){
				this.params = params;
				dojo.safeMixin(this, params);
			}

			if(domNode.tagName == "table"){
				// TODO: read columns from table
			}
			domNode.className += "	ui-widget-content d-list";
			this.refresh();
		},
		refresh: function(){
			var headerNode = this.headerNode = create("div",{
				className: "d-list-header d-list-header-row"
			},this.domNode);
			var bodyNode = this.bodyNode = create("div",{
				className: "d-list-scroller"
			},this.domNode);
			listen(bodyNode, "scroll", function(event){
				// keep the header aligned with the body
				headerNode.scrollLeft = bodyNode.scrollLeft;
			});
			this.renderHeader();
			bodyNode.style.top = headerNode.offsetHeight + "px";
			if(dojo.isQuirks){
				// in quirks mode, the "bottom" CSS property is ignored, so do this to fix it
				// We might want to use a CSS expression or the cssx package to fix this
				bodyNode.style.height = (this.domNode.offsetHeight - headerNode.offsetHeight) + "px";
			}
			this.refreshContent();
			aspect.after(this, "scrollTo", this.onscroll);
			this.postCreate && this.postCreate();
		},
		on: function(eventType, listener){
			// delegate events to the domNode
			var signal = listen(this.domNode, eventType, listener);
			if(has("dom-addeventlistener")){
				this._listeners.push(signal);
			}
		},
		destroy: function(){
			// cleanup listeners
			for(var i = 0; i < this._listeners.length; i++){
				this._listeners.cancel();
			}
		},
		refreshContent: function(){
			// summary:
			//		refreshes the contents of the grid
			if(this.contentNode){
				// remove the content so it can be recreated
				this.contentNode.innerHTML = "";
				// remove any listeners
				for(var i = 0;i < this.observers.length; i++){
					this.observers[i].cancel();
				}
				this.observers = [];
			}else{
				this.contentNode = create("div",{
					className:"d-list-content"
				}, this.bodyNode);
			}
			if(this.init){
				this.init({
					domNode: this.bodyNode,
					containerNode: this.contentNode
				});
			}
			this.preloadNode = null;
		},
		renderCollection: function(results, beforeNode, options){
			// summary:
			//		This renders an array or collection of objects as rows in the grid, before the
			//		given node. This will listen for changes in the collection if an observe method
			//		is available (as it should be if it comes from an Observable data store).
			options = options || {};
			var start = options.start || 0;
			var self = this;
			var contentNode = this.contentNode;
			if(results.observe){
				// observe the results for changes
				this.observers.push(results.observe(function(object, from, to){
					// a change in the data took place
					if(from > -1){
						// remove from old slot
						var row = rows.splice(from, 1)[0];
						contentNode.removeChild(row);
					}
					if(to > -1){
						// add to new slot
						var row = self.createRow(object, rows[to], (options.start + to), options);
						dojo.addClass(row, "ui-state-highlight");
						setTimeout(function(){
							dojo.removeClass(row, "ui-state-highlight");
						}, 250);
						rows.splice(to, 0, row);
					}
				}));
			}
			// now render the results
			if(results.map){
				var rows = results.map(mapEach, console.error);
			}else{
				var rows = [];
				for(var i = 0, l = results.length; i < l; i++){
					rows[i] = mapEach(results[i]);
				}
			}
			function mapEach(object){
				return self.createRow(object, beforeNode, start++, options);
			}
			return rows;
		},
		_autoId: 0,
		renderHeader: function(){
			// no-op in a place list
		},
		createRow: function(object, beforeNode, i, options){
			// summary:
			//		Renders a single row in the grid
			var row = this.renderRow(object, options);
			row.className = (row.className || "") + " ui-state-default d-list-row " + (i% 2 == 1 ? "d-list-row-odd" : "d-list-row-even");
			// get the row id for easy retrieval
			this._rowIdToObject[row.id = this.id + "-row-" + ((this.store && this.store.getIdentity) ? this.store.getIdentity(object) : this._autoId++)] = object;
			this.contentNode.insertBefore(row, beforeNode);
			return row;
		},
		renderRow: function(value, options){
			return dojo.create("div", {
				innerHTML: value,
				tabIndex: this.tabIndex
			});
		},
		row: function(target){
			// summary:
			//		Get the row object by id, object, node, or event
			if(target.target && target.target.nodeType == 1){
				// event
				target = target.target;
			}
			if(target.nodeType == 1){
				var object;
				do{
					var rowId = target.id;
					if(object = this._rowIdToObject[rowId]){
						return new Row(rowId.substring(rowId.indexOf("-row-") + 5), object, target);
					}
					target = target.parentNode;
				}while(target && target != this.domNode);
				return;
			}
			if(typeof target == "object"){
				var id = this.store.getIdentity(target);
			}else{
				var id = target;
				target = this._rowIdToObject[this.id + "-row-" + id];
			}
			return new Row(id, target, byId(this.id + "-row-" + id));
		},
		rowByIndex: function(index){

		}
	});
});<commit_msg>Added getCSSClass to construct class name<commit_after>define(["dojo/_base/html", "dojo/_base/declare", "dojo/on", "dojo/aspect", "./TextEdit", "dojo/has", "dojo/has!touch?./TouchScroll", "cssx/css!./css/d-list.css"], function(dojo, declare, listen, aspect, TextEdit, has, TouchScroll){
	// allow for custom CSS class definitions
	// TODO: figure out what to depend for this
	var byId = function(id){
		return document.getElementById(id);
	};
	var create = dojo.create;
	function Row(id, object, element){
		this.id = id;
		this.data = object;
		this.element = element;
	}
	return declare(TouchScroll ? [TouchScroll] : [], {
		constructor: function(params, srcNodeRef){
		var self = this;
		if(typeof params == "function"){
			// mixins/plugins are being provided, we will mix then into the instance
			var i = 0, mixin;
			while(typeof (mixin = arguments[i++]) == "function"){
				dojo.safeMixin(this, mixin.prototype);
			}
			// shift the arguments to get the params and srcNodeRef for the new instantiation
			params = arguments[i - 1];
			srcNodeRef = arguments[i];
		}
		// summary:
		//		The set of observers for the data
		this.observers = [];
		this._listeners = [];
		this._rowIdToObject = {};
	/* TODO: Implement this to hide (detach from DOM) out-of-sight nodes to improve performance
	 * clearTop = function(){
		var scrollNode = self.bodyNode;
		var transform = self.contentNode.style.webkitTransform;
		var visibleTop = scrollNode.scrollTop + (transform ? -transform.match(/translate[\w]*\(.*?,(.*?)px/)[1] : 0);

		var elements = self.contentNode.childNodes;
		for(var i = 0; i < elements.length; i++){
			if(elements[i].offsetTop > visibleTop){
				break;
			}
		}
		self.otherNode = create("div", {
		});
		var last = elements[i];
		for(; i > 0; i--){
			self.otherNode.appendChild(elements[i -1]);
		}
		var node = create("div", {
			style: {
				height: visibleTop + "px"
			}
		});
		self.contentNode.insertBefore(node, last);
	};*/
			this.create(params, srcNodeRef);
		},
		minRowsPerPage: 25,
		maxRowsPerPage: 100,
		maxEmptySpace: 10000,
		queryOptions: {},
		query: {},
		createNode: create,
		rowHeight: 0,
		getCSSClass: function(shortName){
			return "d-list-" + shortName;
		},
		create: function(params, srcNodeRef){
			var domNode = this.domNode = srcNodeRef.nodeType ? srcNodeRef : byId(srcNodeRef);
			if(!this.id){
				this.id = domNode.id;
			}
			this.tabIndex = domNode.getAttribute("tabindex") || 0;
			domNode.role = "grid";
			if(params){
				this.params = params;
				dojo.safeMixin(this, params);
			}

			if(domNode.tagName == "table"){
				// TODO: read columns from table
			}
			domNode.className += "	ui-widget-content d-list";
			this.refresh();
		},
		refresh: function(){
			var headerNode = this.headerNode = create("div",{
				className: "d-list-header d-list-header-row"
			},this.domNode);
			var bodyNode = this.bodyNode = create("div",{
				className: "d-list-scroller"
			},this.domNode);
			listen(bodyNode, "scroll", function(event){
				// keep the header aligned with the body
				headerNode.scrollLeft = bodyNode.scrollLeft;
			});
			this.renderHeader();
			bodyNode.style.top = headerNode.offsetHeight + "px";
			if(dojo.isQuirks){
				// in quirks mode, the "bottom" CSS property is ignored, so do this to fix it
				// We might want to use a CSS expression or the cssx package to fix this
				bodyNode.style.height = (this.domNode.offsetHeight - headerNode.offsetHeight) + "px";
			}
			this.refreshContent();
			aspect.after(this, "scrollTo", this.onscroll);
			this.postCreate && this.postCreate();
		},
		on: function(eventType, listener){
			// delegate events to the domNode
			var signal = listen(this.domNode, eventType, listener);
			if(has("dom-addeventlistener")){
				this._listeners.push(signal);
			}
		},
		destroy: function(){
			// cleanup listeners
			for(var i = 0; i < this._listeners.length; i++){
				this._listeners.cancel();
			}
		},
		refreshContent: function(){
			// summary:
			//		refreshes the contents of the grid
			if(this.contentNode){
				// remove the content so it can be recreated
				this.contentNode.innerHTML = "";
				// remove any listeners
				for(var i = 0;i < this.observers.length; i++){
					this.observers[i].cancel();
				}
				this.observers = [];
			}else{
				this.contentNode = create("div",{
					className:"d-list-content"
				}, this.bodyNode);
			}
			if(this.init){
				this.init({
					domNode: this.bodyNode,
					containerNode: this.contentNode
				});
			}
			this.preloadNode = null;
		},
		renderCollection: function(results, beforeNode, options){
			// summary:
			//		This renders an array or collection of objects as rows in the grid, before the
			//		given node. This will listen for changes in the collection if an observe method
			//		is available (as it should be if it comes from an Observable data store).
			options = options || {};
			var start = options.start || 0;
			var self = this;
			var contentNode = this.contentNode;
			if(results.observe){
				// observe the results for changes
				this.observers.push(results.observe(function(object, from, to){
					// a change in the data took place
					if(from > -1){
						// remove from old slot
						var row = rows.splice(from, 1)[0];
						contentNode.removeChild(row);
					}
					if(to > -1){
						// add to new slot
						var row = self.createRow(object, rows[to], (options.start + to), options);
						dojo.addClass(row, "ui-state-highlight");
						setTimeout(function(){
							dojo.removeClass(row, "ui-state-highlight");
						}, 250);
						rows.splice(to, 0, row);
					}
				}));
			}
			// now render the results
			if(results.map){
				var rows = results.map(mapEach, console.error);
			}else{
				var rows = [];
				for(var i = 0, l = results.length; i < l; i++){
					rows[i] = mapEach(results[i]);
				}
			}
			function mapEach(object){
				return self.createRow(object, beforeNode, start++, options);
			}
			return rows;
		},
		_autoId: 0,
		renderHeader: function(){
			// no-op in a place list
		},
		createRow: function(object, beforeNode, i, options){
			// summary:
			//		Renders a single row in the grid
			var row = this.renderRow(object, options);
			row.className = (row.className || "") + " ui-state-default d-list-row " + (i% 2 == 1 ? "d-list-row-odd" : "d-list-row-even");
			// get the row id for easy retrieval
			this._rowIdToObject[row.id = this.id + "-row-" + ((this.store && this.store.getIdentity) ? this.store.getIdentity(object) : this._autoId++)] = object;
			this.contentNode.insertBefore(row, beforeNode);
			return row;
		},
		renderRow: function(value, options){
			return dojo.create("div", {
				innerHTML: value,
				tabIndex: this.tabIndex
			});
		},
		row: function(target){
			// summary:
			//		Get the row object by id, object, node, or event
			if(target.target && target.target.nodeType == 1){
				// event
				target = target.target;
			}
			if(target.nodeType == 1){
				var object;
				do{
					var rowId = target.id;
					if(object = this._rowIdToObject[rowId]){
						return new Row(rowId.substring(rowId.indexOf("-row-") + 5), object, target);
					}
					target = target.parentNode;
				}while(target && target != this.domNode);
				return;
			}
			if(typeof target == "object"){
				var id = this.store.getIdentity(target);
			}else{
				var id = target;
				target = this._rowIdToObject[this.id + "-row-" + id];
			}
			return new Row(id, target, byId(this.id + "-row-" + id));
		},
		rowByIndex: function(index){

		}
	});
});<|endoftext|>


<commit_before>'use strict';

function audio_create(id, properties){
    audio_audio[id] = {};
    audio_audio[id]['playing'] = false;

    for(var property in properties){
        audio_audio[id][property] = properties[property];
    }

    audio_audio[id]['connections'] = properties['connections'] || [
      {
        'frequency': {
          'value': audio_audio[id]['frequency'] || 100,
        },
        'id': id,
        'label': 'Oscillator',
        'onended': function(){
            audio_onended(this);
        },
        'type': audio_audio[id]['type'] || 'sine',
      },
    ];
}

function audio_init(default_volume){
    audio_context = new window.AudioContext();
    audio_volume = default_volume !== void 0
      ? default_volume
      : 1;
}

function audio_node_create(id, properties){
    var source = audio_context['create' + properties['label']](
      properties['arg0'],
      properties['arg1'],
      properties['arg2']
    );

    for(var property in properties){
        if(typeof properties[property] === 'object'){
            for(var subproperty in properties[property]){
                source[property][subproperty] = properties[property][subproperty];
            }

        }else{
            source[property] = properties[property];
        }
    }

    audio_sources[id][properties['label']] = source;
}

function audio_onended(that){
    audio_audio[that.id]['playing'] = false;

    if(audio_audio[that.id]['repeat']){
        if(audio_audio[that.id]['timeout'] <= 0){
            audio_start(that.id);
f
        }else{
            window.setTimeout(
              'audio_start("' + that.id + '");',
              audio_audio[that.id]['duration'] * audio_audio[that.id]['timeout']
            );
        }
    }

    delete audio_sources[that.id];
}

function audio_source_create(id, volume_multiplier){
    audio_sources[id] = {
      'duration': audio_audio[id]['duration'] || 0,
      'start': audio_audio[id]['start'] || 0,
      'timeout': audio_audio[id]['timeout'] || 1000,
    };

    var connections_length = audio_audio[id]['connections'].length;
    var volume = audio_audio[id]['volume'] || audio_volume;
    volume_multiplier = volume_multiplier !== void 0
      ? volume_multiplier
      : false;
    if(volume_multiplier !== false){
        volume *= volume_multiplier;
    }

    // Create audio nodes.
    for(var i = 0; i < connections_length; i++){
        audio_node_create(
          id,
          audio_audio[id]['connections'][i]
        );
    }
    audio_node_create(
      id,
      {
        'gain': {
          'value': volume,
        },
        'label': 'Gain',
      }
    );

    // Connect audio nodes.
    if(connections_length > 2){
        for(i = 0; i < connections_length - 1; i++){
            audio_sources[id][audio_audio[id]['connections'][i]['label']].connect(audio_sources[id][audio_audio[id]['connections'][i + 1]['label']]);
        }
    }
    audio_sources[id][audio_audio[id]['connections'][connections_length - 1]['label']].connect(audio_sources[id]['Gain']);
    audio_sources[id]['Gain'].connect(audio_context.destination);
}

function audio_start(id, volume_multiplier){
    if(volume_multiplier === 0){
        return;
    }

    if(audio_audio[id]['playing']){
        audio_stop(id);
    }

    audio_source_create(
      id,
      volume_multiplier
    );

    var startTime = audio_context.currentTime + audio_sources[id]['start'];
    audio_audio[id]['playing'] = true;
    audio_sources[id][audio_audio[id]['connections'][0]['label']].start(startTime);
    audio_stop(
      id,
      startTime + audio_sources[id]['duration']
    );
}

function audio_stop(id, when){
    audio_sources[id][audio_audio[id]['connections'][0]['label']].stop(when || void 0);
}

function audio_stop_all(){
    for(var id in audio_sources){
        audio_stop(id);
    }
}

var audio_audio = {};
var audio_context = 0;
var audio_sources = {};
var audio_volume = 1;
<commit_msg>made gain not built in<commit_after>'use strict';

function audio_create(id, properties){
    audio_audio[id] = {};
    audio_audio[id]['playing'] = false;

    for(var property in properties){
        audio_audio[id][property] = properties[property];
    }

    audio_audio[id]['connections'] = properties['connections'] || [
      {
        'frequency': {
          'value': audio_audio[id]['frequency'] || 100,
        },
        'id': id,
        'label': 'Oscillator',
        'onended': function(){
            audio_onended(this);
        },
        'type': audio_audio[id]['type'] || 'sine',
      },
      {
        'gain': {
          'value': properties['volume'] || audio_volume,
        },
        'label': 'Gain',
      },
    ];
}

function audio_init(default_volume){
    audio_context = new window.AudioContext();
    audio_volume = default_volume !== void 0
      ? default_volume
      : 1;
}

function audio_node_create(id, properties){
    var source = audio_context['create' + properties['label']](
      properties['arg0'],
      properties['arg1'],
      properties['arg2']
    );

    for(var property in properties){
        if(typeof properties[property] === 'object'){
            for(var subproperty in properties[property]){
                source[property][subproperty] = properties[property][subproperty];
            }

        }else{
            source[property] = properties[property];
        }
    }

    audio_sources[id][properties['label']] = source;
}

function audio_onended(that){
    audio_audio[that.id]['playing'] = false;

    if(audio_audio[that.id]['repeat']){
        if(audio_audio[that.id]['timeout'] <= 0){
            audio_start(that.id);
f
        }else{
            window.setTimeout(
              'audio_start("' + that.id + '");',
              audio_audio[that.id]['duration'] * audio_audio[that.id]['timeout']
            );
        }
    }

    delete audio_sources[that.id];
}

function audio_source_create(id, volume_multiplier){
    audio_sources[id] = {
      'duration': audio_audio[id]['duration'] || 0,
      'start': audio_audio[id]['start'] || 0,
      'timeout': audio_audio[id]['timeout'] || 1000,
    };

    // Create audio nodes.
    var connections_length = audio_audio[id]['connections'].length;
    for(var i = 0; i < connections_length; i++){
        audio_node_create(
          id,
          audio_audio[id]['connections'][i]
        );

        if(audio_audio[id]['connections'][i]['label'] === 'Gain'){
            var volume = audio_audio[id]['volume'] || audio_volume;
            volume_multiplier = volume_multiplier !== void 0
              ? volume_multiplier
              : false;
            if(volume_multiplier !== false){
                volume *= volume_multiplier;
            }
            audio_sources[id]['Gain']['gain']['value'] = volume;
        }
    }

    // Connect audio nodes.
    for(i = 0; i < connections_length - 1; i++){
        audio_sources[id][audio_audio[id]['connections'][i]['label']].connect(audio_sources[id][audio_audio[id]['connections'][i + 1]['label']]);
    }
    audio_sources[id][audio_audio[id]['connections'][connections_length - 1]['label']].connect(audio_context.destination);
}

function audio_start(id, volume_multiplier){
    if(volume_multiplier === 0){
        return;
    }

    if(audio_audio[id]['playing']){
        audio_stop(id);
    }

    audio_source_create(
      id,
      volume_multiplier
    );

    var startTime = audio_context.currentTime + audio_sources[id]['start'];
    audio_audio[id]['playing'] = true;
    audio_sources[id][audio_audio[id]['connections'][0]['label']].start(startTime);
    audio_stop(
      id,
      startTime + audio_sources[id]['duration']
    );
}

function audio_stop(id, when){
    audio_sources[id][audio_audio[id]['connections'][0]['label']].stop(when || void 0);
}

function audio_stop_all(){
    for(var id in audio_sources){
        audio_stop(id);
    }
}

var audio_audio = {};
var audio_context = 0;
var audio_sources = {};
var audio_volume = 1;
<|endoftext|>


<commit_before>// @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2-or-later
/*! cheval v1.2.0 by ryanpcmcquen */
// Ryan P.C. McQuen | Everett, WA | ryanpcmcquen@member.fsf.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version, with the following exception:
// the text of the GPL license may be omitted.
//
// This program is distributed in the hope that it will be useful, but
// without any warranty; without even the implied warranty of
// merchantability or fitness for a particular purpose. Compiling,
// interpreting, executing or merely reading the text of the program
// may result in lapses of consciousness and/or very being, up to and
// including the end of all existence and the Universe as we know it.
// See the GNU General Public License for more details.
//
// You may have received a copy of the GNU General Public License along
// with this program (most likely, a file named COPYING).  If not, see
// <https://www.gnu.org/licenses/>.
/*global window*/
/*jslint browser:true*/
(function () {
    "use strict";

    var textClassName = "text-to-copy";
    var buttonClassName = "js-copy-btn";
    var allowButtonTextToChange = true;
    var afterCopyText = {
        desktop: "Copy again",
        iPad: "Now tap the text, then 'Copy'",
        iPhoneOriPod: "Now tap 'Copy'",
        oldSafari: "Press Command + C to copy",
        notSupported: "Please copy manually"
    };
    var sets = {};
    var regexBuilder = function (prefix) {
        return new RegExp(prefix + "\\S*");
    };

    window.addEventListener("DOMContentLoaded", function () {
        var texts = Array.prototype.slice.call(document.querySelectorAll(
            "[class*=" + textClassName + "]"
        ));
        var buttons = Array.prototype.slice.call(document.querySelectorAll(
            "[class*=" + buttonClassName + "]"
        ));

        var classNameFinder = function (arr, regex, namePrefix) {
            return arr.map(function (item) {
                return (item.className.match(regex))
                    ? item.className.match(regex)[0].replace(
                        namePrefix,
                        ""
                    )
                    : false;
            }).sort();
        };

        sets.texts = classNameFinder(
            texts,
            regexBuilder(textClassName),
            textClassName
        );

        sets.buttons = classNameFinder(
            buttons,
            regexBuilder(buttonClassName),
            buttonClassName
        );

        var matches = sets.texts.map(function (ignore, index) {
            return sets.texts[index].match(sets.buttons[
                index
            ]);
        });

        var throwErr = function (err) {
            throw new Error(err);
        };
        var iPhoneORiPod = false;
        var iPad = false;
        var oldSafari = false;
        var navAgent = window.navigator.userAgent;
        if (
            (/^((?!chrome).)*safari/i).test(navAgent) &&
            // ^ Fancy safari detection thanks to: https://stackoverflow.com/a/23522755
            !(/^((?!chrome).)*[0-9][0-9](\.[0-9][0-9]?)?\ssafari/i)
                .test(navAgent)
            // ^ Even fancier Safari < 10 detection thanks to regex.  :^)
        ) {
            oldSafari = true;
        }
        // We need to test for older Safari and the device,
        // because of quirky awesomeness.
        if (navAgent.match(/iPhone|iPod/i)) {
            iPhoneORiPod = true;
        } else if (navAgent.match(/iPad/i)) {
            iPad = true;
        }
        var cheval = function (btn, text) {
            var copyBtn = document.querySelector(btn);

            var setCopyBtnText = function (textToSet) {
                copyBtn.textContent = textToSet;
            };
            if (iPhoneORiPod || iPad) {
                if (oldSafari) {
                    setCopyBtnText("Select text");
                }
            }
            if (copyBtn) {
                copyBtn.addEventListener("click", function () {
                    var oldPosX = window.scrollX;
                    var oldPosY = window.scrollY;
                    // Clone the text-to-copy node so that we can
                    // create a hidden textarea, with its text value.
                    // Thanks to @LeaVerou for the idea.
                    var originalCopyItem = document.querySelector(
                        text
                    );
                    var dollyTheSheep = originalCopyItem.cloneNode(true);
                    var copyItem = document.createElement(
                        "textarea"
                    );
                    copyItem.style.opacity = 0;
                    copyItem.style.position = "absolute";
                    // If .value is undefined, .textContent will
                    // get assigned to the textarea we made.
                    var copyValue = dollyTheSheep.value || dollyTheSheep.textContent;
                    copyItem.value = copyValue;
                    document.body.appendChild(copyItem);
                    if (copyItem) {
                        // Select the text:
                        copyItem.focus();
                        copyItem.selectionStart = 0;
                        // For some reason the 'copyItem' does not get
                        // the correct length, so we use the OG.
                        copyItem.selectionEnd = copyValue.length;
                        try {
                            // Now that we've selected the text, execute the copy command:
                            document.execCommand("copy");
                            // And disable the cloned area to prevent jumping.
                            // This has to come after the `copy` command.
                            copyItem.setAttribute(
                                "disabled",
                                true
                            );
                            // Allow the button text to be changed.
                            // Set `allowButtonTextToChange = false` to leave it alone.
                            // Default is `true`.
                            // Thanks to @jasondavis.
                            if (allowButtonTextToChange) {
                                if (oldSafari) {
                                    if (iPhoneORiPod) {
                                        setCopyBtnText(
                                            afterCopyText.iPhoneOriPod
                                        );
                                    } else if (iPad) {
                                        // The iPad doesn't have the 'Copy' box pop up,
                                        // you have to tap the text first.
                                        setCopyBtnText(
                                            afterCopyText.iPad
                                        );
                                    } else {
                                        // Just old!
                                        setCopyBtnText(
                                            afterCopyText.oldSafari
                                        );
                                    }
                                } else {
                                    setCopyBtnText(
                                        afterCopyText.desktop
                                    );
                                }
                            }
                        } catch (ignore) {
                            if (allowButtonTextToChange) {
                              setCopyBtnText(
                                  afterCopyText.notSupported
                              );
                            }
                        }
                        originalCopyItem.focus();
                        // Restore the user's original position to avoid
                        // 'jumping' when they click a copy button.
                        window.scrollTo(
                            oldPosX,
                            oldPosY
                        );
                        originalCopyItem.selectionStart = 0;
                        originalCopyItem.selectionEnd = copyValue.length;
                        copyItem.remove();
                    } else {
                        throwErr(
                            "You don't have an element with the class: '" +
                            textClassName +
                            "'. Please check the cheval README."
                        );
                    }
                });
            } else {
                throwErr(
                    "You don't have a <button> with the class: '" +
                    buttonClassName +
                    "'. Please check the cheval README."
                );
            }
        };

        // Copy all sets of elements and buttons:
        matches.forEach(function (i) {
            return cheval(
                "." + buttonClassName + i,
                "." + textClassName + i
            );
        });

    });

}());
// @license-end
<commit_msg>Blur to input element after copying on newer iOS devices.<commit_after>// @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2-or-later
/*! cheval v1.2.0 by ryanpcmcquen */
// Ryan P.C. McQuen | Everett, WA | ryanpcmcquen@member.fsf.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version, with the following exception:
// the text of the GPL license may be omitted.
//
// This program is distributed in the hope that it will be useful, but
// without any warranty; without even the implied warranty of
// merchantability or fitness for a particular purpose. Compiling,
// interpreting, executing or merely reading the text of the program
// may result in lapses of consciousness and/or very being, up to and
// including the end of all existence and the Universe as we know it.
// See the GNU General Public License for more details.
//
// You may have received a copy of the GNU General Public License along
// with this program (most likely, a file named COPYING).  If not, see
// <https://www.gnu.org/licenses/>.
/*global window*/
/*jslint browser:true*/
(function () {
    "use strict";

    var textClassName = "text-to-copy";
    var buttonClassName = "js-copy-btn";
    var allowButtonTextToChange = true;
    var afterCopyText = {
        desktop: "Copy again",
        iPad: "Now tap the text, then 'Copy'",
        iPhoneOriPod: "Now tap 'Copy'",
        oldSafari: "Press Command + C to copy",
        notSupported: "Please copy manually"
    };
    var sets = {};
    var regexBuilder = function (prefix) {
        return new RegExp(prefix + "\\S*");
    };

    window.addEventListener("DOMContentLoaded", function () {
        var texts = Array.prototype.slice.call(document.querySelectorAll(
            "[class*=" + textClassName + "]"
        ));
        var buttons = Array.prototype.slice.call(document.querySelectorAll(
            "[class*=" + buttonClassName + "]"
        ));

        var classNameFinder = function (arr, regex, namePrefix) {
            return arr.map(function (item) {
                return (item.className.match(regex))
                    ? item.className.match(regex)[0].replace(
                        namePrefix,
                        ""
                    )
                    : false;
            }).sort();
        };

        sets.texts = classNameFinder(
            texts,
            regexBuilder(textClassName),
            textClassName
        );

        sets.buttons = classNameFinder(
            buttons,
            regexBuilder(buttonClassName),
            buttonClassName
        );

        var matches = sets.texts.map(function (ignore, index) {
            return sets.texts[index].match(sets.buttons[
                index
            ]);
        });

        var throwErr = function (err) {
            throw new Error(err);
        };
        var iPhoneORiPod = false;
        var iPad = false;
        var oldSafari = false;
        var navAgent = window.navigator.userAgent;
        if (
            (/^((?!chrome).)*safari/i).test(navAgent) &&
            // ^ Fancy safari detection thanks to: https://stackoverflow.com/a/23522755
            !(/^((?!chrome).)*[0-9][0-9](\.[0-9][0-9]?)?\ssafari/i)
                .test(navAgent)
            // ^ Even fancier Safari < 10 detection thanks to regex.  :^)
        ) {
            oldSafari = true;
        }
        // We need to test for older Safari and the device,
        // because of quirky awesomeness.
        if (navAgent.match(/iPhone|iPod/i)) {
            iPhoneORiPod = true;
        } else if (navAgent.match(/iPad/i)) {
            iPad = true;
        }
        var cheval = function (btn, text) {
            var copyBtn = document.querySelector(btn);

            var setCopyBtnText = function (textToSet) {
                copyBtn.textContent = textToSet;
            };
            if (iPhoneORiPod || iPad) {
                if (oldSafari) {
                    setCopyBtnText("Select text");
                }
            }
            if (copyBtn) {
                copyBtn.addEventListener("click", function () {
                    var oldPosX = window.scrollX;
                    var oldPosY = window.scrollY;
                    // Clone the text-to-copy node so that we can
                    // create a hidden textarea, with its text value.
                    // Thanks to @LeaVerou for the idea.
                    var originalCopyItem = document.querySelector(
                        text
                    );
                    var dollyTheSheep = originalCopyItem.cloneNode(true);
                    var copyItem = document.createElement(
                        "textarea"
                    );
                    copyItem.style.opacity = 0;
                    copyItem.style.position = "absolute";
                    // If .value is undefined, .textContent will
                    // get assigned to the textarea we made.
                    var copyValue = dollyTheSheep.value || dollyTheSheep.textContent;
                    copyItem.value = copyValue;
                    document.body.appendChild(copyItem);
                    if (copyItem) {
                        // Select the text:
                        copyItem.focus();
                        copyItem.selectionStart = 0;
                        // For some reason the 'copyItem' does not get
                        // the correct length, so we use the OG.
                        copyItem.selectionEnd = copyValue.length;
                        try {
                            // Now that we've selected the text, execute the copy command:
                            document.execCommand("copy");
                            // And disable the cloned area to prevent jumping.
                            // This has to come after the `copy` command.
                            copyItem.setAttribute(
                                "disabled",
                                true
                            );
                            // Allow the button text to be changed.
                            // Set `allowButtonTextToChange = false` to leave it alone.
                            // Default is `true`.
                            // Thanks to @jasondavis.
                            if (allowButtonTextToChange) {
                                if (oldSafari) {
                                    if (iPhoneORiPod) {
                                        setCopyBtnText(
                                            afterCopyText.iPhoneOriPod
                                        );
                                    } else if (iPad) {
                                        // The iPad doesn't have the 'Copy' box pop up,
                                        // you have to tap the text first.
                                        setCopyBtnText(
                                            afterCopyText.iPad
                                        );
                                    } else {
                                        // Just old!
                                        setCopyBtnText(
                                            afterCopyText.oldSafari
                                        );
                                    }
                                } else {
                                    document.activeElement.blur();
                                    setCopyBtnText(
                                        afterCopyText.desktop
                                    );
                                }
                            }
                        } catch (ignore) {
                            if (allowButtonTextToChange) {
                              setCopyBtnText(
                                  afterCopyText.notSupported
                              );
                            }
                        }
                        originalCopyItem.focus();
                        // Restore the user's original position to avoid
                        // 'jumping' when they click a copy button.
                        window.scrollTo(
                            oldPosX,
                            oldPosY
                        );
                        originalCopyItem.selectionStart = 0;
                        originalCopyItem.selectionEnd = copyValue.length;
                        copyItem.remove();
                    } else {
                        throwErr(
                            "You don't have an element with the class: '" +
                            textClassName +
                            "'. Please check the cheval README."
                        );
                    }
                });
            } else {
                throwErr(
                    "You don't have a <button> with the class: '" +
                    buttonClassName +
                    "'. Please check the cheval README."
                );
            }
        };

        // Copy all sets of elements and buttons:
        matches.forEach(function (i) {
            return cheval(
                "." + buttonClassName + i,
                "." + textClassName + i
            );
        });

    });

}());
// @license-end
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Evolveum
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * http://www.opensource.org/licenses/cddl1 or
 * CDDLv1.0.txt file in the source code distribution.
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 *
 * Portions Copyrighted 2012 [name of copyright owner]
 */

function initMessages() {
	$("a").click(function(){
		$(".messagesTop").fadeOut(200,function(){
			$(".messagesTop").remove();
		});
	});

	$(".messagesTop").find(".messages-topPanel").each(function(index){
		var arrow;
		var className = $(this).attr('class');
		if(className.indexOf("messages-topError") >= 0){
			arrow = "messages-topError";
		} else if(className.indexOf("messages-topSucc") >= 0){
			arrow = "messages-topSucc";
		} else if(className.indexOf("messages-topWarn") >= 0){
			arrow = "messages-topWarn";
		} else {
			arrow = "messages-topInfo";
		}

		var blockContent = $("#" + $(this).attr('id') + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).append("");
				if($(this).height() <= 16){
					$("." + arrow +"-arrow").css("marginTop", 0);
				}
			}
		}
	});

	//$(document).find("messages-topError");
	$(".messages-topError").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#FFC2AE");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#FFD7CA");
		}
	});

	$(".messages-topSucc").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#d1eba6");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#dff2bf");
		}
	});

	$(".messages-topWarn").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#fce48d");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#FEEFB3");
		}
	});

	$(".messages-topInfo").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#c3bfff");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#d2d1ff");
		}
	});

	$(".messages-topError").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topError-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topError-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topSucc").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topSucc-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topSucc-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topWarn").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topWarn-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topWarn-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topInfo").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topInfo-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topInfo-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-details-bold").click(function(){
		var idBlock = $(this).attr("id");
		if($(this).parent().find(".messages-details-content").css("display") === "none"){
			$(this).parent().parent().addClass("selected-section");
			$("#"+idBlock+"_content").show();
			$("#"+idBlock+"_arrow").addClass("arrow-down");
		} else {
			$(this).parent().parent().removeClass("selected-section");
			$("#"+idBlock+"_content").hide();
			$("#"+idBlock+"_arrow").removeClass("arrow-down");
		}
	});

	$(".errorStack").click(function(){
		var idBlock = $(this).attr("id");
		var text = "";
		if($("#"+idBlock+"_content").css("display") === "none"){
			text = $(this).text().replace("SHOW","HIDE");
			$("#"+idBlock+"_content").show();
		} else {
			$("#"+idBlock+"_content").hide();
			text = $(this).text().replace("HIDE","SHOW");
		}
		$(this).text(text);
	});
}

<commit_msg>Fixed bug with removing old messagePanel.<commit_after>/*
 * Copyright (c) 2012 Evolveum
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * http://www.opensource.org/licenses/cddl1 or
 * CDDLv1.0.txt file in the source code distribution.
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 *
 * Portions Copyrighted 2012 [name of copyright owner]
 */

function initMessages() {
	$("a").click(function(){
		$(".messagesTop").remove();
	});

	$(".messagesTop").find(".messages-topPanel").each(function(index){
		var arrow;
		var className = $(this).attr('class');
		if(className.indexOf("messages-topError") >= 0){
			arrow = "messages-topError";
		} else if(className.indexOf("messages-topSucc") >= 0){
			arrow = "messages-topSucc";
		} else if(className.indexOf("messages-topWarn") >= 0){
			arrow = "messages-topWarn";
		} else {
			arrow = "messages-topInfo";
		}

		var blockContent = $("#" + $(this).attr('id') + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).append("");
				if($(this).height() <= 16){
					$("." + arrow +"-arrow").css("marginTop", 0);
				}
			}
		}
	});

	//$(document).find("messages-topError");
	$(".messages-topError").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#FFC2AE");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#FFD7CA");
		}
	});

	$(".messages-topSucc").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#d1eba6");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#dff2bf");
		}
	});

	$(".messages-topWarn").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#fce48d");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#FEEFB3");
		}
	});

	$(".messages-topInfo").mouseenter(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.length > 0){
			if(blockContent.find("ul:first").children().size() > 0){
				$(this).css("backgroundColor","#c3bfff");
				$(this).css("cursor","pointer");
			}
		}
	}).mouseleave(function(){
		if(!($(this).attr("class").indexOf("selected") >= 0)){
			$(this).css("backgroundColor","#d2d1ff");
		}
	});

	$(".messages-topError").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topError-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topError-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topSucc").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topSucc-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topSucc-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topWarn").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topWarn-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topWarn-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-topInfo").click(function(){
		var idBlock = $(this).attr("id");
		var blockContent = $("#" + idBlock + "_content");
		if(blockContent.find("ul:first").children().size() > 0){
			if(blockContent.css("display") === "none"){
				blockContent.show();
				$(this).find(".messages-topInfo-arrow").addClass("arrow-up");
				$(this).addClass("selected");
			} else {
				blockContent.hide();
				$(this).find(".messages-topInfo-arrow").removeClass("arrow-up");
				$(this).removeClass("selected");
			}
		}
	});

	$(".messages-details-bold").click(function(){
		var idBlock = $(this).attr("id");
		if($(this).parent().find(".messages-details-content").css("display") === "none"){
			$(this).parent().parent().addClass("selected-section");
			$("#"+idBlock+"_content").show();
			$("#"+idBlock+"_arrow").addClass("arrow-down");
		} else {
			$(this).parent().parent().removeClass("selected-section");
			$("#"+idBlock+"_content").hide();
			$("#"+idBlock+"_arrow").removeClass("arrow-down");
		}
	});

	$(".errorStack").click(function(){
		var idBlock = $(this).attr("id");
		var text = "";
		if($("#"+idBlock+"_content").css("display") === "none"){
			text = $(this).text().replace("SHOW","HIDE");
			$("#"+idBlock+"_content").show();
		} else {
			$("#"+idBlock+"_content").hide();
			text = $(this).text().replace("HIDE","SHOW");
		}
		$(this).text(text);
	});
}

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Daniel Cohen Gindi (danielgindi@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* global DGTable, _, Backbone */
DGTable.RowCollection = (function () {
    'use strict';

    // Define class RowCollection
    var RowCollection = function() {

        // Instantiate an Array. Seems like the `.length = ` of an inherited Array does not work well.
        // I will not use the IFRAME solution either in fear of memory leaks, and we're supporting large datasets...
        var collection = [];

        // Synthetically set the 'prototype'
        _.extend(collection, RowCollection.prototype);

        // Call initializer
        collection.initialize.apply(collection, arguments);

        return collection;
    };

    // Inherit Array
    RowCollection.prototype = [];

    // Add events model from Backbone
    _.extend(RowCollection.prototype, Backbone.Events);

    RowCollection.prototype.initialize = function(options) {

        options = options || {};

        /** @field {String} filterColumn */
        this.filterColumn = null;

        /** @field {String} filterString */
        this.filterString = null;

        /** @field {Boolean} filterCaseSensitive */
        this.filterCaseSensitive = false;

        /** @field {string} sortColumn */
        this.sortColumn = options.sortColumn == null ? [] : options.sortColumn;
    };

    /**
     * @param {Object|Object[]} rows Row or array of rows to add to this collection
     * @param {number?} at Position to insert rows. This will prevent the sort if it is active.
     */
    RowCollection.prototype.add = function (rows, at) {
        var isArray = ('splice' in rows && 'length' in rows), i, len;
        if (isArray) {
            if (at) {
                for (i = 0, len = rows.length; i < len; i++) {
                    this.splice(at++, 0, rows[i]);
                }
            } else {
                for (i = 0, len = rows.length; i < len; i++) {
                    this.push(rows[i]);
                }
            }
        } else {
            if (at) {
                this.splice(at, 0, rows);
            } else {
                this.push(rows);
            }
        }
    };

    /**
     * @param {Object|Object[]=} rows Row or array of rows to add to this collection
     */
    RowCollection.prototype.reset = function (rows) {
        this.length = 0;
        if (rows) {
            this.add(rows);
        }
    };

    /**
     * @param {string} columnName name of the column to filter on
     * @param {string} filter keyword to filter by
     * @param {boolean=false} caseSensitive is the filter case sensitive?
     * @returns {DGTable.RowCollection} success result
     */
    RowCollection.prototype.filteredCollection = function (columnName, filter, caseSensitive) {
        filter = filter.toString();
        if (filter && columnName != null) {
            var rows = new RowCollection({ sortColumn: this.sortColumn });
            this.filterColumn = columnName;
            this.filterString = filter;
            this.filterCaseSensitive = caseSensitive;
            var originalRowIndex = 0;
            for (var i = 0, len = this.length, row; i < len; i++) {
                row = this[i];
                if (this.shouldBeVisible(row)) {
                    row['__i'] = originalRowIndex++;
                    rows.push(row);
                }
            }
            return rows;
        } else {
            this.filterColumn = null;
            this.filterString = null;
            return null;
        }
    };

    /**
     * @param {Array} row
     * @returns {boolean}
     */
    RowCollection.prototype.shouldBeVisible = function (row) {
        if (row && this.filterColumn) {
            var actualVal = row[this.filterColumn];
            if (actualVal == null) {
                return false;
            }
            actualVal = actualVal.toString();
            var filterVal = this.filterString;
            if (!this.filterCaseSensitive) {
                actualVal = actualVal.toUpperCase();
                filterVal = filterVal.toUpperCase();
            }
            return actualVal.indexOf(filterVal) !== -1;
        }
        return true;
    };

    (function(){
        var nativeSort = RowCollection.prototype.sort;

        function getDefaultComparator(column, descending) {
            var lessVal = descending ? 1 : -1, moreVal = descending ? -1 : 1;
            return function(leftRow, rightRow) {
                var col = column, leftVal = leftRow[col], rightVal = rightRow[col];
                return leftVal < rightVal ? lessVal : (leftVal > rightVal ? moreVal : 0);
            };
        }

        /**
         * @param {Boolean=false} silent
         * @returns {DGTable.RowCollection} self
         */
        RowCollection.prototype.sort = function(silent) {
            if (this.sortColumn.length) {
                var comparators = [], i, returnVal;
                for (i = 0; i < this.sortColumn.length; i++) {
                    returnVal = {};
                    this.trigger('requiresComparatorForColumn', returnVal, this.sortColumn[i].column, this.sortColumn[i].descending);
                    comparators.push(_.bind(returnVal.comparator || getDefaultComparator(this.sortColumn[i].column, this.sortColumn[i].descending), this));
                }
                if (comparators.length === 1) {
                    nativeSort.call(this, comparators[0]);
                } else {
                    var len = comparators.length,
                        value,
                        comparator = function(leftRow, rightRow) {
                            for (i = 0; i < len; i++) {
                                value = comparators[i](leftRow, rightRow);
                                if (value !== 0) {
                                    return value;
                                }
                            }
                            return value;
                        };
                    nativeSort.call(this, comparator);
                }

                if (!silent) {
                    this.trigger('sort');
                }
            }
            return this;
        };
    })();

    return RowCollection;

})();<commit_msg>Correctly assigning the original row index<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Daniel Cohen Gindi (danielgindi@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* global DGTable, _, Backbone */
DGTable.RowCollection = (function () {
    'use strict';

    // Define class RowCollection
    var RowCollection = function() {

        // Instantiate an Array. Seems like the `.length = ` of an inherited Array does not work well.
        // I will not use the IFRAME solution either in fear of memory leaks, and we're supporting large datasets...
        var collection = [];

        // Synthetically set the 'prototype'
        _.extend(collection, RowCollection.prototype);

        // Call initializer
        collection.initialize.apply(collection, arguments);

        return collection;
    };

    // Inherit Array
    RowCollection.prototype = [];

    // Add events model from Backbone
    _.extend(RowCollection.prototype, Backbone.Events);

    RowCollection.prototype.initialize = function(options) {

        options = options || {};

        /** @field {String} filterColumn */
        this.filterColumn = null;

        /** @field {String} filterString */
        this.filterString = null;

        /** @field {Boolean} filterCaseSensitive */
        this.filterCaseSensitive = false;

        /** @field {string} sortColumn */
        this.sortColumn = options.sortColumn == null ? [] : options.sortColumn;
    };

    /**
     * @param {Object|Object[]} rows Row or array of rows to add to this collection
     * @param {number?} at Position to insert rows. This will prevent the sort if it is active.
     */
    RowCollection.prototype.add = function (rows, at) {
        var isArray = ('splice' in rows && 'length' in rows), i, len;
        if (isArray) {
            if (at) {
                for (i = 0, len = rows.length; i < len; i++) {
                    this.splice(at++, 0, rows[i]);
                }
            } else {
                for (i = 0, len = rows.length; i < len; i++) {
                    this.push(rows[i]);
                }
            }
        } else {
            if (at) {
                this.splice(at, 0, rows);
            } else {
                this.push(rows);
            }
        }
    };

    /**
     * @param {Object|Object[]=} rows Row or array of rows to add to this collection
     */
    RowCollection.prototype.reset = function (rows) {
        this.length = 0;
        if (rows) {
            this.add(rows);
        }
    };

    /**
     * @param {string} columnName name of the column to filter on
     * @param {string} filter keyword to filter by
     * @param {boolean=false} caseSensitive is the filter case sensitive?
     * @returns {DGTable.RowCollection} success result
     */
    RowCollection.prototype.filteredCollection = function (columnName, filter, caseSensitive) {
        filter = filter.toString();
        if (filter && columnName != null) {
            var rows = new RowCollection({ sortColumn: this.sortColumn });
            this.filterColumn = columnName;
            this.filterString = filter;
            this.filterCaseSensitive = caseSensitive;
            for (var i = 0, len = this.length, row; i < len; i++) {
                row = this[i];
                if (this.shouldBeVisible(row)) {
                    row['__i'] = i;
                    rows.push(row);
                }
            }
            return rows;
        } else {
            this.filterColumn = null;
            this.filterString = null;
            return null;
        }
    };

    /**
     * @param {Array} row
     * @returns {boolean}
     */
    RowCollection.prototype.shouldBeVisible = function (row) {
        if (row && this.filterColumn) {
            var actualVal = row[this.filterColumn];
            if (actualVal == null) {
                return false;
            }
            actualVal = actualVal.toString();
            var filterVal = this.filterString;
            if (!this.filterCaseSensitive) {
                actualVal = actualVal.toUpperCase();
                filterVal = filterVal.toUpperCase();
            }
            return actualVal.indexOf(filterVal) !== -1;
        }
        return true;
    };

    (function(){
        var nativeSort = RowCollection.prototype.sort;

        function getDefaultComparator(column, descending) {
            var lessVal = descending ? 1 : -1, moreVal = descending ? -1 : 1;
            return function(leftRow, rightRow) {
                var col = column, leftVal = leftRow[col], rightVal = rightRow[col];
                return leftVal < rightVal ? lessVal : (leftVal > rightVal ? moreVal : 0);
            };
        }

        /**
         * @param {Boolean=false} silent
         * @returns {DGTable.RowCollection} self
         */
        RowCollection.prototype.sort = function(silent) {
            if (this.sortColumn.length) {
                var comparators = [], i, returnVal;
                for (i = 0; i < this.sortColumn.length; i++) {
                    returnVal = {};
                    this.trigger('requiresComparatorForColumn', returnVal, this.sortColumn[i].column, this.sortColumn[i].descending);
                    comparators.push(_.bind(returnVal.comparator || getDefaultComparator(this.sortColumn[i].column, this.sortColumn[i].descending), this));
                }
                if (comparators.length === 1) {
                    nativeSort.call(this, comparators[0]);
                } else {
                    var len = comparators.length,
                        value,
                        comparator = function(leftRow, rightRow) {
                            for (i = 0; i < len; i++) {
                                value = comparators[i](leftRow, rightRow);
                                if (value !== 0) {
                                    return value;
                                }
                            }
                            return value;
                        };
                    nativeSort.call(this, comparator);
                }

                if (!silent) {
                    this.trigger('sort');
                }
            }
            return this;
        };
    })();

    return RowCollection;

})();<|endoftext|>


<commit_before>/*********************************************
This basic accelerometer example logs a stream
of x, y, and z data from the accelerometer
*********************************************/

var tessel = require('tessel');
var accel = require('../').connect(tessel.port("A"));

// Initialize the accelerometer.
accel.on('connected', function () {
	// Stream accelerometer data
	accel.on('data', function (xyz) {
		console.log("x:", xyz[0].toFixed(2),
      "y:", xyz[1].toFixed(2),
      "z:", xyz[2].toFixed(2));
	});
});
<commit_msg>this RFID code reads, but reads really fast. Will check the code, but committing because this version actually works.<commit_after>/*********************************************
This basic accelerometer example logs a stream
of x, y, and z data from the accelerometer
*********************************************/

var tessel = require('tessel');
var accel = require('../').connect(tessel.port("A"));

// Initialize the accelerometer.
accel.on('connected', function () {
	// Stream accelerometer data
	accel.on('data', function (xyz) {
		console.log("x:", xyz[0].toFixed(2),
      "y:", xyz[1].toFixed(2),
      "z:", xyz[2].toFixed(2));
	});
});<|endoftext|>


<commit_before>import React from "react";
import {
  defaults, assign, isFunction, partialRight, pick, without, isEqual, cloneDeep, get
} from "lodash";
import Events from "./events";
import VictoryTransition from "../victory-transition/victory-transition";

const areVictoryPropsEqual = (a, b) => (
  Object.keys(a).reduce((equal, key) => {
    if (!equal) { return false; } // exit early if inequality found
    const aProp = a[key];
    const bProp = b[key];
    if (key === "sharedEvents") { // go deeper on these props
      return areVictoryPropsEqual(aProp, bProp);
    } else if (key === "getEvents" || key === "getEventState") {
      return true; // mark these props equal at all times
    } else {
      return isEqual(aProp, bProp);
    }
  }, true)
);

export default (WrappedComponent) => {
  return class addEvents extends WrappedComponent {

    componentWillMount() {
      if (isFunction(super.componentWillMount)) {
        super.componentWillMount();
      }
      this.state = this.state || {};
      this.stateCopy = {}; // start with an empty object so any change triggers rerender
      const getScopedEvents = Events.getScopedEvents.bind(this);
      this.getEvents = partialRight(Events.getEvents.bind(this), getScopedEvents);
      this.getEventState = Events.getEventState.bind(this);
      this.setupEvents(this.props);
    }

    shouldComponentUpdate(nextProps, nextState) {
      if (this.props.animating || get(nextProps, "sharedEvents.events.length")) {
        return true;
      }

      const stateChange = !isEqual(this.stateCopy, nextState);
      this.stateCopy = cloneDeep(this.state); // save state copy, as events.js must mutate in-place
      if (stateChange) {
        return true;
      }

      if (!areVictoryPropsEqual(this.props, nextProps)) {
        return true;
      }

      return false;
    }

    componentWillUpdate(newProps) {
      if (isFunction(super.componentWillReceiveProps)) {
        super.componentWillReceiveProps();
      }
      this.setupEvents(newProps);
    }

    setupEvents(props) {
      const { sharedEvents } = props;
      const components = WrappedComponent.expectedComponents;
      this.componentEvents = Events.getComponentEvents(props, components);
      this.getSharedEventState = sharedEvents && isFunction(sharedEvents.getEventState) ?
        sharedEvents.getEventState : () => undefined;
      this.baseProps = this.getBaseProps(props);
      this.dataKeys = Object.keys(this.baseProps).filter((key) => key !== "parent");
      this.hasEvents = props.events || props.sharedEvents || this.componentEvents;
      this.events = this.getAllEvents(props);
    }

    getBaseProps(props) {
      const sharedParentState = this.getSharedEventState("parent", "parent");
      const parentState = this.getEventState("parent", "parent");
      const baseParentProps = defaults({}, parentState, sharedParentState);
      const parentPropsList = baseParentProps.parentControlledProps;
      const parentProps = parentPropsList ? pick(baseParentProps, parentPropsList) : {};
      const modifiedProps = defaults({}, parentProps, props);
      return isFunction(WrappedComponent.getBaseProps) ?
        WrappedComponent.getBaseProps(modifiedProps) : {};
    }

    getAllEvents(props) {
      if (Array.isArray(this.componentEvents)) {
        return Array.isArray(props.events) ?
          this.componentEvents.concat(...props.events) : this.componentEvents;
      }
      return props.events;
    }

    getComponentProps(component, type, index) {
      const { role } = WrappedComponent;
      const key = this.dataKeys && this.dataKeys[index] || index;
      const baseProps = this.baseProps[key][type] || this.baseProps[key];
      if (!baseProps && !this.hasEvents) {
        return undefined;
      }
      if (this.hasEvents) {
        const baseEvents = this.getEvents(this.props, type, key);
        const componentProps = defaults(
          { index, key: `${role}-${type}-${key}` },
          this.getEventState(key, type),
          this.getSharedEventState(key, type),
          component.props,
          baseProps
        );
        const events = defaults(
          {}, Events.getPartialEvents(baseEvents, key, componentProps), componentProps.events
        );
        return assign(
          {}, componentProps, { events }
        );
      }
      return defaults(
        { index, key: `${role}-${type}-${key}` },
        component.props,
        baseProps
      );
    }

    renderContainer(component, children) {
      const isContainer = component.type && component.type.role === "container";
      const parentProps = isContainer ? this.getComponentProps(component, "parent", "parent") : {};
      return React.cloneElement(component, parentProps, children);
    }

    animateComponent(props, animationWhitelist) {
      return (
        <VictoryTransition animate={props.animate} animationWhitelist={animationWhitelist}>
          {React.createElement(this.constructor, props)}
        </VictoryTransition>
      );
    }

    // Used by `VictoryLine` and `VictoryArea`
    renderContinuousData(props) {
      const { dataComponent, labelComponent, groupComponent } = props;
      const dataKeys = without(this.dataKeys, "all");
      const labelComponents = dataKeys.reduce((memo, key) => {
        const labelProps = this.getComponentProps(labelComponent, "labels", key);
        if (labelProps && labelProps.text !== undefined && labelProps.text !== null) {
          memo = memo.concat(React.cloneElement(labelComponent, labelProps));
        }
        return memo;
      }, []);
      const dataProps = this.getComponentProps(dataComponent, "data", "all");
      const children = [React.cloneElement(dataComponent, dataProps), ...labelComponents];
      return this.renderContainer(groupComponent, children);
    }

    renderData(props) {
      const { dataComponent, labelComponent, groupComponent } = props;
      const dataComponents = this.dataKeys.map((_dataKey, index) => {
        const dataProps = this.getComponentProps(dataComponent, "data", index);
        return React.cloneElement(dataComponent, dataProps);
      });

      const labelComponents = this.dataKeys.map((_dataKey, index) => {
        const labelProps = this.getComponentProps(labelComponent, "labels", index);
        if (labelProps.text !== undefined && labelProps.text !== null) {
          return React.cloneElement(labelComponent, labelProps);
        }
        return undefined;
      }).filter(Boolean);

      const children = [...dataComponents, ...labelComponents];
      return this.renderContainer(groupComponent, children);
    }

  };
};
<commit_msg>add comments<commit_after>import React from "react";
import {
  defaults, assign, isFunction, partialRight, pick, without, isEqual, cloneDeep, get
} from "lodash";
import Events from "./events";
import VictoryTransition from "../victory-transition/victory-transition";

const areVictoryPropsEqual = (a, b) => (
  Object.keys(a).reduce((equal, key) => {
    if (!equal) { return false; } // exit early if inequality found
    const aProp = a[key];
    const bProp = b[key];
    if (key === "sharedEvents") { // go deeper on these props
      return areVictoryPropsEqual(aProp, bProp);
    } else if (key === "getEvents" || key === "getEventState") {
      return true; // mark these props equal at all times
    } else {
      return isEqual(aProp, bProp);
    }
  }, true)
);

export default (WrappedComponent) => {
  return class addEvents extends WrappedComponent {

    componentWillMount() {
      if (isFunction(super.componentWillMount)) {
        super.componentWillMount();
      }
      this.state = this.state || {};
      this.stateCopy = cloneDeep({ ...this.state }); // idk why cloneDeep(this.state) doesn't work,
      // but using cloneDeep(this.state) fails, as the first state change is missed
      const getScopedEvents = Events.getScopedEvents.bind(this);
      this.getEvents = partialRight(Events.getEvents.bind(this), getScopedEvents);
      this.getEventState = Events.getEventState.bind(this);
      this.setupEvents(this.props);
    }

    shouldComponentUpdate(nextProps, nextState) {
      if (
        this.props.animating // cannot use props.animate, as this is set to null during animation
        || get(nextProps, "sharedEvents.events.length") // for parent events
      ) {
        return true;
      }

      // save state copy; state is edited in-place so this.state is the SAME OBJECT has nextState.
      // i tried to replace _.extend in events.js with data copies, but that broke events;
      // there must be logic that relies on the mutation
      const stateChange = !isEqual(this.stateCopy, nextState);
      this.stateCopy = cloneDeep(this.state);
      if (stateChange) {
        return true;
      }

      if (!areVictoryPropsEqual(this.props, nextProps)) {
        return true;
      }

      return false;
    }

    componentWillUpdate(newProps) {
      if (isFunction(super.componentWillReceiveProps)) {
        super.componentWillReceiveProps();
      }
      this.setupEvents(newProps);
    }

    setupEvents(props) {
      const { sharedEvents } = props;
      const components = WrappedComponent.expectedComponents;
      this.componentEvents = Events.getComponentEvents(props, components);
      this.getSharedEventState = sharedEvents && isFunction(sharedEvents.getEventState) ?
        sharedEvents.getEventState : () => undefined;
      this.baseProps = this.getBaseProps(props);
      this.dataKeys = Object.keys(this.baseProps).filter((key) => key !== "parent");
      this.hasEvents = props.events || props.sharedEvents || this.componentEvents;
      this.events = this.getAllEvents(props);
    }

    getBaseProps(props) {
      const sharedParentState = this.getSharedEventState("parent", "parent");
      const parentState = this.getEventState("parent", "parent");
      const baseParentProps = defaults({}, parentState, sharedParentState);
      const parentPropsList = baseParentProps.parentControlledProps;
      const parentProps = parentPropsList ? pick(baseParentProps, parentPropsList) : {};
      const modifiedProps = defaults({}, parentProps, props);
      return isFunction(WrappedComponent.getBaseProps) ?
        WrappedComponent.getBaseProps(modifiedProps) : {};
    }

    getAllEvents(props) {
      if (Array.isArray(this.componentEvents)) {
        return Array.isArray(props.events) ?
          this.componentEvents.concat(...props.events) : this.componentEvents;
      }
      return props.events;
    }

    getComponentProps(component, type, index) {
      const { role } = WrappedComponent;
      const key = this.dataKeys && this.dataKeys[index] || index;
      const baseProps = this.baseProps[key][type] || this.baseProps[key];
      if (!baseProps && !this.hasEvents) {
        return undefined;
      }
      if (this.hasEvents) {
        const baseEvents = this.getEvents(this.props, type, key);
        const componentProps = defaults(
          { index, key: `${role}-${type}-${key}` },
          this.getEventState(key, type),
          this.getSharedEventState(key, type),
          component.props,
          baseProps
        );
        const events = defaults(
          {}, Events.getPartialEvents(baseEvents, key, componentProps), componentProps.events
        );
        return assign(
          {}, componentProps, { events }
        );
      }
      return defaults(
        { index, key: `${role}-${type}-${key}` },
        component.props,
        baseProps
      );
    }

    renderContainer(component, children) {
      const isContainer = component.type && component.type.role === "container";
      const parentProps = isContainer ? this.getComponentProps(component, "parent", "parent") : {};
      return React.cloneElement(component, parentProps, children);
    }

    animateComponent(props, animationWhitelist) {
      return (
        <VictoryTransition animate={props.animate} animationWhitelist={animationWhitelist}>
          {React.createElement(this.constructor, props)}
        </VictoryTransition>
      );
    }

    // Used by `VictoryLine` and `VictoryArea`
    renderContinuousData(props) {
      const { dataComponent, labelComponent, groupComponent } = props;
      const dataKeys = without(this.dataKeys, "all");
      const labelComponents = dataKeys.reduce((memo, key) => {
        const labelProps = this.getComponentProps(labelComponent, "labels", key);
        if (labelProps && labelProps.text !== undefined && labelProps.text !== null) {
          memo = memo.concat(React.cloneElement(labelComponent, labelProps));
        }
        return memo;
      }, []);
      const dataProps = this.getComponentProps(dataComponent, "data", "all");
      const children = [React.cloneElement(dataComponent, dataProps), ...labelComponents];
      return this.renderContainer(groupComponent, children);
    }

    renderData(props) {
      const { dataComponent, labelComponent, groupComponent } = props;
      const dataComponents = this.dataKeys.map((_dataKey, index) => {
        const dataProps = this.getComponentProps(dataComponent, "data", index);
        return React.cloneElement(dataComponent, dataProps);
      });

      const labelComponents = this.dataKeys.map((_dataKey, index) => {
        const labelProps = this.getComponentProps(labelComponent, "labels", index);
        if (labelProps.text !== undefined && labelProps.text !== null) {
          return React.cloneElement(labelComponent, labelProps);
        }
        return undefined;
      }).filter(Boolean);

      const children = [...dataComponents, ...labelComponents];
      return this.renderContainer(groupComponent, children);
    }

  };
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var notify = require("gulp-notify");
var preen = require('preen');
var sourcemaps = require('gulp-sourcemaps');
var imagemin = require('gulp-imagemin');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
var path = require('path');
var del = require('del');
var pump = require('pump');

var paths = {
    sass: ['scss/**/*.scss'],
    index: 'app/index.html',
    scripts: ['app/js/app.js', 'app/js/**/*.js'],
    styles: 'app/scss/**/*.*',
    templates: 'app/templates/**/*.*',
    images: 'app/img/**/*.*',
    lib: 'www/lib/**/*.*',
    //Destination folders
    destImages: './www/img/',
    destTemplates: './www/templates/'
};

gulp.task('serve:before', ['watch']);

gulp.task('default', ['sass', 'index', 'scripts', 'styles', 'templates', 'images', 'lib']);

gulp.task('serve', function (done) {
    sh.exec('ionic serve', done);
});

gulp.task('sass', function (done) {
    gulp.src('./scss/ionic.app.scss')
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(gulp.dest('./www/css/'))
        .pipe(minifyCss({
            keepSpecialComments: 0
        }))
        .pipe(rename({ extname: '.min.css' }))
        .pipe(gulp.dest('./www/css/'))
        .on('end', done);
});

gulp.task('index', function () {
    return gulp.src(paths.index)
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest("./www/"))
        .pipe(notify({ message: 'Index built' }));
});

gulp.task('scripts', function (done) {
    pump([
        gulp.src(paths.scripts),
        jshint(),
        jshint.reporter('default', { verbose: true }),
        //jshint.reporter('fail'), //Fail if jshint show errors in console
        sourcemaps.init(),
        concat("app.js"),
        sourcemaps.write(),
        gulp.dest("./www/build/"),
        rename('app.min.js'),
        uglify(),
        gulp.dest("./www/build/"),
        notify({ message: 'Scripts built' })
    ],
        done
    );
});

gulp.task('styles', function () {
    return gulp.src(paths.styles)
        .pipe(sourcemaps.init())
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(concat('style.css'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./www/css/'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifyCss())
        .pipe(gulp.dest('./www/css/'))
        .pipe(notify({ message: 'Styles built' }));
});

function MinifyTemplates(path, destPath) {
    return gulp.src(path)
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest(destPath || paths.destTemplates));
}

gulp.task('templates', ['clean-templates'], function (done) {
    MinifyTemplates(paths.templates).on('end', function () {
        gulp.src('').pipe(notify({ message: 'Templates built' }));
        done();
    });
});

function MinifyImages(path, destPath) {
    return gulp.src(path)
        .pipe(imagemin({ optimizationLevel: 5 }))
        .pipe(gulp.dest(destPath || paths.destImages));
}

gulp.task('images', ['clean-images'], function (done) {
    MinifyImages(paths.images).on('end', function () {
        gulp.src('').pipe(notify({ message: 'Images built' }));
        done();
    });
});

gulp.task('lib', function (done) {
    //https://forum.ionicframework.com/t/how-to-manage-bower-overweight/17997/10?u=jdnichollsc
    preen.preen({}, function () {
        gulp.src('').pipe(notify({ message: 'Lib built' }));
        done();
    });
});

gulp.task('clean-images', function () {
    return del(paths.destImages);
});

gulp.task('clean-templates', function () {
    return del(paths.destTemplates);
});

gulp.task('watch', function () {
    gulp.watch(paths.sass, ['sass']);
    gulp.watch(paths.index, ['index']);
    gulp.watch(paths.scripts, ['scripts']);
    gulp.watch(paths.styles, ['styles']);
    gulp.watch(paths.templates, function (event) {
        var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
        if (event.type === "deleted") {
            del(destPathFile);
        } else {
            var pathFile = path.relative(__dirname, event.path);
            var destPath = path.dirname(destPathFile);
            MinifyTemplates(pathFile, destPath).on('end', function () {
                gulp.src('').pipe(notify({ message: 'Template built' }));
            });
        }
    });
    gulp.watch(paths.images, function (event) {
        var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
        if (event.type === "deleted") {
            del(destPathFile);
        } else {
            var pathFile = path.relative(__dirname, event.path);
            var destPath = path.dirname(destPathFile);
            MinifyImages(pathFile, destPath).on('end', function () {
                gulp.src('').pipe(notify({ message: 'Image built' }));
            });
        }
    });
    gulp.watch(paths.lib, ['lib']);
});

gulp.task('install', ['git-check'], function () {
    return bower.commands.install()
        .on('log', function (data) {
            gutil.log('bower', gutil.colors.cyan(data.id), data.message);
        });
});

gulp.task('git-check', function (done) {
    if (!sh.which('git')) {
        console.log(
            '  ' + gutil.colors.red('Git is not installed.'),
            '\n  Git, the version control system, is required to download Ionic.',
            '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
            '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
        );
        process.exit(1);
    }
    done();
});

/* GitHub Page - http(s)://<username>.github.io/<projectname>
   TODO: Execute the following steps if you don't want to publish your code to GitHub Pages like a demo.
   - Uninstall the gulp plugins from package.json:
        npm uninstall gulp-gh-pages --save-dev
        npm uninstall merge2 --save-dev
   - Remove the folder './gh-pages'
   - Remove the code below
*/
var ghPages = require('gulp-gh-pages');
var merge2  = require('merge2');

gulp.task('deploy-files', function () {
    var sourcePath = [
        './www/**/*',
        '!./www/pre.db'
    ];
    return merge2(
        gulp.src('./gh-pages/**/*'),
        gulp.src(sourcePath, { base: './' })
    )
    .pipe(ghPages());
});

gulp.task('deploy', ['deploy-files'], function () {
    return gulp.src('').pipe(notify({ message: 'GitHub Page updated' }));
});<commit_msg>Fix for gulp watch<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var notify = require("gulp-notify");
var preen = require('preen');
var sourcemaps = require('gulp-sourcemaps');
var imagemin = require('gulp-imagemin');
var autoprefixer = require('gulp-autoprefixer');
var jshint = require('gulp-jshint');
var path = require('path');
var del = require('del');
var pump = require('pump');

var paths = {
    sass: ['scss/**/*.scss'],
    index: 'app/index.html',
    scripts: ['app/js/app.js', 'app/js/**/*.js'],
    styles: 'app/scss/**/*.*',
    templates: 'app/templates/**/*.*',
    images: 'app/img/**/*.*',
    lib: 'www/lib/**/*.*',
    //Destination folders
    destImages: './www/img/',
    destTemplates: './www/templates/'
};

gulp.task('ionic:watch:before', ['watch'])

gulp.task('default', ['sass', 'index', 'scripts', 'styles', 'templates', 'images', 'lib']);

gulp.task('serve', function (done) {
    sh.exec('ionic serve', done);
});

gulp.task('sass', function (done) {
    gulp.src('./scss/ionic.app.scss')
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(gulp.dest('./www/css/'))
        .pipe(minifyCss({
            keepSpecialComments: 0
        }))
        .pipe(rename({ extname: '.min.css' }))
        .pipe(gulp.dest('./www/css/'))
        .on('end', done);
});

gulp.task('index', function () {
    return gulp.src(paths.index)
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest("./www/"))
        .pipe(notify({ message: 'Index built' }));
});

gulp.task('scripts', function (done) {
    pump([
        gulp.src(paths.scripts),
        jshint(),
        jshint.reporter('default', { verbose: true }),
        //jshint.reporter('fail'), //Fail if jshint show errors in console
        sourcemaps.init(),
        concat("app.js"),
        sourcemaps.write(),
        gulp.dest("./www/build/"),
        rename('app.min.js'),
        uglify(),
        gulp.dest("./www/build/"),
        notify({ message: 'Scripts built' })
    ],
        done
    );
});

gulp.task('styles', function () {
    return gulp.src(paths.styles)
        .pipe(sourcemaps.init())
        .pipe(sass())
        .on('error', sass.logError)
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(concat('style.css'))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./www/css/'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifyCss())
        .pipe(gulp.dest('./www/css/'))
        .pipe(notify({ message: 'Styles built' }));
});

function MinifyTemplates(path, destPath) {
    return gulp.src(path)
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest(destPath || paths.destTemplates));
}

gulp.task('templates', ['clean-templates'], function (done) {
    MinifyTemplates(paths.templates).on('end', function () {
        gulp.src('').pipe(notify({ message: 'Templates built' }));
        done();
    });
});

function MinifyImages(path, destPath) {
    return gulp.src(path)
        .pipe(imagemin({ optimizationLevel: 5 }))
        .pipe(gulp.dest(destPath || paths.destImages));
}

gulp.task('images', ['clean-images'], function (done) {
    MinifyImages(paths.images).on('end', function () {
        gulp.src('').pipe(notify({ message: 'Images built' }));
        done();
    });
});

gulp.task('lib', function (done) {
    //https://forum.ionicframework.com/t/how-to-manage-bower-overweight/17997/10?u=jdnichollsc
    preen.preen({}, function () {
        gulp.src('').pipe(notify({ message: 'Lib built' }));
        done();
    });
});

gulp.task('clean-images', function () {
    return del(paths.destImages);
});

gulp.task('clean-templates', function () {
    return del(paths.destTemplates);
});

gulp.task('watch', function () {
    gulp.watch(paths.sass, ['sass']);
    gulp.watch(paths.index, ['index']);
    gulp.watch(paths.scripts, ['scripts']);
    gulp.watch(paths.styles, ['styles']);
    gulp.watch(paths.templates, function (event) {
        var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
        if (event.type === "deleted") {
            del(destPathFile);
        } else {
            var pathFile = path.relative(__dirname, event.path);
            var destPath = path.dirname(destPathFile);
            MinifyTemplates(pathFile, destPath).on('end', function () {
                gulp.src('').pipe(notify({ message: 'Template built' }));
            });
        }
    });
    gulp.watch(paths.images, function (event) {
        var destPathFile = path.join('./www', path.relative(path.join(__dirname, './app'), event.path));
        if (event.type === "deleted") {
            del(destPathFile);
        } else {
            var pathFile = path.relative(__dirname, event.path);
            var destPath = path.dirname(destPathFile);
            MinifyImages(pathFile, destPath).on('end', function () {
                gulp.src('').pipe(notify({ message: 'Image built' }));
            });
        }
    });
    gulp.watch(paths.lib, ['lib']);
});

gulp.task('install', ['git-check'], function () {
    return bower.commands.install()
        .on('log', function (data) {
            gutil.log('bower', gutil.colors.cyan(data.id), data.message);
        });
});

gulp.task('git-check', function (done) {
    if (!sh.which('git')) {
        console.log(
            '  ' + gutil.colors.red('Git is not installed.'),
            '\n  Git, the version control system, is required to download Ionic.',
            '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
            '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
        );
        process.exit(1);
    }
    done();
});

/* GitHub Page - http(s)://<username>.github.io/<projectname>
   TODO: Execute the following steps if you don't want to publish your code to GitHub Pages like a demo.
   - Uninstall the gulp plugins from package.json:
        npm uninstall gulp-gh-pages --save-dev
        npm uninstall merge2 --save-dev
   - Remove the folder './gh-pages'
   - Remove the code below
*/
var ghPages = require('gulp-gh-pages');
var merge2  = require('merge2');

gulp.task('deploy-files', function () {
    var sourcePath = [
        './www/**/*',
        '!./www/pre.db'
    ];
    return merge2(
        gulp.src('./gh-pages/**/*'),
        gulp.src(sourcePath, { base: './' })
    )
    .pipe(ghPages());
});

gulp.task('deploy', ['deploy-files'], function () {
    return gulp.src('').pipe(notify({ message: 'GitHub Page updated' }));
});

<|endoftext|>