<commit_before>popup = function(url) {
	window.open (url, "Papermill", config='height=580, width=870, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no')
}

close_popup = function(source) {
	source.close();
}

/*
If you have a popup library, override popup and close_popup in your application.js

* e.g. facebox :

popup = function(url) {
	jQuery.facebox(function() {
	  jQuery.get(url, function(data) {
	    jQuery.facebox(data)
	  })
	})
	return false;
}
close_popup = function(source) {
	jQuery(document).trigger('close.facebox');
}

* e.g. Shadowbox :

popup = function(url) {
	Shadowbox.open({
  	content:    url-,
    player:     "iframe",
		width: 			870,
		height: 		580
  });
	return false;
}

close_popup = function(source) {
	Shadowbox.close();
}

*/

notify = function(message, type) {
	if(type != "notice") { alert(type + ": " + message) }
}

/*
If you have a notification library, override notify

* e.g. jGrowl :

notify = function(message, type) {
	if(type == "notice") { jQuery.noticeAdd({ text: message, stayTime: 4000, stay: false, type: type }) }
	if(type == "warning") {	jQuery.noticeAdd({ text: message, stayTime: 9000, stay: false, type: type }) }
	if(type == "error") {	jQuery.noticeAdd({ text: message, stayTime: 20000, stay: false, type: type }) }
}

*/

var Upload = {
	files_queued: 0,
	file_dialog_complete: function(num_selected, num_queued)
	{
		// SwfUpload doesn't order uploads by name out of the box...
		this.sorted_queue = [];
		this.index = 0;
		if (num_queued > 0)	{
			file_queue = [];
			global_index = 0;
			index = 0;
			do {
				file = this.callFlash("GetFileByIndex", [global_index]);
				if(file != null && file.filestatus == -1) {
					file_queue[index] = file;
					index++;
				}
				global_index++;
			} while (file != null);
			this.sorted_queue = file_queue.sort(function(a,b){
				if(b.name < a.name){ return (1) } else { return (-1) }
			})
			var self = this;
			jQuery(this.sorted_queue).each( function(index, file) {
				div = jQuery('

').attr({ 'id': file.id, 'class': 'swfupload asset' });
				div.append(jQuery('').attr('class', 'name').html(file.name.substring(0, 10) + '...'));
				div.append(jQuery('').attr('class', 'status').html(SWFUPLOAD_PENDING));
				div.append(jQuery('').attr('class', 'progress').append(''));

				if(self.settings.file_queue_limit == 1) {
					jQuery("#" + self.settings.upload_id).html(div);
				} else {
					jQuery("#" + self.settings.upload_id).append(div);
				}
			})
			this.startUpload(this.sorted_queue[this.index++].id);
		}
	},

	upload_start: function(file)
	{
		jQuery('#' + file.id + ' .status').html(SWFUPLOAD_LOADING);
	},
	upload_progress: function(file, bytes, total)
	{
		percent = Math.ceil((bytes / total) * 100);
		jQuery('#' + file.id + ' .progress span').width(percent + '%');
	},
	upload_error: function(file, errorCode, message) {
		try {
			switch (errorCode) {
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				notify("Too many files selected", "error");
				return;
			default:
				notify("An error occurred in the upload", "error");
				return;
			}
		} catch (ex) {
		}
	},

	upload_success: function(file, data)
	{
		if(jQuery(data).length == 0) {
			notify(data, "warning");
			jQuery('#' + file.id).remove();
		} else {
			jQuery('#' + file.id).replaceWith(jQuery(data));
		}
	},
	upload_complete: function(file)
	{
		Upload.files_queued -= 1;
		if(this.sorted_queue[this.index]) {
			this.startUpload(this.sorted_queue[this.index++].id)
		}
	},

	file_queue_error: function(file, errorCode, message)  {
		try {
			switch (errorCode) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				notify("Too many files selected", "error");
				return;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				notify("File is too big", "error");
				return;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				notify("File is empty.  Please select another file", "error");
				return;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				notify("File is not an allowed file type", "error");
				return;
			default:
				notify("An error occurred in the upload", "error");
				return;
			}
		} catch (e) {
		}
	}
}

modify_all = function(papermill_id) {
	container = jQuery("#" + papermill_id)[0];
	attribute_name = jQuery("#batch_" + papermill_id)[0].value
	attribute_wording = jQuery("#batch_" + papermill_id + " option:selected").text();
	value = prompt(attribute_wording + ":")
	if(value != null) {
		jQuery.ajax({async:true, data:jQuery(container).sortable('serialize'), dataType:'script', type:'post', url:'/papermill/mass_edit?attribute=' + attribute_name + "&value=" + value})
	}
}

mass_delete = function(papermill_id, wording) {
	if(confirm(wording)){
    jQuery.ajax({async:true, data:jQuery('#' + papermill_id).sortable('serialize'), dataType:'script', type:'post', url:'/papermill/mass_delete'})
  }
}
<commit_msg>error handling<commit_after>popup = function(url) {
	window.open (url, "Papermill", config='height=580, width=870, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no')
}

close_popup = function(source) {
	source.close();
}

/*
If you have a popup library, override popup and close_popup in your application.js

* e.g. facebox :

popup = function(url) {
	jQuery.facebox(function() {
	  jQuery.get(url, function(data) {
	    jQuery.facebox(data)
	  })
	})
	return false;
}
close_popup = function(source) {
	jQuery(document).trigger('close.facebox');
}

* e.g. Shadowbox :

popup = function(url) {
	Shadowbox.open({
  	content:    url-,
    player:     "iframe",
		width: 			870,
		height: 		580
  });
	return false;
}

close_popup = function(source) {
	Shadowbox.close();
}

*/

notify = function(message, type) {
	if(type != "notice") { alert(type + ": " + message) }
}

/*
If you have a notification library, override notify

* e.g. jGrowl :

notify = function(message, type) {
	if(type == "notice") { jQuery.noticeAdd({ text: message, stayTime: 4000, stay: false, type: type }) }
	if(type == "warning") {	jQuery.noticeAdd({ text: message, stayTime: 9000, stay: false, type: type }) }
	if(type == "error") {	jQuery.noticeAdd({ text: message, stayTime: 20000, stay: false, type: type }) }
}

*/

var Upload = {
	files_queued: 0,
	file_dialog_complete: function(num_selected, num_queued)
	{
		// SwfUpload doesn't order uploads by name out of the box...
		this.sorted_queue = [];
		this.index = 0;
		if (num_queued > 0)	{
			file_queue = [];
			global_index = 0;
			index = 0;
			do {
				file = this.callFlash("GetFileByIndex", [global_index]);
				if(file != null && file.filestatus == -1) {
					file_queue[index] = file;
					index++;
				}
				global_index++;
			} while (file != null);
			this.sorted_queue = file_queue.sort(function(a,b){
				if(b.name < a.name){ return (1) } else { return (-1) }
			})
			var self = this;
			jQuery(this.sorted_queue).each( function(index, file) {
				div = jQuery('

').attr({ 'id': file.id, 'class': 'swfupload asset' });
				div.append(jQuery('').attr('class', 'name').html(file.name.substring(0, 10) + '...'));
				div.append(jQuery('').attr('class', 'status').html(SWFUPLOAD_PENDING));
				div.append(jQuery('').attr('class', 'progress').append(''));

				if(self.settings.file_queue_limit == 1) {
					jQuery("#" + self.settings.upload_id).html(div);
				} else {
					jQuery("#" + self.settings.upload_id).append(div);
				}
			})
			this.startUpload(this.sorted_queue[this.index++].id);
		}
	},

	upload_start: function(file)
	{
		jQuery('#' + file.id + ' .status').html(SWFUPLOAD_LOADING);
	},
	upload_progress: function(file, bytes, total)
	{
		percent = Math.ceil((bytes / total) * 100);
		jQuery('#' + file.id + ' .progress span').width(percent + '%');
	},
	upload_error: function(file, errorCode, message) {
		try {
			switch (errorCode) {
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				notify("Too many files selected", "error");
				return;
			default:
				notify("An error occurred in the upload" + errorCode, "error");
				return;
			}
		} catch (ex) {
		}
	},

	upload_success: function(file, data)
	{
		if(jQuery(data).length == 0) {
			notify(data, "warning");
			jQuery('#' + file.id).remove();
		} else {
			jQuery('#' + file.id).replaceWith(jQuery(data));
		}
	},
	upload_complete: function(file)
	{
		Upload.files_queued -= 1;
		if(this.sorted_queue[this.index]) {
			this.startUpload(this.sorted_queue[this.index++].id)
		}
	},

	file_queue_error: function(file, errorCode, message)  {
		try {
			switch (errorCode) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				notify("Too many files selected", "error");
				return;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				notify("File is too big", "error");
				return;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				notify("File is empty.  Please select another file", "error");
				return;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				notify("File is not an allowed file type", "error");
				return;
			default:
				notify("An error occurred in the upload" + errorCode, "error");
				return;
			}
		} catch (e) {
		}
	}
}

modify_all = function(papermill_id) {
	container = jQuery("#" + papermill_id)[0];
	attribute_name = jQuery("#batch_" + papermill_id)[0].value
	attribute_wording = jQuery("#batch_" + papermill_id + " option:selected").text();
	value = prompt(attribute_wording + ":")
	if(value != null) {
		jQuery.ajax({async:true, data:jQuery(container).sortable('serialize'), dataType:'script', type:'post', url:'/papermill/mass_edit?attribute=' + attribute_name + "&value=" + value})
	}
}

mass_delete = function(papermill_id, wording) {
	if(confirm(wording)){
    jQuery.ajax({async:true, data:jQuery('#' + papermill_id).sortable('serialize'), dataType:'script', type:'post', url:'/papermill/mass_delete'})
  }
}
<|endoftext|>


<commit_before>'use strict';
var d3 = require('d3');
var _ = require('lodash');
var utils = require('lightning-client-utils');

var margin = {
    top: 30,
    right: 20,
    bottom: 20,
    left: 45
};

var nestedExtent = function(arrays, map) {
    var max = d3.max(arrays, function(arr) {
        return d3.max(_.map(arr, map));
    });
    var min = d3.min(arrays, function(arr) {
        return d3.min(_.map(arr, map));
    });

    return [min, max];
};

var LineGraph = function(selector, data, images, opts) {

    if(!opts) {
        opts = {};
    }

    this.opts = opts;

    this.width = (opts.width || $(selector).width()) - margin.left - margin.right;
    this.height = (opts.height || (this.width * 0.6)) - margin.top - margin.bottom;

    this.data = this._formatData(data);
    this.selector = selector;
    this.defaultSize = 2;
    this._init();
};

LineGraph.prototype._init = function() {

    var data = this.data;
    var height = this.height;
    var width = this.width;
    var opts = this.opts;
    var selector = this.selector;
    var self = this;

    var series = data.series;
    var color = data.color.length > 0 ? data.color : utils.getColors(series.length);
    var size = data.size

    console.log(color)

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    var noZoom = d3.scale.linear();

    this.x = d3.scale.linear()
        .domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread])
        .range([0, width]);

    this.y = d3.scale.linear()
        .domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread])
        .range([height, 0]);

    this.line = d3.svg.line()
        .x(function (d) {
            return self.x(d.x);
        })
        .y(function (d) {
            return self.y(d.y);
        })

    var yToggle;
    if(opts.zoomAxes) {
        this.zoom = d3.behavior.zoom();
        if(opts.zoomAxes.indexOf('x') > -1) {
            this.zoom.x(this.x);
        }
        if(opts.zoomAxes.indexOf('y') > -1) {
            this.zoom.y(this.y);
            yToggle = true;
        } else {
            yToggle = false;
        }

        this.zoom.on('zoom', zoomed);

    } else {
        yToggle = true;
        this.zoom = d3.behavior.zoom()
            .x(this.x)
            .y(this.y)
            .on('zoom', zoomed);
    }

    var svg = d3.select(selector)
        .append('svg:svg')
        .attr('class', 'line-plot')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('svg:g')
        .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
        .call(this.zoom);

    svg.append('svg:rect')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'plot');

    d3.select('body').on('keydown', function() {
        if(d3.event.shiftKey) {
            if(yToggle) {
                yToggle = false;
                self.zoom.y(noZoom);
            } else {
                yToggle = true;
                self.zoom.y(self.y);
            }
        }
    });

    var makeXAxis = function () {
        return d3.svg.axis()
            .scale(self.x)
            .orient('bottom')
            .ticks(5);
    };

    var makeYAxis = function () {
        return d3.svg.axis()
            .scale(self.y)
            .orient('left')
            .ticks(5);
    };

    this.xAxis = d3.svg.axis()
        .scale(this.x)
        .orient('bottom')
        .ticks(5);

    svg.append('svg:g')
        .attr('class', 'x axis')
        .attr('transform', 'translate(0, ' + height + ')')
        .call(this.xAxis);

    this.yAxis = d3.svg.axis()
        .scale(this.y)
        .orient('left')
        .ticks(5);

    svg.append('g')
        .attr('class', 'y axis')
        .call(this.yAxis);

    svg.append('g')
        .attr('class', 'x grid')
        .attr('transform', 'translate(0,' + height + ')')
        .call(makeXAxis()
                .tickSize(-height, 0, 0)
                .tickFormat(''));

    svg.append('g')
        .attr('class', 'y grid')
        .call(makeYAxis()
                .tickSize(-width, 0, 0)
                .tickFormat(''));

    var clip = svg.append('svg:clipPath')
        .attr('id', 'clip')
        .append('svg:rect')
        .attr('x', 0)
        .attr('y', 0)
        .attr('width', width)
        .attr('height', height);

    var chartBody = svg.append('g')
        .attr('clip-path', 'url(#clip)');

    _.each(series, function(d, i) {
        chartBody.append('path')
            .datum(d)
            .attr('class', 'line')
            .attr('stroke', color[i])
            .style('stroke-width', size[i] ? size[i] : self.defaultSize)
            .style('stroke-opacity', 0.9)
            .attr('d', self.line);
    });

    function updateAxis() {

        self.svg.select('.x.axis').call(self.xAxis);
        self.svg.select('.y.axis').call(self.yAxis);
        self.svg.select('.x.grid')
            .call(makeXAxis()
                .tickSize(-height, 0, 0)
                .tickFormat(''));
        self.svg.select('.y.grid')
            .call(makeYAxis()
                    .tickSize(-width, 0, 0)
                    .tickFormat(''));
    }

    function zoomed() {

        updateAxis();
        self.svg.selectAll('.line')
            .attr('class', 'line')
            .attr('d', self.line);
    }

    this.svg = svg;
    this.zoomed = zoomed;
    this.updateAxis = updateAxis;
};

LineGraph.prototype._formatData = function(data) {

    if(_.isArray(data.series[0])) {
        // handle case of mutliple series
        data.series = _.map(data.series, function(d) {
            return _.map(d, function(datum, i) {
                return {
                    x: data.index ? data.index[i] : i,
                    y: datum
                };
            });
        });
    } else {
        // handle a single series
        data.series = [_.map(data.series, function(d, i) {
            return {
                x: data.index ? data.index[i] : i,
                y: d
            };
        })];
    }

    data.color = utils.getColorFromData(data);
    if (data.color.length == 1) {
        data.color = _.times(data.series.length, _.constant(data.color));
    }

    data.size = data.size || []

    return data;
};

module.exports = LineGraph;

LineGraph.prototype.updateData = function(data) {

    this.data = this._formatData(data);
    var series = this.data.series;

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    this.x.domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread]);
    this.y.domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread]);

    this.updateAxis();

    this.svg.selectAll('.line')
        .data(series)
        .transition()
        .attr('d', this.line);

};

LineGraph.prototype.appendData = function(data) {

    this.data = this.data.concat(this._formatData(data));
    var series = this.data.series;

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    this.x.domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread]);
    this.y.domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread]);

    this.updateAxis();

    this.svg.selectAll('.line')
        .data(series)
        .transition()
        .attr('d', this.line);
};
<commit_msg>Propagate singleton size<commit_after>'use strict';
var d3 = require('d3');
var _ = require('lodash');
var utils = require('lightning-client-utils');

var margin = {
    top: 30,
    right: 20,
    bottom: 20,
    left: 45
};

var nestedExtent = function(arrays, map) {
    var max = d3.max(arrays, function(arr) {
        return d3.max(_.map(arr, map));
    });
    var min = d3.min(arrays, function(arr) {
        return d3.min(_.map(arr, map));
    });

    return [min, max];
};

var LineGraph = function(selector, data, images, opts) {

    if(!opts) {
        opts = {};
    }

    this.opts = opts;

    this.width = (opts.width || $(selector).width()) - margin.left - margin.right;
    this.height = (opts.height || (this.width * 0.6)) - margin.top - margin.bottom;

    this.data = this._formatData(data);
    this.selector = selector;
    this.defaultSize = 2;
    this._init();
};

LineGraph.prototype._init = function() {

    var data = this.data;
    var height = this.height;
    var width = this.width;
    var opts = this.opts;
    var selector = this.selector;
    var self = this;

    var series = data.series;
    var color = data.color.length > 0 ? data.color : utils.getColors(series.length);
    var size = data.size

    console.log(color)

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    var noZoom = d3.scale.linear();

    this.x = d3.scale.linear()
        .domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread])
        .range([0, width]);

    this.y = d3.scale.linear()
        .domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread])
        .range([height, 0]);

    this.line = d3.svg.line()
        .x(function (d) {
            return self.x(d.x);
        })
        .y(function (d) {
            return self.y(d.y);
        })

    var yToggle;
    if(opts.zoomAxes) {
        this.zoom = d3.behavior.zoom();
        if(opts.zoomAxes.indexOf('x') > -1) {
            this.zoom.x(this.x);
        }
        if(opts.zoomAxes.indexOf('y') > -1) {
            this.zoom.y(this.y);
            yToggle = true;
        } else {
            yToggle = false;
        }

        this.zoom.on('zoom', zoomed);

    } else {
        yToggle = true;
        this.zoom = d3.behavior.zoom()
            .x(this.x)
            .y(this.y)
            .on('zoom', zoomed);
    }

    var svg = d3.select(selector)
        .append('svg:svg')
        .attr('class', 'line-plot')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('svg:g')
        .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
        .call(this.zoom);

    svg.append('svg:rect')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'plot');

    d3.select('body').on('keydown', function() {
        if(d3.event.shiftKey) {
            if(yToggle) {
                yToggle = false;
                self.zoom.y(noZoom);
            } else {
                yToggle = true;
                self.zoom.y(self.y);
            }
        }
    });

    var makeXAxis = function () {
        return d3.svg.axis()
            .scale(self.x)
            .orient('bottom')
            .ticks(5);
    };

    var makeYAxis = function () {
        return d3.svg.axis()
            .scale(self.y)
            .orient('left')
            .ticks(5);
    };

    this.xAxis = d3.svg.axis()
        .scale(this.x)
        .orient('bottom')
        .ticks(5);

    svg.append('svg:g')
        .attr('class', 'x axis')
        .attr('transform', 'translate(0, ' + height + ')')
        .call(this.xAxis);

    this.yAxis = d3.svg.axis()
        .scale(this.y)
        .orient('left')
        .ticks(5);

    svg.append('g')
        .attr('class', 'y axis')
        .call(this.yAxis);

    svg.append('g')
        .attr('class', 'x grid')
        .attr('transform', 'translate(0,' + height + ')')
        .call(makeXAxis()
                .tickSize(-height, 0, 0)
                .tickFormat(''));

    svg.append('g')
        .attr('class', 'y grid')
        .call(makeYAxis()
                .tickSize(-width, 0, 0)
                .tickFormat(''));

    var clip = svg.append('svg:clipPath')
        .attr('id', 'clip')
        .append('svg:rect')
        .attr('x', 0)
        .attr('y', 0)
        .attr('width', width)
        .attr('height', height);

    var chartBody = svg.append('g')
        .attr('clip-path', 'url(#clip)');

    _.each(series, function(d, i) {
        chartBody.append('path')
            .datum(d)
            .attr('class', 'line')
            .attr('stroke', color[i])
            .style('stroke-width', size[i] ? size[i] : self.defaultSize)
            .style('stroke-opacity', 0.9)
            .attr('d', self.line);
    });

    function updateAxis() {

        self.svg.select('.x.axis').call(self.xAxis);
        self.svg.select('.y.axis').call(self.yAxis);
        self.svg.select('.x.grid')
            .call(makeXAxis()
                .tickSize(-height, 0, 0)
                .tickFormat(''));
        self.svg.select('.y.grid')
            .call(makeYAxis()
                    .tickSize(-width, 0, 0)
                    .tickFormat(''));
    }

    function zoomed() {

        updateAxis();
        self.svg.selectAll('.line')
            .attr('class', 'line')
            .attr('d', self.line);
    }

    this.svg = svg;
    this.zoomed = zoomed;
    this.updateAxis = updateAxis;
};

LineGraph.prototype._formatData = function(data) {

    if(_.isArray(data.series[0])) {
        // handle case of mutliple series
        data.series = _.map(data.series, function(d) {
            return _.map(d, function(datum, i) {
                return {
                    x: data.index ? data.index[i] : i,
                    y: datum
                };
            });
        });
    } else {
        // handle a single series
        data.series = [_.map(data.series, function(d, i) {
            return {
                x: data.index ? data.index[i] : i,
                y: d
            };
        })];
    }

    data.color = utils.getColorFromData(data);
    if (data.color.length == 1) {
        data.color = _.times(data.series.length, _.constant(data.color));
    }

    data.size = data.size || []
    if (data.size.length == 1) {
        data.size = _.times(data.series.length, _.constant(data.size));
    }

    return data;
};

module.exports = LineGraph;

LineGraph.prototype.updateData = function(data) {

    this.data = this._formatData(data);
    var series = this.data.series;

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    this.x.domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread]);
    this.y.domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread]);

    this.updateAxis();

    this.svg.selectAll('.line')
        .data(series)
        .transition()
        .attr('d', this.line);

};

LineGraph.prototype.appendData = function(data) {

    this.data = this.data.concat(this._formatData(data));
    var series = this.data.series;

    var yDomain = nestedExtent(series, function(d) {
        return d.y;
    });
    var xDomain = nestedExtent(series, function(d) {
        return d.x;
    });

    var ySpread = Math.abs(yDomain[1] - yDomain[0]) || 1;
    var xSpread = Math.abs(xDomain[1] - xDomain[0]) || 1;

    this.x.domain([xDomain[0] - 0.05 * xSpread, xDomain[1] + 0.05 * xSpread]);
    this.y.domain([yDomain[0] - 0.1 * ySpread, yDomain[1] + 0.1 * ySpread]);

    this.updateAxis();

    this.svg.selectAll('.line')
        .data(series)
        .transition()
        .attr('d', this.line);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import NotifBubbles from './notif_bubbles';
import { getNotifText } from '../../consts/utils';

const { ipcRenderer } = require('electron');

class Notifs extends Component {
  constructor() {
    super();
    this.state = {
      active: false,
    };
  }
  componentDidMount() {
    /*
     * In our container, which connected this component to redux,
     * we asked for auth state and said that we will dispatch notifs actions.
     * That's why we can access them as props in here.
     */
    const { fetchNotifs } = this.props;

    fetchNotifs();

    setInterval(() => {
      fetchNotifs();
    }, 10000);

    ipcRenderer.on('open_notif', () => { this.setState({ active: true }); });
  }
  componentDidUpdate(prevProps) {
    const prevNotifs = prevProps.notifs;
    if (
      !prevNotifs ||
      !this.props.notifs ||
      !this.props.auth.user
    ) {
      return;
    }
    const currentNotifs = this.props.notifs;
    const prevUnread = prevNotifs.num_unread;
    const currentUnread = currentNotifs.num_unread;
    const notifs = this.props.notifs;
    if (prevUnread < currentUnread) {
      const notif = notifs.items[0];
      const isCollab = notif.rt === 2;
      const osNotif = {
        body: getNotifText(
          notif.type,
          notifs.username_map[notif.uid].name,
          isCollab,
        ),
        id: notif.rant_id,
        content: notif,
      };
      this.props.openNotif(osNotif);
    }
  }
  toggleNotif(e) {
    if (e.target.className === 'notif_bubble_container') {
      this.setState({ active: !this.state.active });
    }
  }
  render() {
    const {
      notifs, auth, open, clearNotifs, theme,
    } = this.props;

    /* Wondering why there is notifs.notifs?
     * If you look at the default state, it looks like this:
     * const NOTIFS = { state: STATE.INITIAL, notifs: {} }
     * so in redux store, it's stored like this:
     * { ...other states, notifs: { state: STATE.INITIAL, notifs: {} } }
     * So in our container, when we ask redux for notifs, it actually gives
     * use this:
     * notifs: { state: STATE.INITIAL, notifs: {} }

     * Also, we check if notif actually exists by checking notifs.notifs.data
     * otherwise we don't show any numbers yet
     */
    if (!notifs || !auth.user) {
      return
;
    }
    return (
      <div
        className={`notifs_container ${this.state.active ? 'active' : ''}`}
        onClick={e => this.toggleNotif(e)}
      >
        <button
          className="notifs_ball"
          style={{
            backgroundColor: theme.plus_notif ? theme.plus_notif.backgroundColor : '#D55161',
            color: theme.id === 'dark_theme' ? '#ffffff' : theme.item_card.backgroundColor,
          }}
          onClick={() => { this.setState({ active: !this.state.active }); }}
        >

          <span
            className={`num_unread ${notifs.num_unread > 0 ? 'unread' : ''}`}
          >
            { notifs ? notifs.num_unread : '' }

        </button>
        <div className={`notif_bubbles ${this.state.active ? 'active' : 'inactive'}`}>
          <button
            style={{
              backgroundColor: theme.plus_notif ? theme.plus_notif.backgroundColor : '#D55161',
              color: theme.id === 'dark_theme' ? '#ffffff' : theme.item_card.backgroundColor,
            }}
            className="notifs_clear"
            onClick={() => { clearNotifs(); }}
          >Clear All
          </button>
          <NotifBubbles data={notifs} open={open} />

        <div className={`notifs_bubbles_container ${this.state.active ? 'active' : ''}`} />

    );
  }
}

Notifs.propTypes = {
  auth: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
  fetchNotifs: PropTypes.func.isRequired,
  notifs: PropTypes.object,
  openNotif: PropTypes.func.isRequired,
  open: PropTypes.func.isRequired,
  clearNotifs: PropTypes.func.isRequired,
};

export default Notifs;
<commit_msg>fixed notif color<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import NotifBubbles from './notif_bubbles';
import { getNotifText } from '../../consts/utils';

const { ipcRenderer } = require('electron');

class Notifs extends Component {
  constructor() {
    super();
    this.state = {
      active: false,
    };
  }
  componentDidMount() {
    /*
     * In our container, which connected this component to redux,
     * we asked for auth state and said that we will dispatch notifs actions.
     * That's why we can access them as props in here.
     */
    const { fetchNotifs } = this.props;

    fetchNotifs();

    setInterval(() => {
      fetchNotifs();
    }, 10000);

    ipcRenderer.on('open_notif', () => { this.setState({ active: true }); });
  }
  componentDidUpdate(prevProps) {
    const prevNotifs = prevProps.notifs;
    if (
      !prevNotifs ||
      !this.props.notifs ||
      !this.props.auth.user
    ) {
      return;
    }
    const currentNotifs = this.props.notifs;
    const prevUnread = prevNotifs.num_unread;
    const currentUnread = currentNotifs.num_unread;
    const notifs = this.props.notifs;
    if (prevUnread < currentUnread) {
      const notif = notifs.items[0];
      const isCollab = notif.rt === 2;
      const osNotif = {
        body: getNotifText(
          notif.type,
          notifs.username_map[notif.uid].name,
          isCollab,
        ),
        id: notif.rant_id,
        content: notif,
      };
      this.props.openNotif(osNotif);
    }
  }
  toggleNotif(e) {
    if (e.target.className === 'notif_bubble_container') {
      this.setState({ active: !this.state.active });
    }
  }
  render() {
    const {
      notifs, auth, open, clearNotifs, theme,
    } = this.props;

    /* Wondering why there is notifs.notifs?
     * If you look at the default state, it looks like this:
     * const NOTIFS = { state: STATE.INITIAL, notifs: {} }
     * so in redux store, it's stored like this:
     * { ...other states, notifs: { state: STATE.INITIAL, notifs: {} } }
     * So in our container, when we ask redux for notifs, it actually gives
     * use this:
     * notifs: { state: STATE.INITIAL, notifs: {} }

     * Also, we check if notif actually exists by checking notifs.notifs.data
     * otherwise we don't show any numbers yet
     */
    if (!notifs || !auth.user) {
      return
;
    }
    return (
      <div
        className={`notifs_container ${this.state.active ? 'active' : ''}`}
        onClick={e => this.toggleNotif(e)}
      >
        <button
          className="notifs_ball"
          style={{
            backgroundColor: theme.plus_notif ? theme.plus_notif.backgroundColor : '#D55161',
            color: theme.id === 'dark_theme' ? '#ffffff' : theme.item_card.backgroundColor,
          }}
          onClick={() => { this.setState({ active: !this.state.active }); }}
        >

          <span
            className={`num_unread ${notifs.num_unread > 0 ? 'unread' : ''}`}
            style={{
              backgroundColor: theme.item_card.backgroundColor,
              color: theme.id === 'dark_theme' ? '#ffffff' : theme.item_card.color,
            }}
          >
            { notifs ? notifs.num_unread : '' }

        </button>
        <div className={`notif_bubbles ${this.state.active ? 'active' : 'inactive'}`}>
          <button
            style={{
              backgroundColor: theme.plus_notif ? theme.plus_notif.backgroundColor : '#D55161',
              color: theme.id === 'dark_theme' ? '#ffffff' : theme.item_card.backgroundColor,
            }}
            className="notifs_clear"
            onClick={() => { clearNotifs(); }}
          >Clear All
          </button>
          <NotifBubbles data={notifs} open={open} />

        <div className={`notifs_bubbles_container ${this.state.active ? 'active' : ''}`} />

    );
  }
}

Notifs.propTypes = {
  auth: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
  fetchNotifs: PropTypes.func.isRequired,
  notifs: PropTypes.object,
  openNotif: PropTypes.func.isRequired,
  open: PropTypes.func.isRequired,
  clearNotifs: PropTypes.func.isRequired,
};

export default Notifs;
<|endoftext|>


<commit_before>define(['jquery', 'bootbox'], function($, bootbox) {
    /*
     * Managing the bootbox popup on a .confirm link.
     *
     * Expected HTML structure to make this script work
     *
     */
    var init = function (l) {
        var locale = l || 'fr';
        bootbox.setDefaults({
            locale: locale
        });

        $(document).on("click", ".confirm", function(event) {
            event.preventDefault();
            var self = this;
            bootbox.confirm($(this).data('message'), function(result) {
                if (result) {
                    window.location = self.href;
                }
            });
        });
    };

    return init;
});
<commit_msg>improve confirm script by adding optional callback on post confirm<commit_after>define(['jquery', 'bootbox'], function($, bootbox) {
    /*
     * Managing the bootbox popup on a .confirm link.
     *
     * Expected HTML structure to make this script work
     *
     */
    var init = function (l, callback) {
        var locale = l || 'fr';
        bootbox.setDefaults({
            locale: locale
        });

        $(document).on("click", ".confirm", function(event) {
            event.preventDefault();
            var self = this;
            bootbox.confirm($(this).data('message'), function(result) {
                if (result) {
                    if (typeof callback === "function") {
                        callback();
                    } else {
                        window.location = self.href;
                    }
                }
            });
        });
    };

    return init;
});
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import { sortListByDate } from './helpers/sort';

/**
 * Method to render the status(es) of all interpretations on a given variant
 * Primarily for the display of all interpretations on the 'Basic Info' tab in the VCI
 * Specifically, it renders a linkout to the interpretation's evaluation summary IF the interpretation had ben approved
 * @param {object} classification - The 'provisional_variant' object associated with a given interpretation
 */
export function renderInterpretationStatus(classification) {
    const status = classification.classificationStatus;
    let affiliationId = classification.affiliation ? classification.affiliation : null;
    let userId = classification.submitted_by.slice(7, -1);
    let snapshots = classification.associatedInterpretationSnapshots && classification.associatedInterpretationSnapshots.length ? classification.associatedInterpretationSnapshots : [];
    let filteredSnapshots = [];
    // Determine whether the classification had been previously approved
    if (snapshots && snapshots.length) {
        filteredSnapshots = snapshots.filter(snapshot => {
            return snapshot.approvalStatus === 'Approved' && snapshot.resourceType === 'interpretation';
        });
        // The "In progress" label shouldn't be shown after any given number of Provisional/Approval had been saved
        let sortedSnapshots = sortListByDate(snapshots, 'date_created');
        if (status === 'In progress') {
            if (sortedSnapshots[0].approvalStatus === 'Provisioned') {
                if (filteredSnapshots.length) {
                    return (

                                APPROVED
                                View Classification
                                NEW PROVISIONAL

                    );
                } else {
                    return PROVISIONAL;
                }
            } else if (sortedSnapshots[0].approvalStatus === 'Approved') {
                return (

                            APPROVED
                            View Classification

                );
            }
        } else {
            if (status === 'Provisional') {
                if (filteredSnapshots.length) {
                    return (

                                APPROVED
                                View Classification
                                NEW PROVISIONAL

                    );
                } else {
                    return PROVISIONAL;
                }
            } else if (status === 'Approved') {
                return (

                            APPROVED
                            View Classification

                );
            }
        }
    } else {
        if (status === 'In progress') {
            return IN PROGRESS;
        }
    }
}

/**
 * Method to render linkout to the evidence summary of a given approved classification
 */
function renderViewSnapshotSummaryLink(snapshots, status, affiliationId, userId) {
    let url, snapshotUuid, param;
    let matchingSnapshots = snapshots && snapshots.length ? snapshots.filter(snapshot => snapshot.approvalStatus === status) : null;
    let snapshot = matchingSnapshots && matchingSnapshots.length ? matchingSnapshots[0] : null;
    if (snapshot) {
        snapshotUuid = snapshot['uuid'];

        if (affiliationId && affiliationId.length) {
            param = '&affiliationId=' + affiliationId;
        } else if (userId && userId.length) {
            param = '&userId=' + userId;
        }

        url = '/variant-interpretation-summary/?snapshot=' + snapshotUuid + '&status=' + status + param;

        return url;
    }
}<commit_msg>Refactor function to use shared library functions to render interpretation status labels<commit_after>'use strict';
import React from 'react';
import { renderInProgressStatus } from './render_in_progress_status';
import { renderProvisionalStatus } from './render_provisional_status';
import { renderApprovalStatus } from './render_approval_status';
import { renderNewProvisionalStatus } from './render_new_provisional_status';
import { renderPublishStatus } from './render_publish_status';

/**
 * Method to render the status(es) of all interpretations on a given variant
 * Primarily for the display of all interpretations on the 'Basic Info' tab in the VCI
 * Specifically, it renders a linkout to the interpretation's evaluation summary IF the interpretation had ben approved
 * @param {object} classification - The 'provisional_variant' object associated with a given interpretation
 */
export function renderInterpretationStatus(classification) {
    let affiliationId = classification.affiliation ? classification.affiliation : null;
    let userId = classification.submitted_by.slice(7, -1);
    let snapshots = classification.associatedInterpretationSnapshots && classification.associatedInterpretationSnapshots.length ? classification.associatedInterpretationSnapshots : [];

    if (snapshots && snapshots.length) {
        return (

                    {renderProvisionalStatus(snapshots, 'interpretation', null, null, false)}
                    {renderApprovalStatus(snapshots, 'interpretation', null, affiliationId, userId)}
                    {renderNewProvisionalStatus(snapshots, 'interpretation', null, null, false)}
                    {renderPublishStatus(snapshots)}

        );
    } else {
        return (

                    {renderInProgressStatus(classification)}

        );
    }
}
<|endoftext|>


<commit_before>function Window1(title){

	var win = Ti.UI.createWindow({
		backgroundColor: '#fff',
		title: title
	});

	// base view
	var view = Ti.UI.createView({
		backgroundImage: '/images/bg_sample.png'
	});

	// top view
	var view_top = Ti.UI.createView({
		height: '35%',
		width: 'auto',
		fill: false,
		top: 0
	});

	var icon_image = Ti.UI.createImageView({
		image: '/images/icon_umbrella.png',
		width: 130,
		top:10
	});

	// bottom view
	var view_bottom = Ti.UI.createView({
		height: '83%',
		width: 'auto',
	  	fill: false,
	  	top: '22%',
		bottom: 0
	});

	var view_bottom_back = Ti.UI.createView({
	 	backgroundColor: '#dcdcdc',
	 	opacity: 0.7,
	 	top:60,
	 	width: '80%',
		height: '70%'
	});

	var view_prof = Ti.UI.createView({
		width: '100%',
		fill: false,
		top: 0
	});

	var prof_kind = [
						{text:'相合仲間 ', num: '24人'},
						{text:'助けた回数 ', num: '2回'},
						{text:'助けてもらった回数 ', num: '2回'},
						{text:'紳士ポイント ', num: '10pt'}
					];

	var nameLabel = Ti.UI.createLabel({
		text:  Ti.App._username,
		top: 20,
    	font: { fontSize:23 },
	    color: '#000',
	    fontWeight: 'bold'
	});
	view_prof.add(nameLabel);
	var view_profLabel = Ti.UI.createView({
		height: '75%',
		top: 65,
		bottom: 0,
		layout: 'vertical'
	});

	for(var i=0;i<prof_kind.length;i++){
		var profLabel = Ti.UI.createLabel({
			left: 20,
			width: '65%',
			color: '#666'
		});
		var numLabel = Ti.UI.createLabel({
			left: 15,
			width: '20%',
			color: '#38695A',
			font: {fontSize: 20}
		});
		var view_profList = Ti.UI.createView({
			width: '100%',
			height: '21%',
			bottom: 0,
			layout: 'horizontal'
		});
		profLabel.text = prof_kind[i].text;
		numLabel.text = prof_kind[i].num;
		view_profList.add(profLabel);
		view_profList.add(numLabel);
		view_profLabel.add(view_profList);
	}
	view_prof.add(view_profLabel);
	view_top.add(icon_image);
	view_bottom_back.add(view_prof);
	view_bottom.add(view_bottom_back);

	view.add(view_top);
	view.add(view_bottom);

	win.add(view);

	return win;
}

module.exports = Window1;<commit_msg>add buyBtn into window1<commit_after>function Window1(title){

	var win = Ti.UI.createWindow({
		backgroundColor: '#fff',
		title: title
	});

	// base view
	var view = Ti.UI.createView({
		layout: 'vertical',
		backgroundImage: '/images/bg_sample.png'
	});

	// top view
	var view_top = Ti.UI.createView({
		height: '25%',
		width: 'auto',
		fill: false,
		top: 0
	});

	var icon_image = Ti.UI.createImageView({
		image: '/images/icon_umbrella.png',
		width: 130,
		//top:10
	});

	// bottom view
	var view_bottom = Ti.UI.createView({
		height: '60%',
		width: 'auto',
	  	fill: false,
	  	top: 0,
	});

	var view_bottom_back = Ti.UI.createView({
	 	backgroundColor: '#dcdcdc',
	 	opacity: 0.7,
	 	width: '80%',
		height: '90%'
	});

	var view_prof = Ti.UI.createView({
		layout: 'vertical',
		width: '80%',
		fill: false,
		height: '90%'
	});

	var prof_kind = [
						{text:'相合仲間 ', num: '24人'},
						{text:'助けた回数 ', num: '2回'},
						{text:'助けてもらった回数 ', num: '2回'},
						{text:'紳士ポイント ', num: '10pt'}
					];

	var nameLabel = Ti.UI.createLabel({
		height: '20%',
		text:  Ti.App._username,
    	font: { fontSize:23 },
	    color: '#000',
	    fontWeight: 'bold'
	});
	view_prof.add(nameLabel);
	var view_profLabel = Ti.UI.createView({
		height: '80%',
		layout: 'vertical'
	});

	for(var i=0;i<prof_kind.length;i++){
		var profLabel = Ti.UI.createLabel({
			left: 20,
			width: '65%',
			color: '#666'
		});
		var numLabel = Ti.UI.createLabel({
			left: 15,
			width: '20%',
			color: '#38695A',
			font: {fontSize: 20}
		});
		var view_profList = Ti.UI.createView({
			width: '100%',
			height: '25%',
			bottom: 0,
			layout: 'horizontal'
		});
		profLabel.text = prof_kind[i].text;
		numLabel.text = prof_kind[i].num;
		view_profList.add(profLabel);
		view_profList.add(numLabel);
		view_profLabel.add(view_profList);
	}
	view_prof.add(view_profLabel);
	view_top.add(icon_image);
	view_bottom_back.add(view_prof);
	view_bottom.add(view_bottom_back);

	var buyBtn = Ti.UI.createButton({
		height: '10%',
		width: '80%',
		title: '傘を買う',
		color: '#fff',
		backgroundImage: '/images/back-login-button.png'
	});

	view.add(view_top);
	view.add(view_bottom);
	view.add(buyBtn);

	win.add(view);

	return win;
}

module.exports = Window1;<|endoftext|>


<commit_before>var hero;
var ground;
var crates;

var spriteScale;

var spaceKey;
var swipe;

/* global game */

var level1State = {

    create: function() {
        spriteScale = 4;

        game.physics.startSystem(Phaser.Physics.ARCADE);
        //game.physics.arcade.gravity.y = 600;
        game.world.setBounds(0, 0, w + 64, game.height);
        game.stage.backgroundColor = '#3598db';

        grass = game.add.tileSprite(
            0, game.world.height - (2 * spriteScale * 16),
            w, spriteScale * 16,
            'grass');
        ground = game.add.tileSprite(
            0, game.world.height - (spriteScale * 16),
            w, spriteScale * 16,
            'ground');
        hero = game.add.sprite(w / 2 - spriteScale * 16 / 2, game.world.height - (2 * spriteScale * 16), 'hero');

        game.physics.enable([ground, hero], Phaser.Physics.ARCADE);

        grass.tileScale.y = spriteScale;
        grass.tileScale.x = spriteScale;

        ground.body.immovable = true;
        ground.body.allowGravity = false;
        ground.tileScale.y = spriteScale;
        ground.tileScale.x = spriteScale;

        hero.body.collideWorldBounds = true;
        hero.scale.setTo(spriteScale, spriteScale);
        hero.body.gravity.y = 600;

        hero.animations.add('run', [6, 7, 8, 9, 10, 11], 20, true);
        hero.animations.play('run');

        crates = this.game.add.group();
        crates.enableBody = true;
        crates.createMultiple(12, 'crate');
        crates.setAll('checkWorldBounds', true);
        crates.setAll('outOfBoundsKill', true);

        //  Register the keys.
        spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        //  Stop the following keys from propagating up to the browser
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);
        swipe = game.input.activePointer;

        this.generatePath();
    },

    update: function() {
        game.physics.arcade.collide(ground, hero);
        game.physics.arcade.collide(crates, hero);
        ground.tilePosition.x -= 2;
        grass.tilePosition.x -= 1;
        //grass.frame = Math.floor(Math.random() * 2);

        // if (cursors.left.isDown) { }
        // else if (cursors.right.isDown) { }
        if (spaceKey.isDown ||
            (swipe.isDown && (swipe.positionDown.y > swipe.position.y))) {
            if (hero.body.touching.down) {
                hero.body.velocity.y = -300;

            }
        }
        // else if (cursors.down.isDown) { }

    },
    render: function() {
        // game.debug.body(hero);
        // game.debug.body(ground);
    },
    generatePath: function() {

    }
};
<commit_msg>experiment - add crate to scene<commit_after>var hero;
var ground;
var crates;

var spriteScale;

var spaceKey;
var swipe;

/* global game */

var level1State = {

    create: function() {
        spriteScale = 4;

        game.physics.startSystem(Phaser.Physics.ARCADE);
        //game.physics.arcade.gravity.y = 600;
        game.world.setBounds(0, 0, w + 64, game.height);
        game.stage.backgroundColor = '#3598db';

        grass = game.add.tileSprite(
            0, game.world.height - (2 * spriteScale * 16),
            w, spriteScale * 16,
            'grass');
        ground = game.add.tileSprite(
            0, game.world.height - (spriteScale * 16),
            w, spriteScale * 16,
            'ground');
        hero = game.add.sprite(w / 2 - spriteScale * 16 / 2, game.world.height - (2 * spriteScale * 16), 'hero');

        grass.tileScale.y = spriteScale;
        grass.tileScale.x = spriteScale;

        crates = this.game.add.group();
        crates.enableBody = true;
        crates.createMultiple(12, 'crate');
        crates.setAll('checkWorldBounds', true);
        crates.setAll('outOfBoundsKill', true);

        var crate = crates.getFirstExists(false);
        crate.scale.setTo(spriteScale, spriteScale);2
        crate.reset(w - spriteScale * 12, game.world.height - (spriteScale * 16) - (12 * spriteScale));

        game.physics.enable([ground, hero, crate], Phaser.Physics.ARCADE);

        ground.body.immovable = true;
        ground.body.allowGravity = false;
        ground.tileScale.y = spriteScale;
        ground.tileScale.x = spriteScale;

        hero.body.collideWorldBounds = true;
        hero.scale.setTo(spriteScale, spriteScale);
        hero.body.gravity.y = 600;

        hero.animations.add('run', [6, 7, 8, 9, 10, 11], 20, true);
        hero.animations.play('run');

        //  Register the keys.
        spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        //  Stop the following keys from propagating up to the browser
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);
        swipe = game.input.activePointer;

        this.generatePath();
    },

    update: function() {
        game.physics.arcade.collide(ground, hero);
        game.physics.arcade.collide(crates, hero);
        ground.tilePosition.x -= 2;
        grass.tilePosition.x -= 1;
        //grass.frame = Math.floor(Math.random() * 2);

        // if (cursors.left.isDown) { }
        // else if (cursors.right.isDown) { }
        if (spaceKey.isDown ||
            (swipe.isDown && (swipe.positionDown.y > swipe.position.y))) {
            if (hero.body.touching.down) {
                hero.body.velocity.y = -300;
            }
        }
        // else if (cursors.down.isDown) { }

    },
    render: function() {
        // game.debug.body(hero);
        // game.debug.body(ground);
    },
    generatePath: function() {

    }
};
<|endoftext|>


<commit_before>var hero;
var ground;
var grass;
var crates;
var crate;

var spriteScale;

var spaceKey;
var swipe;

var counter = 0;
var counterText = 0;

/* global game */

var level1State = {

    create: function() {
        spriteScale = 4;

        counterText = game.add.text(0, 0, 'Counter: 0', { font: "48px Arial", fill: "#ffffff", align: "left" });

        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.world.setBounds(0, 0, w + 64, game.height);
        game.stage.backgroundColor = '#3598db';

        grass = game.add.tileSprite(
            0, game.world.height - (2 * spriteScale * 16),
            w, spriteScale * 16,
            'grass');
        ground = game.add.tileSprite(
            0, game.world.height - (spriteScale * 16),
            w, spriteScale * 16,
            'ground');
        hero = game.add.sprite(w / 2 - spriteScale * 16 / 2, game.world.height - (2 * spriteScale * 16), 'hero');

        crates = this.game.add.group();
        crates.enableBody = true;
        crates.createMultiple(12, 'crate');

        game.physics.enable([ground, hero], Phaser.Physics.ARCADE);

        grass.tileScale.y = spriteScale;
        grass.tileScale.x = spriteScale;

        ground.body.immovable = true;
        ground.body.allowGravity = false;
        ground.tileScale.y = spriteScale;
        ground.tileScale.x = spriteScale;

        hero.body.collideWorldBounds = true;
        hero.scale.setTo(spriteScale, spriteScale);
        hero.body.gravity.y = 600;

        hero.animations.add('run', [6, 7, 8, 9, 10, 11], 20, true);
        hero.animations.play('run');

        //  Register the keys.
        spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        //  Stop the following keys from propagating up to the browser
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);
        swipe = game.input.activePointer;

        game.time.events.loop(Phaser.Timer.SECOND, this.updateCounter, game);
        this.placeCrate();
    },

    update: function() {
        game.physics.arcade.collide(ground, hero);
        game.physics.arcade.collide(crate, hero, function(){
            console.log('coll!');
        }, null, this);
        ground.tilePosition.x -= 2;
        grass.tilePosition.x -= 1;

        // if (cursors.left.isDown) { }
        // else if (cursors.right.isDown) { }
        if (spaceKey.isDown ||
            (swipe.isDown && (swipe.positionDown.y > swipe.position.y))) {
            if (hero.body.touching.down) {
                hero.body.velocity.y = -350;
            }
        }
        // else if (cursors.down.isDown) { }

    },
    render: function() {
        // game.debug.body(hero);
        // game.debug.body(ground);
    },
    placeCrate: function() {
        crate = crates.getFirstExists(false);
        crate.scale.setTo(spriteScale, spriteScale);
        crate.reset(
            w,
            game.world.height - (spriteScale * 16) - (12 * spriteScale));
        crate.body.velocity.x = -500;
        crate.body.kinematic = true;
        crate.checkWorldBounds = true;
        crate.outOfBoundsKill = true;

        game.time.events.add(game.rnd.integerInRange(150, 3000), this.placeCrate, this);
    },
    updateCounter: function() {
        counter++;

        counterText.setText('Counter: ' + counter);
    }
};
<commit_msg>add initial game over condition and handler<commit_after>var hero;
var ground;
var grass;
var crates;
var crate;

var spriteScale;

var spaceKey;
var swipe;

var counter;
var counterText;
var gameOverText;

/* global game */

var level1State = {

    create: function() {
        spriteScale = 4;
        counter = 0;
        counterText = 0;

        gameOverText = game.add.text(game.world.centerX, game.world.centerY, 'Game Over', {
            font: "64px Arial",
            fill: "#ffffff",
            align: "center"
        });
        gameOverText.visible = false;

        counterText = game.add.text(0, 0, 'Counter: 0', {
            font: "48px Arial",
            fill: "#ffffff",
            align: "left"
        });

        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.world.setBounds(0, 0, w + 64, game.height);
        game.stage.backgroundColor = '#3598db';

        grass = game.add.tileSprite(
            0, game.world.height - (2 * spriteScale * 16),
            w, spriteScale * 16,
            'grass');
        ground = game.add.tileSprite(
            0, game.world.height - (spriteScale * 16),
            w, spriteScale * 16,
            'ground');
        hero = game.add.sprite(w / 2 - spriteScale * 16 / 2, game.world.height - (2 * spriteScale * 16), 'hero');

        crates = this.game.add.group();
        crates.enableBody = true;
        crates.createMultiple(12, 'crate');

        game.physics.enable([ground, hero], Phaser.Physics.ARCADE);

        grass.tileScale.y = spriteScale;
        grass.tileScale.x = spriteScale;

        ground.body.immovable = true;
        ground.body.allowGravity = false;
        ground.tileScale.y = spriteScale;
        ground.tileScale.x = spriteScale;

        hero.body.collideWorldBounds = true;
        hero.scale.setTo(spriteScale, spriteScale);
        hero.body.gravity.y = 600;

        hero.animations.add('run', [6, 7, 8, 9, 10, 11], 20, true);
        hero.animations.play('run');

        //  Register the keys.
        spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        //  Stop the following keys from propagating up to the browser
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);
        swipe = game.input.activePointer;

        game.time.events.loop(Phaser.Timer.SECOND, this.updateCounter, game);
        this.placeCrate();
    },

    update: function() {
        game.physics.arcade.collide(ground, hero);
        game.physics.arcade.collide(crate, hero, this.playerHit, null, this);
        ground.tilePosition.x -= 2;
        grass.tilePosition.x -= 1;

        // if (cursors.left.isDown) { }
        // else if (cursors.right.isDown) { }
        if (spaceKey.isDown ||
            (swipe.isDown && (swipe.positionDown.y > swipe.position.y))) {
            if (hero.body.touching.down) {
                hero.body.velocity.y = -350;
            }
        }
        // else if (cursors.down.isDown) { }

    },
    render: function() {
        // game.debug.body(hero);
        // game.debug.body(ground);
    },
    placeCrate: function() {
        crate = crates.getFirstExists(false);
        crate.scale.setTo(spriteScale, spriteScale);
        crate.reset(
            w,
            game.world.height - (spriteScale * 16) - (12 * spriteScale));
        crate.body.velocity.x = -500;
        crate.body.kinematic = true;
        crate.checkWorldBounds = true;
        crate.outOfBoundsKill = true;

        game.time.events.add(game.rnd.integerInRange(150, 3000), this.placeCrate, this);
    },
    playerHit: function() {
        this.gameOver();
    },
    updateCounter: function() {
        counter++;
        counterText.setText('Counter: ' + counter);
    },
    gameOver: function() {
        gameOverText.visible = true;
        game.paused = true;
    }
};
<|endoftext|>


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

/*****************************************************************************/

var nfc = window.nfc = {};

nfc._reset = function() {
	nfc._busName = "org.neard";
	nfc._bus = null;
	nfc._uri = null;
	nfc._manager = null;
	nfc._adapter = null;
	nfc._tag = null;
	nfc._peer = null;
	nfc.polling = false;
};

/*****************************************************************************/

nfc._NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

nfc._NDEFMessageForRecordIds = function(ids) {

	var future = new cloudeebus.Future(function (resolver) {

		var records = [];

		function onRecPropsOk(props) {
			records.push(nfc._NDEFRecordForProps(props));
			if (records.length == ids.length)
				resolver.resolve(new NDEFMessage(records), true);
		}

		for (var i=0; i<ids.length; i++) {
			var recProxy = nfc._bus.getObject(nfc._busName, ids[i]);
			recProxy.callMethod("org.neard.Record", "GetProperties",
					[]).then(onRecPropsOk, function(err) {resolver.reject(err,true)});
		}
	});

	return future;
}

/*****************************************************************************/

nfc._peerChanged = function(key, value) {

	if (key == "Records") {
		nfc._peer.props.Records = value;
		if (nfc._peer.onmessageread)
			nfc._NDEFMessageForRecordIds(nfc._peer.props.Records).then(
					function(msg) {
						nfc._peer.onmessageread({type: "messageread", param: msg});
					});
	}
};

nfc._adapterChanged = function(key, value) {

	function onTagPropsOk(props) {
		nfc._tag.props = props;
		if (nfc.ontagfound)
			nfc.ontagfound({type: "tagfound", param: nfc._tag});
	}

	function onPeerPropsOk(props) {
		nfc._peer.props = props;
		if (nfc.onpeerfound)
			nfc.onpeerfound({type: "peerfound", param: nfc._peer});
	}

	function onTagFound(tagId) {
		if (nfc._tag) /* trigger "found" callback only once */
			return;
		nfc._tag = new nfc.NFCTag(nfc._bus.getObject(nfc._busName, tagId));
		nfc._tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[]).then(onTagPropsOk);
	}

	function onPeerFound(deviceId) {
		if (nfc._peer) /* trigger "found" callback only once */
			return;
		nfc._peer = new nfc.NFCPeer(nfc._bus.getObject(nfc._busName, deviceId));
		nfc._peer.proxy.callMethod("org.neard.Device", "GetProperties",
				[]).then(onPeerPropsOk);
		nfc._peer.proxy.connectToSignal("org.neard.Device","PropertyChanged",
				nfc._peerChanged);
		}

	if (key == "Tags") {
		if (value.length == 0) {
			nfc._tag = null;
			if (nfc.ontaglost)
				nfc.ontaglost({type: "taglost"});
			nfc.startPoll();
		}
		else
			onTagFound(value[0]);
	}
	if (key == "Devices") {
		if (value.length == 0) {
			nfc._peer = null;
			if (nfc.onpeerlost)
				nfc.onpeerlost({type: "peerlost"});
			nfc.startPoll();
		}
		else
			onPeerFound(value[0]);
	}
	if (key == "Polling") {
		nfc.polling = value;
		if (value) {
			if (nfc.onpollstart)
				nfc.onpollstart({type: "pollstart"});
		}
		else {
			if (nfc.onpollstop)
				nfc.onpollstop({type: "pollstop"});
		}
	}

};

/*****************************************************************************/

nfc._init = function(uri, manifest) {
	nfc._reset();

	var future = new cloudeebus.Future(function (resolver) {
		function onAdapterPropsOk(props) {
			nfc._adapter.props = props;
			nfc.polling = props.Polling ? true : false;
			resolver.accept();
		}

		function onAdapterOk() {
			nfc._adapter.GetProperties().then(onAdapterPropsOk, onerror);
		}

		function onManagerPropsOk(props) {
			if (props.Adapters.length == 0)
				resolver.reject("No NFC Adapter found", true);
			else {
				nfc._adapter = nfc._bus.getObject(nfc._busName,
						props.Adapters[0],
						onAdapterOk,
						onerror);
				nfc._adapter.connectToSignal("org.neard.Adapter","PropertyChanged",
						nfc._adapterChanged);
			}
		}

		function onManagerOk() {
			nfc._manager.GetProperties().then(onManagerPropsOk, onerror);
		}

		function onConnectOk() {
			nfc._bus = cloudeebus.SystemBus();
			nfc._uri = uri;
			nfc._manager = nfc._bus.getObject(nfc._busName, "/", onManagerOk, onerror);
		}

		function onerror(error) {
			cloudeebus.log("NFC init error: " + error.desc);
			resolver.reject(error.desc, true);
		}

		cloudeebus.connect(uri, manifest, onConnectOk, onerror);
	});

	return future;
};

/*****************************************************************************/

nfc.startPoll = function() {
	return nfc._adapter.StartPollLoop("Initiator").then(function(){nfc.polling=true;});
};

nfc.stopPoll = function() {
	return nfc._adapter.StopPollLoop().then(function(){nfc.polling=false;});
};

/*****************************************************************************/

nfc.NFCPeer = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	this.isConnected = false;
	return this;
};

nfc.NFCPeer.prototype.sendNDEF = function(ndefMessage) {
	var futures = [];
	for (var i=0; i< ndefMessage.records.length; i++) {
		var ndefRecord = ndefMessage.records[i];
		var rec = ndefRecord.neardRecord();
		futures.push(this.proxy.callMethod("org.neard.Device", "Push", [rec]));
	}
	return cloudeebus.Future.every.apply(cloudeebus.Future,futures);
};

nfc.NFCPeer.prototype.startHandover = function(type) {
	return this.proxy.callMethod("org.neard.Device", "Push",
		[{
			 Type: "Handover",
			 Carrier: type
		}]);
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function() {
	if (!this.props)
		return cloudeebus.Future.reject("Tag properties unknown.");

	return nfc._NDEFMessageForRecordIds(this.props.Records);
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	return this.proxy.callMethod("org.neard.Tag", "Write", [rec]);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

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

/*****************************************************************************/

var nfc = window.nfc = {};

nfc._reset = function() {
	nfc._busName = "org.neard";
	nfc._bus = null;
	nfc._uri = null;
	nfc._manager = null;
	nfc._adapter = null;
	nfc._tag = null;
	nfc._peer = null;
	nfc.polling = false;
};

/*****************************************************************************/

nfc._NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

nfc._NDEFMessageForRecordIds = function(ids) {

	var promise = new cloudeebus.Promise(function (resolver) {

		var records = [];

		function onRecPropsOk(props) {
			records.push(nfc._NDEFRecordForProps(props));
			if (records.length == ids.length)
				resolver.resolve(new NDEFMessage(records), true);
		}

		for (var i=0; i<ids.length; i++) {
			var recProxy = nfc._bus.getObject(nfc._busName, ids[i]);
			recProxy.callMethod("org.neard.Record", "GetProperties",
					[]).then(onRecPropsOk, function(err) {resolver.reject(err,true)});
		}
	});

	return promise;
}

/*****************************************************************************/

nfc._peerChanged = function(key, value) {

	if (key == "Records") {
		nfc._peer.props.Records = value;
		if (nfc._peer.onmessageread)
			nfc._NDEFMessageForRecordIds(nfc._peer.props.Records).then(
					function(msg) {
						nfc._peer.onmessageread({type: "messageread", param: msg});
					});
	}
};

nfc._adapterChanged = function(key, value) {

	function onTagPropsOk(props) {
		nfc._tag.props = props;
		if (nfc.ontagfound)
			nfc.ontagfound({type: "tagfound", param: nfc._tag});
	}

	function onPeerPropsOk(props) {
		nfc._peer.props = props;
		if (nfc.onpeerfound)
			nfc.onpeerfound({type: "peerfound", param: nfc._peer});
	}

	function onTagFound(tagId) {
		if (nfc._tag) /* trigger "found" callback only once */
			return;
		nfc._tag = new nfc.NFCTag(nfc._bus.getObject(nfc._busName, tagId));
		nfc._tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[]).then(onTagPropsOk);
	}

	function onPeerFound(deviceId) {
		if (nfc._peer) /* trigger "found" callback only once */
			return;
		nfc._peer = new nfc.NFCPeer(nfc._bus.getObject(nfc._busName, deviceId));
		nfc._peer.proxy.callMethod("org.neard.Device", "GetProperties",
				[]).then(onPeerPropsOk);
		nfc._peer.proxy.connectToSignal("org.neard.Device","PropertyChanged",
				nfc._peerChanged);
		}

	if (key == "Tags") {
		if (value.length == 0) {
			nfc._tag = null;
			if (nfc.ontaglost)
				nfc.ontaglost({type: "taglost"});
			nfc.startPoll();
		}
		else
			onTagFound(value[0]);
	}
	if (key == "Devices") {
		if (value.length == 0) {
			nfc._peer = null;
			if (nfc.onpeerlost)
				nfc.onpeerlost({type: "peerlost"});
			nfc.startPoll();
		}
		else
			onPeerFound(value[0]);
	}
	if (key == "Polling") {
		nfc.polling = value;
		if (value) {
			if (nfc.onpollstart)
				nfc.onpollstart({type: "pollstart"});
		}
		else {
			if (nfc.onpollstop)
				nfc.onpollstop({type: "pollstop"});
		}
	}

};

/*****************************************************************************/

nfc._init = function(uri, manifest) {
	nfc._reset();

	var promise = new cloudeebus.Promise(function (resolver) {
		function onAdapterPropsOk(props) {
			nfc._adapter.props = props;
			nfc.polling = props.Polling ? true : false;
			resolver.fulfill();
		}

		function onAdapterOk() {
			nfc._adapter.GetProperties().then(onAdapterPropsOk, onerror);
		}

		function onManagerPropsOk(props) {
			if (props.Adapters.length == 0)
				resolver.reject("No NFC Adapter found", true);
			else {
				nfc._adapter = nfc._bus.getObject(nfc._busName,
						props.Adapters[0],
						onAdapterOk,
						onerror);
				nfc._adapter.connectToSignal("org.neard.Adapter","PropertyChanged",
						nfc._adapterChanged);
			}
		}

		function onManagerOk() {
			nfc._manager.GetProperties().then(onManagerPropsOk, onerror);
		}

		function onConnectOk() {
			nfc._bus = cloudeebus.SystemBus();
			nfc._uri = uri;
			nfc._manager = nfc._bus.getObject(nfc._busName, "/", onManagerOk, onerror);
		}

		function onerror(error) {
			cloudeebus.log("NFC init error: " + error.desc);
			resolver.reject(error.desc, true);
		}

		cloudeebus.connect(uri, manifest, onConnectOk, onerror);
	});

	return promise;
};

/*****************************************************************************/

nfc.startPoll = function() {
	return nfc._adapter.StartPollLoop("Initiator").then(function(){nfc.polling=true;});
};

nfc.stopPoll = function() {
	return nfc._adapter.StopPollLoop().then(function(){nfc.polling=false;});
};

/*****************************************************************************/

nfc.NFCPeer = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	this.isConnected = false;
	return this;
};

nfc.NFCPeer.prototype.sendNDEF = function(ndefMessage) {
	var promises = [];
	for (var i=0; i< ndefMessage.records.length; i++) {
		var ndefRecord = ndefMessage.records[i];
		var rec = ndefRecord.neardRecord();
		promises.push(this.proxy.callMethod("org.neard.Device", "Push", [rec]));
	}
	return cloudeebus.Promise.every.apply(cloudeebus.Promise,promises);
};

nfc.NFCPeer.prototype.startHandover = function(type) {
	return this.proxy.callMethod("org.neard.Device", "Push",
		[{
			 Type: "Handover",
			 Carrier: type
		}]);
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function() {
	if (!this.props)
		return cloudeebus.Promise.reject("Tag properties unknown.");

	return nfc._NDEFMessageForRecordIds(this.props.Records);
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	return this.proxy.callMethod("org.neard.Tag", "Write", [rec]);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

<|endoftext|>


<commit_before>function tooltipHtml(n, d){ /* function to create html content string in tooltip div. */
  return "
"+n+"

"+
  "
Percentage:	"+(d.feeling)+"%
"
  "
";
}

function getEmotionVals(emotion, state) {
	return Math.round(100*Math.random());
}

var states ={};
["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
.forEach(function(d){
  var feeling=getEmotionVals(0,0);
  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
});

/* draw states on id #statesvg */
uStates.draw("#statesvg", states, tooltipHtml);

d3.select(self.frameElement).style("height", "600px");<commit_msg>debugging emo_score<commit_after>function tooltipHtml(n, d){ /* function to create html content string in tooltip div. */
  return "
"+n+"

"+
  "
Percentage:	"+(d.feeling)+"%
"
  "
";
}

function emo_score() {
		var dict = {

		};
		$.ajax({
        type:     "POST",
        async: 	  false,
        url:     "../get_sentiments.php",
        success: function(data) {
            var emos = $.parseJSON(data);

            for (var i = 0; i < 50; i++) {
            	for (var key in emos[i].state) {
            		if(key !== null) {
            			dict[key] = {};
            			console.log(1);
            		}
            	}

            }

        }
    });
}

function getEmotionVals(emotion, state) {
	emo_score();
	return Math.round(100*Math.random());
}

var states ={};
["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
.forEach(function(d){
  var feeling=getEmotionVals(0,0);
  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
});

/* draw states on id #statesvg */
uStates.draw("#statesvg", states, tooltipHtml);

d3.select(self.frameElement).style("height", "600px");<|endoftext|>


<commit_before>/**
 * ngul 0.4
 * Copyright 2013 Kamalakar Gadireddy. and other contributors; https://github.com/gkodes/ngul
 * @license: MIT
 */

(function(angular, nu) {
'use strict';
/*global nu, angular: true, FileReader: true*/
  var list = angular.module('nu.list', []);
  list.directive('nuList', ['$parse',
    function($parse) { // try to rename it to collection or list
      return {
        template: '

',
        restrict: 'EACM', // 145 550 ? 12118
        replace: true,
        controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
          this.$render = angular.noop; // invokde for rending an element, expected an compiler
          this.$filter = angular.noop; // invokde before render if return false wont render that element
          this.$link = angular.noop; // invokde after render with the element
          this.$srcVar = $attrs[$attrs.nuList? 'nuList' : 'src'];
          this.$src = $parse(this.$srcVar)($scope);
          this.$indexOf = angular.noop;
          var nuList = this;

          var render = function(item) {
            var node = nuList.$render(item);
            node.data('src', item);
            nuList.$link(node);
          };

          this.$indexOf = function(node) {
            for(var i = 0; i < nuList.$src.length; i++) {
              if( angular.equals(node, nuList.$src[i]) ) {
                return i;
              }
            }
            return -1;
          };

          this.$add = function(item) {
            if(item) {
              nuList.$src.push(item);
            }
          };

          this.$remove = function(node) {
            nuList.$src.splice(nuList.$indexOf(node), 1);
          };

          this.$empty = function() {
            $element.empty();
          };

          this.$draw = function() {
            nuList.$empty();
            angular.forEach(nuList.$src, function(item) {
              if( nu.isDefinedAndNotNull(item) ) {
                render(item);
              }
            });
          };
        }],
        link: function(scope, element, attr, nuList) {
          scope.$watchCollection(nuList.$srcVar, nuList.$draw);
        }
      };
    }
  ]);

  list.directive('nuListType', [
    function() {
      var nodes = {
        'img': angular.element(''),
        'txt': angular.element('')
      };

      var engines = {
        'img': function(node) {
          return function(value) {
            node.removeClass('async').find('img')
              .attr('src', value);
          };
        },
        'txt': function(node) {
          return function(value) {
            node.removeClass('async').text(value);
          };
        }
      };

      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var engine, baseNode;
          nuList.$formatters = [];

          attr.$observe('nuListType', function(value) {
            var isIMG = value == 'img';
            engine = engines[(isIMG)? 'img' : 'txt'];
            baseNode = nodes[(isIMG)? 'img' : 'txt'];
          });

          nuList.$render = function(item) {
            //TODO: Node Pooling
            var node = baseNode.clone();
            nu.pipeLine(nuList.$formatters, engine(node))
              .onAsync(function(){
                node.addClass('async');
              }).next(item);
            nuList.$render.append(node);
            return node;
          };
          nuList.$render.append = function(node) {
            element.append(node); // angular.element(element[0])
          };
        }
      };
    }
  ]);

  list.directive('nuListRemovable', ['$parse',
    function($parse) { // ClickToRemove
      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var canRemove, remove_event = function(event) {
            var target = angular.element(event.currentTarget);
            nuList.$remove(target.data('src'));
            target.remove();
          };

          nuList.$link = function(node) {
            if(canRemove === false) { return; }
            node.addClass('remove').on('click', remove_event);
          };

          var updateView = function() {
            var nodes = element.find('span');
            if(canRemove) {
              nodes.addClass('remove').on('click', remove_event);
              return;
            }
            nodes.removeClass('remove').off('click');
          };

          attr.$observe('nuListRemovable', function(value) {
            canRemove = value === 'false'? false: true;
            updateView();
          });
        }
      };
    }
  ]);

  list.directive('nuListAddable', ['$parse',
    function($parse) { // ClickToRemove
      var linkers = {
        'img' : function(scope, element, attr, nuList) {
          var buffer = angular.element('' +
            '<input type="file">');
          var input = buffer.find('input');
          input.on('change', function(event) {
            for(var i = 0; i < event.currentTarget.files.length; i++) {
              nuList.$add(event.currentTarget.files[i]);
              scope.$digest();
            }
          });
          attr.$observe('multiple', function(value) {
            if(angular.isDefined(value) && value) { input.attr('multiple',''); }
              else { input.removeAttr('multiple'); }
          });

          //buffer.doFocus = angular.noop;
          buffer.doFocus = function(event) {
            if(event.srcElement === element[0]) {
              buffer[0].click();
            }
          };

          return buffer;
        },
        'txt' : function(scope, element, attr, nuList) {
          var buffer = angular.element(' ');

          buffer.on('keydown', function(event) {
            var keyCode = (event.which || event.keyCode);
            if (keyCode === 13) {
              var input = this.innerHTML.replace(' ','').trim();
              this.innerHTML = '';
              //this.blur();
              event.preventDefault();
              if (input !== '') {
                if (input) {
                  nuList.$add(input);
                  scope.$digest();
                }
              }
            }
          }).on('focus', function() {
            this.innerHTML = this.innerHTML.replace(' ', '');
          }).on('blur', function() { // event
            if(this.innerHTML === '') { this.innerHTML = ' '; }
          });

          buffer.doFocus = function(event) {
            event.stopPropagation();
            buffer[0].focus();
          };

          return buffer;
        }
      };

      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var buffer, elementRaw = element[0], hasBuffer, base$add = nuList.$add;
          nuList.$parsers = [];
          nuList.$add = function(item) {
            nu.pipeLine(nuList.$parsers, base$add).next(item);
          };

          var nuList$empty = nuList.$empty;
          var empty = function() {
            while(elementRaw.firstChild != elementRaw.lastChild) {
              angular.element(elementRaw.firstChild).remove();
            }
          };

          var nuList$render_append = nuList.$render.append;
          var append = function(node) {
            elementRaw.insertBefore(node[0], buffer[0]);
          };

          var picture_push = function() {
            this.done(this.result);
          };

          var picture_formatter = function(value) {
            if(value.name && value.type && value.type.match(/image.*/)) {
              var reader = new FileReader();
              reader.done = this.async();
              reader.onload = picture_push;
              reader.readAsDataURL(value);
            }
            return value;
          };

          var updateBuffer = function() {
            element.off('mouseup');
            if(buffer) {
              if( !hasBuffer && buffer[0].parentNode === element[0]) {
                element[0].removeChild(buffer[0]);
                nuList.$empty = nuList$empty;
                nuList.$render.append = nuList$render_append;
                return;
              }

              element.append(buffer);
              nuList.$empty = empty;
              nuList.$render.append = append;
              element.on('mouseup', buffer.doFocus);
            }
          };

          attr.$observe('nuListAddable', function(value) {
            hasBuffer = value !== 'false'? true: false;
            updateBuffer();
          });

          attr.$observe('nuListType', function(value) {
            var isIMG = value == 'img';
            var get_buffer = linkers[isIMG? 'img' : 'txt'];
            if(buffer) {
              if(buffer[0].parentNode === element[0]) {
                buffer.remove();
              }
              buffer.unbind();
            }

            buffer = get_buffer(scope, element, attr, nuList);
            updateBuffer();

            if(isIMG) { // TODO: remove the formater if type changes
              nuList.$formatters.push(picture_formatter);
            }
          });
        }
      };
    }
  ]);

  list.directive('nuListTypeFilter', [
    function() { // ClickToRemove
      return {
        restrict: 'A',
        require: 'nuList', // nuListAddable
        link: function(scope, element, attr, nuList) {
          var type;
          nuList.$parsers.push(function(file){
            if( !nu.isDefinedAndNotNull(type) ||
                    file.type.match(type) ) {
              return file;
            }
          });

          attr.$observe('nuListTypeFilter', function(value) {
            type = new RegExp(value);
          });
        }
      };
    }
  ]);
//TODO: Need to support two events onRemove onAdd
})(angular, nu);
<commit_msg>Update List Fix<commit_after>/**
 * ngul 0.4
 * Copyright 2013 Kamalakar Gadireddy. and other contributors; https://github.com/gkodes/ngul
 * @license: MIT
 */

(function(angular, nu) {
'use strict';
/*global nu, angular: true, FileReader: true*/
  var list = angular.module('nu.list', []);
  list.directive('nuList', [
    function() { // try to rename it to collection or list
      return {
        template: '

',
        restrict: 'EACM', // 145 550 ? 12118
        replace: true,
        controller: ['$scope', '$element', '$attrs', function($scope, $element) {
          this.$render = angular.noop; // invokde for rending an element, expected an compiler
          this.$filter = angular.noop; // invokde before render if return false wont render that element
          this.$link = angular.noop; // invokde after render with the element

          this.$indexOf = angular.noop;
          var nuList = this;

          var render = function(item) {
            var node = nuList.$render(item);
            node.data('src', item);
            nuList.$link(node);
          };

          this.$indexOf = function(node) {
            for(var i = 0; i < nuList.$src.length; i++) {
              if( angular.equals(node, nuList.$src[i]) ) {
                return i;
              }
            }
            return -1;
          };

          this.$add = function(item) {
            if(item) {
              nuList.$src.push(item);
            }
          };

          this.$remove = function(node) {
            nuList.$src.splice(nuList.$indexOf(node), 1);
          };

          this.$empty = function() {
            $element.empty();
          };

          this.$draw = function() {
            nuList.$empty();
            angular.forEach(nuList.$src, function(item) {
              if( nu.isDefinedAndNotNull(item) ) {
                render(item);
              }
            });
          };
        }],
        link: function(scope, element, attrs, nuList) {
          var src = attrs[attrs.nuList? 'nuList' : 'src'];
          scope.$watchCollection(src, function(value) {
            nuList.$src = value? value : [];
            nuList.$draw();
          });
        }
      };
    }
  ]);

  list.directive('nuListType', [
    function() {
      var nodes = {
        'img': angular.element(''),
        'txt': angular.element('')
      };

      var engines = {
        'img': function(node) {
          return function(value) {
            node.removeClass('async').find('img')
              .attr('src', value);
          };
        },
        'txt': function(node) {
          return function(value) {
            node.removeClass('async').text(value);
          };
        }
      };

      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var engine, baseNode;
          nuList.$formatters = [];

          attr.$observe('nuListType', function(value) {
            var isIMG = value == 'img';
            engine = engines[(isIMG)? 'img' : 'txt'];
            baseNode = nodes[(isIMG)? 'img' : 'txt'];
          });

          nuList.$render = function(item) {
            //TODO: Node Pooling
            var node = baseNode.clone();
            nu.pipeLine(nuList.$formatters, engine(node))
              .onAsync(function(){
                node.addClass('async');
              }).next(item);
            nuList.$render.append(node);
            return node;
          };
          nuList.$render.append = function(node) {
            element.append(node); // angular.element(element[0])
          };
        }
      };
    }
  ]);

  list.directive('nuListRemovable', [
    function() { // ClickToRemove
      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var canRemove, remove_event = function(event) {
            var target = angular.element(event.currentTarget);
            nuList.$remove(target.data('src'));
            target.remove();
          };

          nuList.$link = function(node) {
            if(canRemove === false) { return; }
            node.addClass('remove').on('click', remove_event);
          };

          var updateView = function() {
            var nodes = element.find('span');
            if(canRemove) {
              nodes.addClass('remove').on('click', remove_event);
              return;
            }
            nodes.removeClass('remove').off('click');
          };

          attr.$observe('nuListRemovable', function(value) {
            canRemove = value === 'false'? false: true;
            updateView();
          });
        }
      };
    }
  ]);

  list.directive('nuListAddable', [
    function() { // ClickToRemove
      var linkers = {
        'img' : function(scope, element, attr, nuList) {
          var buffer = angular.element('' +
            '<input type="file">');
          var input = buffer.find('input');
          input.on('change', function(event) {
            for(var i = 0; i < event.currentTarget.files.length; i++) {
              nuList.$add(event.currentTarget.files[i]);
              scope.$digest();
            }
          });
          attr.$observe('multiple', function(value) {
            if(angular.isDefined(value) && value) { input.attr('multiple',''); }
              else { input.removeAttr('multiple'); }
          });

          //buffer.doFocus = angular.noop;
          buffer.doFocus = function(event) {
            if(event.srcElement === element[0]) {
              buffer[0].click();
            }
          };

          return buffer;
        },
        'txt' : function(scope, element, attr, nuList) {
          var buffer = angular.element(' ');

          buffer.on('keydown', function(event) {
            var keyCode = (event.which || event.keyCode);
            if (keyCode === 13) {
              var input = this.innerHTML.replace(' ','').trim();
              this.innerHTML = '';
              //this.blur();
              event.preventDefault();
              if (input !== '') {
                if (input) {
                  nuList.$add(input);
                  scope.$digest();
                }
              }
            }
          }).on('focus', function() {
            this.innerHTML = this.innerHTML.replace(' ', '');
          }).on('blur', function() { // event
            if(this.innerHTML === '') { this.innerHTML = ' '; }
          });

          buffer.doFocus = function(event) {
            event.stopPropagation();
            buffer[0].focus();
          };

          return buffer;
        }
      };

      return {
        restrict: 'A',
        require: 'nuList',
        link: function(scope, element, attr, nuList) {
          var buffer, elementRaw = element[0], hasBuffer, base$add = nuList.$add;
          nuList.$parsers = [];
          nuList.$add = function(item) {
            nu.pipeLine(nuList.$parsers, base$add).next(item);
          };

          var nuList$empty = nuList.$empty;
          var empty = function() {
            while(elementRaw.firstChild != elementRaw.lastChild) {
              angular.element(elementRaw.firstChild).remove();
            }
          };

          var nuList$render_append = nuList.$render.append;
          var append = function(node) {
            elementRaw.insertBefore(node[0], buffer[0]);
          };

          var picture_push = function() {
            this.done(this.result);
          };

          var picture_formatter = function(value) {
            if(value.name && value.type && value.type.match(/image.*/)) {
              var reader = new FileReader();
              reader.done = this.async();
              reader.onload = picture_push;
              reader.readAsDataURL(value);
            }
            return value;
          };

          var updateBuffer = function() {
            element.off('mouseup');
            if(buffer) {
              if( !hasBuffer && buffer[0].parentNode === element[0]) {
                element[0].removeChild(buffer[0]);
                nuList.$empty = nuList$empty;
                nuList.$render.append = nuList$render_append;
                return;
              }

              element.append(buffer);
              nuList.$empty = empty;
              nuList.$render.append = append;
              element.on('mouseup', buffer.doFocus);
            }
          };

          attr.$observe('nuListAddable', function(value) {
            hasBuffer = value !== 'false'? true: false;
            updateBuffer();
          });

          attr.$observe('nuListType', function(value) {
            var isIMG = value == 'img';
            var get_buffer = linkers[isIMG? 'img' : 'txt'];
            if(buffer) {
              if(buffer[0].parentNode === element[0]) {
                buffer.remove();
              }
              buffer.unbind();
            }

            buffer = get_buffer(scope, element, attr, nuList);
            updateBuffer();

            if(isIMG) { // TODO: remove the formater if type changes
              nuList.$formatters.push(picture_formatter);
            }
          });
        }
      };
    }
  ]);

  list.directive('nuListTypeFilter', [
    function() { // ClickToRemove
      return {
        restrict: 'A',
        require: 'nuList', // nuListAddable
        link: function(scope, element, attr, nuList) {
          var type;
          nuList.$parsers.push(function(file){
            if( !nu.isDefinedAndNotNull(type) ||
                    file.type.match(type) ) {
              return file;
            }
          });

          attr.$observe('nuListTypeFilter', function(value) {
            type = new RegExp(value);
          });
        }
      };
    }
  ]);
//TODO: Need to support two events onRemove onAdd
})(angular, nu);
<|endoftext|>