<commit_before>var azure = require('azure');
var appInsights = require("applicationinsights");
var config = require('./config');

appInsights.setup(config.AppInsightsKey).start();
<commit_msg>facebook<commit_after>var azure = require('azure');
var appInsights = require("applicationinsights");
var config = require('./config');

appInsights.setup(config.AppInsightsKey).start();<|endoftext|>


<commit_before>/**
 * Simulates the robot runtime for development and testing purposes.
 *
 * NOTE: FakeRuntime is NOT transpiled or bundled by webpack like most of the other JS code
 * It will be run "as is" as a child-process of the rest of the application.
 * Some experimental features that are used elsewhere in Dawn may not be available here.
 */

const dgram = require('dgram');
const ProtoBuf = require('protobufjs');
const _ = require('lodash');

const builder = ProtoBuf.loadProtoFile('./main/ansible/ansible.proto');
const AnsibleMain = builder.build('main');
const DawnData = AnsibleMain.DawnData;

const clientPort = '12346'; // send port
const serverPort = '12345'; // receive port
const hostname = 'localhost';
const client = dgram.createSocket('udp4');// sender
const server = dgram.createSocket('udp4'); // receiver

/**
 * Handler to receive messages from Dawn.
 * We don't do anything besides decode it and print it out.
 */
server.on('message', (msg, rinfo) => {
  // Decode and get the raw object.
  const data = DawnData.decode(msg).toRaw();
  console.log(`FakeRuntime received: ${JSON.stringify(data)}\n`);
});

server.bind(serverPort, hostname);

/**
 * Returns a random number between min and max.
 */
const randomFloat = (min, max) => ((max - min) * Math.random() + min);

/**
 * Generate fake data to send to Dawn
 */
const generateFakeData = () => [
  {
    type: 'UPDATE_STATUS',
    status: { value: 0 },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Motor 1',
      peripheralType: 'MOTOR_SCALAR',
      value: randomFloat(-100, 100),
      id: '1',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Limit Switch 1',
      peripheralType: 'LimitSwitch',
      value: Math.round(randomFloat(0, 1)),
      id: '2',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Scalar Sensor 1',
      peripheralType: 'SENSOR_SCALAR',
      value: randomFloat(-100, 100),
      id: '3',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Servo 1',
      peripheralType: 'ServoControl',
      value: Math.round(randomFloat(0, 180)),
      id: '4',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Color Sensor 1',
      peripheralType: 'ColorSensor',
      value: [
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 360)),
        Math.round(randomFloat(0, 360)),
      ],
      id: '5',
    },
  },
  {
    type: 'UPDATE_CONSOLE',
    value: 'Some print statement\n',
  },
];

/**
 * Send the encoded randomly generated data to Dawn
 */
setInterval(() => {
  const fakeData = generateFakeData();
  // Don't know what Runtime protobufs look like so
  // we are encoding with JSON for right now.
  const encodedData = JSON.stringify(fakeData);
  client.send(encodedData, clientPort, hostname);
}, 500);
<commit_msg>Fix proto path<commit_after>/**
 * Simulates the robot runtime for development and testing purposes.
 *
 * NOTE: FakeRuntime is NOT transpiled or bundled by webpack like most of the other JS code
 * It will be run "as is" as a child-process of the rest of the application.
 * Some experimental features that are used elsewhere in Dawn may not be available here.
 */

const dgram = require('dgram');
const ProtoBuf = require('protobufjs');
const _ = require('lodash');

const builder = ProtoBuf.loadProtoFile('./main/ansible/ansible-protos/ansible.proto');
const DawnData = builder.build('DawnData');

const clientPort = '12346'; // send port
const serverPort = '12345'; // receive port
const hostname = 'localhost';
const client = dgram.createSocket('udp4');// sender
const server = dgram.createSocket('udp4'); // receiver

/**
 * Handler to receive messages from Dawn.
 * We don't do anything besides decode it and print it out.
 */
server.on('message', (msg, rinfo) => {
  // Decode and get the raw object.
  const data = DawnData.decode(msg).toRaw();
  console.log(`FakeRuntime received: ${JSON.stringify(data)}\n`);
});

server.bind(serverPort, hostname);

/**
 * Returns a random number between min and max.
 */
const randomFloat = (min, max) => ((max - min) * Math.random() + min);

/**
 * Generate fake data to send to Dawn
 */
const generateFakeData = () => [
  {
    type: 'UPDATE_STATUS',
    status: { value: 0 },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Motor 1',
      peripheralType: 'MOTOR_SCALAR',
      value: randomFloat(-100, 100),
      id: '1',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Limit Switch 1',
      peripheralType: 'LimitSwitch',
      value: Math.round(randomFloat(0, 1)),
      id: '2',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Scalar Sensor 1',
      peripheralType: 'SENSOR_SCALAR',
      value: randomFloat(-100, 100),
      id: '3',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Servo 1',
      peripheralType: 'ServoControl',
      value: Math.round(randomFloat(0, 180)),
      id: '4',
    },
  },
  {
    type: 'UPDATE_PERIPHERAL',
    peripheral: {
      name: 'Color Sensor 1',
      peripheralType: 'ColorSensor',
      value: [
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 255)),
        Math.round(randomFloat(0, 360)),
        Math.round(randomFloat(0, 360)),
      ],
      id: '5',
    },
  },
  {
    type: 'UPDATE_CONSOLE',
    value: 'Some print statement\n',
  },
];

/**
 * Send the encoded randomly generated data to Dawn
 */
setInterval(() => {
  const fakeData = generateFakeData();
  // Don't know what Runtime protobufs look like so
  // we are encoding with JSON for right now.
  const encodedData = JSON.stringify(fakeData);
  client.send(encodedData, clientPort, hostname);
}, 500);
<|endoftext|>


<commit_before>"use strict";

var Stroke = function(brush) {
    this.brush = brush;
    this.traces = [];
};

var Trace = function(x, y, p, t) {
    this.x = x;
    this.y = y;
    this.p = p;
    this.t = t;
};

var Brush = function(radius, globalAlpha, spacing) {
    var distance;
    var prevX;
    var prevY;
    var prevP;
    var lastX;
    var lastY;
    var direction;
    this.name = 'arc';
    this.radius = radius;
    this.globalAlpha = globalAlpha;
    this.spacing = spacing;
    this.draw = function(canvas, trace) {
        var ctx = canvas[0].getContext('2d');
        ctx.globalAlpha = this.globalAlpha;
        ctx.fillStyle = this.fillStyle;
        ctx.globalCompositeOperation = this.globalCompositeOperation;
        ctx.beginPath();
        ctx.arc(trace.x, trace.y, trace.p * this.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
    };
    this.down = function(canvas, trace) {
        isDrawing = true;
        lastX = prevX = trace.x;
        lastY = prevY = trace.y;
        prevP = trace.p;
        distance = 0;
        stroke.traces.push(trace);
        this.draw(canvas, trace);
    };
    this.move = function(canvas, trace) {
        if (isDrawing) {
            var dx = trace.x - prevX;
            var dy = trace.y - prevY;
            var dp = trace.p - prevP;
            distance += Math.sqrt(dx * dx + dy * dy);
            prevX = trace.x;
            prevY = trace.y;
            var ldx = trace.x - lastX;
            var ldy = trace.y - lastY;
            var ld = Math.sqrt(ldx * ldx + ldy * ldy);
            direction = Math.atan2(ldy, ldx);
            var midScale = (prevP + trace.p) / 2;
            var drawSpacing = this.radius * this.spacing * midScale;
            if (drawSpacing === 0) {
                return
            }
            if (distance < drawSpacing) {
                prevP = trace.p;
                return
            }
            var scaleSpacing = dp * (drawSpacing / distance);
            if (ld < drawSpacing) {
                lastX = trace.x;
                lastY = trace.y;
                distance -= drawSpacing;
                stroke.traces.push(trace);
                this.draw(canvas, new Trace(lastX, lastY, trace.p, new Date().getTime()));
            } else {
                while (distance >= drawSpacing) {
                    var tx = Math.cos(direction);
                    var ty = Math.sin(direction);
                    lastX += tx * drawSpacing;
                    lastY += ty * drawSpacing;
                    prevP += scaleSpacing;
                    distance -= drawSpacing;
                    stroke.traces.push(trace);
                    this.draw(canvas, new Trace(lastX, lastY, prevP, new Date().getTime()));
                }
            }
        }
    };
};

var brush;
var stroke;
var isLocked;
var isDrawing;

function getPressure() {
    var wacom = document.getElementById('wacom').penAPI;
    if (wacom === undefined) {
        return 0.5
    } else {
        return wacom.pressure
    }
}

$(document).ready(function() {
    var strokes = [];
    var save = $('#save');
    var canvas = $('#canvas');
    canvas.on('mousedown', function(e) {
        if (!isLocked) {
            isLocked = true;
            $('#width').prop('disabled', true);
            $('#height').prop('disabled', true);
        }
        isDrawing = true;
        brush = new Brush(
            $('#radius').val(),
            $('#flow').val(),
            $('#spacing').val()
        );
        if ($('#eraser').is(':checked')) {
            brush.globalCompositeOperation = 'destination-out';
        } else {
            brush.globalCompositeOperation = 'source-over';
            brush.fillStyle = $('#color').val();
        }
        stroke = new Stroke(brush);
        brush.down(canvas, new Trace(e.offsetX, e.offsetY, getPressure(), new Date().getTime()));
    });
    canvas.on('mousemove', function(e) {
        if (isDrawing) {
            brush.move(canvas, new Trace(e.offsetX, e.offsetY, getPressure(), new Date().getTime()));
        }
    });
    canvas.on('mouseup mouseleave', function() {
        if (stroke) {
            strokes.push(stroke);
        }
        isDrawing = false;
        brush = undefined;
        stroke = undefined;
    });
    save.submit(function(e) {
        $.ajax({
            url: save[0].action,
            type: save[0].method,
            dataType: 'json',
            data: {
                title: $('#title').val(),
                description: $('#description').val(),
                canvas: canvas[0].toDataURL(),
                strokes: JSON.stringify(strokes)
            },
            success: function(data) {
                window.location.replace(data.location);
            }
        });
        e.preventDefault();
    });
    var width = $('#width');
    width.on('change', function() {
        canvas[0].width = width.val();
    });
    var height = $('#height');
    height.on('change', function() {
        canvas[0].height = height.val();
    })
});
<commit_msg>Pass Wacom object to getPressure<commit_after>"use strict";

var Stroke = function(brush) {
    this.brush = brush;
    this.traces = [];
};

var Trace = function(x, y, p, t) {
    this.x = x;
    this.y = y;
    this.p = p;
    this.t = t;
};

var Brush = function(radius, globalAlpha, spacing) {
    var distance;
    var prevX;
    var prevY;
    var prevP;
    var lastX;
    var lastY;
    var direction;
    this.name = 'arc';
    this.radius = radius;
    this.globalAlpha = globalAlpha;
    this.spacing = spacing;
    this.draw = function(canvas, trace) {
        var ctx = canvas[0].getContext('2d');
        ctx.globalAlpha = this.globalAlpha;
        ctx.fillStyle = this.fillStyle;
        ctx.globalCompositeOperation = this.globalCompositeOperation;
        ctx.beginPath();
        ctx.arc(trace.x, trace.y, trace.p * this.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
    };
    this.down = function(canvas, trace) {
        isDrawing = true;
        lastX = prevX = trace.x;
        lastY = prevY = trace.y;
        prevP = trace.p;
        distance = 0;
        stroke.traces.push(trace);
        this.draw(canvas, trace);
    };
    this.move = function(canvas, trace) {
        if (isDrawing) {
            var dx = trace.x - prevX;
            var dy = trace.y - prevY;
            var dp = trace.p - prevP;
            distance += Math.sqrt(dx * dx + dy * dy);
            prevX = trace.x;
            prevY = trace.y;
            var ldx = trace.x - lastX;
            var ldy = trace.y - lastY;
            var ld = Math.sqrt(ldx * ldx + ldy * ldy);
            direction = Math.atan2(ldy, ldx);
            var midScale = (prevP + trace.p) / 2;
            var drawSpacing = this.radius * this.spacing * midScale;
            if (drawSpacing === 0) {
                return
            }
            if (distance < drawSpacing) {
                prevP = trace.p;
                return
            }
            var scaleSpacing = dp * (drawSpacing / distance);
            if (ld < drawSpacing) {
                lastX = trace.x;
                lastY = trace.y;
                distance -= drawSpacing;
                stroke.traces.push(trace);
                this.draw(canvas, new Trace(lastX, lastY, trace.p, new Date().getTime()));
            } else {
                while (distance >= drawSpacing) {
                    var tx = Math.cos(direction);
                    var ty = Math.sin(direction);
                    lastX += tx * drawSpacing;
                    lastY += ty * drawSpacing;
                    prevP += scaleSpacing;
                    distance -= drawSpacing;
                    stroke.traces.push(trace);
                    this.draw(canvas, new Trace(lastX, lastY, prevP, new Date().getTime()));
                }
            }
        }
    };
};

var brush;
var stroke;
var isLocked;
var isDrawing;

function getPressure(wacom) {
    if (wacom === undefined) {
        return 0.5
    } else {
        return wacom.pressure
    }
}

$(document).ready(function() {
    var wacom = document.getElementById('wacom').penAPI;
    var strokes = [];
    var save = $('#save');
    var canvas = $('#canvas');
    canvas.on('mousedown', function(e) {
        if (!isLocked) {
            isLocked = true;
            $('#width').prop('disabled', true);
            $('#height').prop('disabled', true);
        }
        isDrawing = true;
        brush = new Brush(
            $('#radius').val(),
            $('#flow').val(),
            $('#spacing').val()
        );
        if ($('#eraser').is(':checked')) {
            brush.globalCompositeOperation = 'destination-out';
        } else {
            brush.globalCompositeOperation = 'source-over';
            brush.fillStyle = $('#color').val();
        }
        stroke = new Stroke(brush);
        brush.down(canvas, new Trace(e.offsetX, e.offsetY, getPressure(wacom), new Date().getTime()));
    });
    canvas.on('mousemove', function(e) {
        if (isDrawing) {
            brush.move(canvas, new Trace(e.offsetX, e.offsetY, getPressure(wacom), new Date().getTime()));
        }
    });
    canvas.on('mouseup mouseleave', function() {
        if (stroke) {
            strokes.push(stroke);
        }
        isDrawing = false;
        brush = undefined;
        stroke = undefined;
    });
    save.submit(function(e) {
        $.ajax({
            url: save[0].action,
            type: save[0].method,
            dataType: 'json',
            data: {
                title: $('#title').val(),
                description: $('#description').val(),
                canvas: canvas[0].toDataURL(),
                strokes: JSON.stringify(strokes)
            },
            success: function(data) {
                window.location.replace(data.location);
            }
        });
        e.preventDefault();
    });
    var width = $('#width');
    width.on('change', function() {
        canvas[0].width = width.val();
    });
    var height = $('#height');
    height.on('change', function() {
        canvas[0].height = height.val();
    })
});
<|endoftext|>


<commit_before>
/*************************888888888888888*******************
 * 3D Cone To Tetrahedron Animation With Virtual Trackball *
 * Design by ZulNs @Yogyakarta, December 2015              *
 ***********************************************************/

var _diameter = 100,
	_height = 140,
	_bladesNumber = 12,
	_opacity = 0.75,
	_transitionInterval = 3000,
	_transformInterval = 2000,
	_modelName = 'cone',
	_model,
	_cssRules = '',
	_isPaused = false,
	_isManual = false,
	_dragging = false,
	_isFiredByMouse = false,
	_touchId,
	_lastTransform, _matrix, _spx, _spy,
	_productToRadians,
	_isTransitionStopped = true,
	_transitionTimer,
	_currentTransition = 0,
	_isTransformStopped = false,
	_transformTimer,
	_currentBladesNumber = _bladesNumber,
	_bladesAdder = -1,
	_animate = document.getElementById('toggle-animation'),
	_transist = document.getElementById('toggle-transition'),
	_transform = document.getElementById('toggle-transform'),
	_diameterInput = document.getElementById('diameter-length'),
	_heightInput = document.getElementById('height-value'),
	_bladesNumberInput = document.getElementById('blades-number'),
	_opacityInput = document.getElementById('opacity-value'),
	_intervalInput = document.getElementById('transition-interval'),
	_transformIntervalInput = document.getElementById('transform-interval'),
	_transitionIntervalInput = document.getElementById('transition-interval');

init();

function init() {
	document.querySelector('#title span').innerHTML = document.title;
	if (document.location.search.toLowerCase() === '?3d')
		document.querySelector('#title a').href = '../cuboid3d.html?3';
	_diameterInput.value = _diameter;
	_heightInput.value = _height;
	_bladesNumberInput.value = _bladesNumber;
	_opacityInput.value = _opacity * 100;
	_transitionIntervalInput.value = _transitionInterval;
	_transformIntervalInput.value = _transformInterval;
	for (var i = 1; i <= 6; i++)
		document.getElementById('unpack-' + i).checked = false;
	appendModel();
	_model.classList.add('animate');
	if (_bladesNumber > 3)
		_transformTimer = window.setInterval(nextTransform, _transformInterval);
	else {
		toggleTransform();
		_transform.disabled = true;
	}
}

function appendModel() {
	var wrap = document.createElement("div");
	_model = document.createElement("div");
	wrap.classList.add(_modelName + '-wrapper');
	_model.classList.add(_modelName);
	createModel(_model, _diameter, _height, _bladesNumber, _opacity);
	wrap.appendChild(_model);
	document.body.appendChild(wrap);
	_model.setAttribute('draggable', 'false');
	addEvent(_model, 'mousedown', handleMouseDown);
	addEvent(_model, 'mousemove', handleMouseMove);
	addEvent(document, 'mouseup', handleMouseUp);
	if ('touchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0) {
		addEvent(_model, 'touchstart', handleTouchStart);
		addEvent(_model, 'touchmove', handleTouchMove);
		addEvent(document, 'touchcancel', handleTouchEnd);
		addEvent(document, 'touchend', handleTouchEnd);
	}
}

function addEvent(elm, evt, callback) {
	if (!!window.addEventListener)
		elm.addEventListener(evt, callback);
	else
		elm.attachEvent('on' + evt, callback);
}

function handleMouseDown(evt) {
	if (!_dragging) {
		var e = evt || window.event;
		e.preventDefault();
		e.stopPropagation();
		_isFiredByMouse = true;
		startDragging(e.pageX, e.pageY);
	}
}

function handleMouseMove(evt) {
	if (_dragging && _isFiredByMouse) {
		var e = evt || window.event;
		e.preventDefault();
		whileDragging(e.pageX, e.pageY);
	}
}

function handleMouseUp(evt) {
	if (_dragging && _isFiredByMouse) {
		var e = evt || window.event;
		e.preventDefault();
		endDragging();
	}
}

function handleTouchStart(evt) {
	var e = evt || window.event;
	if (_dragging && !_isFiredByMouse && e.touches.length == 1) endDragging();
	if (!_dragging) {
		var touch = e.changedTouches[0];
		e.preventDefault();
		//e.stopPropagation();
		_isFiredByMouse = false;
		_touchId = touch.identifier;
		startDragging(touch.pageX, touch.pageY);
	}
}

function handleTouchMove(evt) {
	if (_dragging && !_isFiredByMouse) {
		var e = evt || window.event,
			touches = e.changedTouches,
			touch;
		for (var i = 0; i < touches.length; i++) {
			touch = touches[i];
			if (touch.identifier === _touchId) {
				e.preventDefault();
				whileDragging(touch.pageX, touch.pageY);
				break;
			}
		}
	}
}

function handleTouchEnd(evt) {
	if (_dragging && !_isFiredByMouse) {
		var e = evt || window.event,
			touches = e.changedTouches,
			touch;
		for (var i = 0; i < touches.length; i++) {
			touch = touches[i];
			if (touch.identifier === _touchId) {
				e.preventDefault();
				endDragging();
				return;
			}
		}
	}
}

function startDragging(spx, spy) {
	_spx = spx;
	_spy = spy;
	_dragging = true;
	if (!_isPaused) toggleAnimation();
	if (!_isManual) {
		_lastTransform = window.getComputedStyle(_model).getPropertyValue('transform');
		_matrix = toArray(_lastTransform);
		_model.classList.remove('animate');
		_model.classList.remove('paused');
		_model.style.cssText = addVendorPrefix('transform: ' + _lastTransform + ';');
		_isManual = true;
		_animate.innerHTML = 'Animate';
	}
}

function whileDragging(cpx, cpy) {
	var sx, sy, x = 0, y = 0, z = 0, cr = 0.5, rad, css;
	if (_spx != cpx || _spy != cpy) {
		sx = (_spy - cpy);
		sy = (cpx - _spx);
		rad = Math.sqrt(sx * sx + sy * sy) * _productToRadians;
		x = sx * _matrix[0] + sy * _matrix[1];
		y = sx * _matrix[4] + sy * _matrix[5];
		z = sx * _matrix[8] + sy * _matrix[9];
		css = 'transform: ' + _lastTransform + ' rotate3d(' + x + ', ' + y + ', ' + z + ', ' + rad + 'rad);';
		_model.style.cssText = addVendorPrefix(css);
	}
}

function endDragging() {
	_dragging = false;
	_lastTransform = window.getComputedStyle(_model).getPropertyValue('transform');
	_matrix = toArray(_lastTransform);
}

function applyEntries() {
	var dl = getIntValue(_diameterInput.value),
		h = getIntValue(_heightInput.value),
		bn = getIntValue(_bladesNumberInput.value),
		ov = getIntValue(_opacityInput.value),
		tsi = getIntValue(_transitionIntervalInput.value),
		tfi = getIntValue(_transformIntervalInput.value);
	if (dl < 1) dl = 1;
	if (h < 1) h = 1;
	if (bn < 3) bn = 3;
	if (ov < 0) ov = 0;
	if (ov > 100) ov = 100;
	if (tsi < 1000) tsi = 1000;
	if (tfi < 1000) tfi = 1000;
	_diameterInput.value = dl;
	_heightInput.value = h;
	_bladesNumberInput.value = bn;
	_opacityInput.value = ov;
	_transitionIntervalInput.value = tsi;
	_transformIntervalInput.value = tfi;
	ov /= 100;
	if (dl != _diameter || h != _height || bn != _bladesNumber || ov != _opacity) {
		if (!_isTransformStopped) window.clearInterval(_transformTimer);
		_transform.disabled = (bn == 3);
		_diameter = dl;
		_height = h;
		_bladesNumber = bn;
		_opacity = ov;
		_currentBladesNumber = bn;
		_bladesAdder = -1;
		recreateModel(_model, dl, h, bn, ov);
		if (!_isTransformStopped && bn > 3)
			_transformTimer = window.setInterval(nextTransform, _transformInterval);
		if (!_isTransformStopped && bn == 3)
			toggleTransform();
	}
	if (tsi != _transitionInterval) {
		_transitionInterval = tsi;
		if (!_isTransitionStopped) {
			window.clearInterval(_transitionTimer);
			_transitionTimer = window.setInterval(nextTransition, _transitionInterval);
		}
	}
	if (tfi != _transformInterval) {
		_transformInterval = tfi;
		if (!_isTransformStopped) {
			window.clearInterval(_transformTimer);
			_transformTimer = window.setInterval(nextTransform, _transformInterval);
		}
	}
}

function getIntValue(value) {
	var iv = parseInt(value);
	if (isNaN(iv)) iv = 0;
	return iv;
}

function toggleAnimation() {
	if (_isManual) {
		_model.style.cssText = '';
		_model.classList.add('animate');
		_isManual = false;
		_dragging = false;
		_animate.innerHTML = 'Pause Animation';
	}
	else {
		if (_isPaused) {
			_model.classList.remove('paused');
			_animate.innerHTML = 'Pause Animation';
		}
		else {
			_model.classList.add('paused');
			_animate.innerHTML = 'Continue Animation';
		}
	}
	_isPaused ^= true;
}

function toggleTransition() {
	if (_isTransitionStopped) {
		_transist.innerHTML = 'Stop All Transitions';
		_transitionTimer = window.setInterval(nextTransition, _transitionInterval);
	}
	else {
		window.clearInterval(_transitionTimer);
		uncheckLastOption();
		_currentTransition = 0;
		_transist.innerHTML = 'Play All Transitions';
	}
	_isTransitionStopped ^= true;
}

function toggleTransform() {
	if (_isTransformStopped) {
		_transform.innerHTML = 'Stop Transform';
		_transformTimer = window.setInterval(nextTransform, _transformInterval);
	}
	else {
		window.clearInterval(_transformTimer);
		_transform.innerHTML = 'Start Transform';
	}
	_isTransformStopped ^= true;
}

function unpack(idNum) {
	if (document.getElementById('unpack-' + idNum).checked) {
		uncheckLastOption();
		_model.classList.add('unpack-' + idNum);
		_currentTransition = idNum;
	}
	else {
		_model.classList.remove('unpack-' + idNum);
		_currentTransition = 0;
	}
}

function uncheckLastOption() {
	if (_currentTransition) {
		document.getElementById('unpack-' + _currentTransition).checked = false;
		_model.classList.remove('unpack-' + _currentTransition);
	}
}

function nextTransition() {
	var t = ~~(Math.random() * 7);
	if (t == _currentTransition) t = ++t % 7;
	if (t) {
		document.getElementById('unpack-' + t).checked = true;
		unpack(t);
	}
	else {
		uncheckLastOption();
		_currentTransition = 0;
	}
}

function nextTransform() {
	_currentBladesNumber += _bladesAdder;
	if (_currentBladesNumber < 3) {
		_currentBladesNumber = 4;
		_bladesAdder = 1;
	}
	else if (_currentBladesNumber > _bladesNumber) {
		_currentBladesNumber = _bladesNumber - 1;
		_bladesAdder = -1;
	}
	recreateModel(_model, _diameter, _height, _currentBladesNumber, _opacity);
}

function toArray(str) {
	var res = [], arr = str.substring(9, str.length -1).split(',');
	for (var i in arr) res.push(parseFloat(arr[i]));
	return res;
}

function addVendorPrefix(property) {
	return	'-webkit-' + property +
			'-moz-' + property +
			'-o-' + property +
			property;
}

function getRainbowColor(step, numOfSteps) {
	var h = (step % numOfSteps) / numOfSteps,
		i = ~~(h * 6),
		a = h * 6 - i,
		d = 1 - a;
	switch (i) {
		case 0: r = 1; g = a; b = 0; break;
		case 1: r = d; g = 1; b = 0; break;
		case 2: r = 0; g = 1; b = a; break;
		case 3: r = 0; g = d; b = 1; break;
		case 4: r = a; g = 0; b = 1; break;
		case 5: r = 1; g = 0; b = d;
	}
	var c = '#' + ('0' + (~~(r * 255)).toString(16)).slice(-2) + ('0' + (~~(g * 255)).toString(16)).slice(-2) + ('0' + (~~(b * 255)).toString(16)).slice(-2);
	return c;
}

function recreateModel(model, diameter, height, bladesNumber, opacity) {
	var nodes = document.querySelectorAll('.' + _modelName + ' svg');
	for (var i = 0; i < nodes.length; i++) nodes[i].parentNode.removeChild(nodes[i]);
	document.getElementById(_modelName + '-style').remove();
	createModel(model, diameter, height, bladesNumber, opacity);
}

function createModel(model, diameter, height, bladesNumber, opacity) {
	var baseAngle = Math.PI / bladesNumber,
		bladeAngle = 2 * baseAngle,
		tiltAngle = Math.atan2(diameter / 2, height),
		bladeW = diameter * Math.tan(baseAngle),
		bladeH = height / Math.cos(tiltAngle),
		coverW = diameter,
		coverH = diameter,
		outerDia,
		halfS = (bladesNumber - bladesNumber % 2) / 2,
		style = document.createElement('style');
	_productToRadians = 2 * Math.PI / (bladeH + bladeH + diameter);
	if (bladesNumber % 4) {
		outerDia = diameter / Math.cos(baseAngle);
		if (bladesNumber % 2) {
			coverW = outerDia * Math.sin(Math.PI * (bladesNumber - 1) / 2 / bladesNumber);
			coverH = (outerDia + diameter) / 2;
		}
		else
			coverW = outerDia;
	}
	model.appendChild(createFace(coverW, coverH, Math.PI / 2, diameter, height, bladesNumber, bladeW, bladeH, bladeAngle, tiltAngle, 'rainbow-gradient', opacity, 'cover', false));
	for (var c = 0; c < bladesNumber; c++)
		model.appendChild(createFace(bladeW, bladeH, bladeAngle * (c - halfS), diameter, height, bladesNumber, bladeW, bladeH,
				bladeAngle, tiltAngle, getRainbowColor(c, bladesNumber), opacity, 'side-' + c.toString(), true));
	style.type = 'text/css';
	style.id = _modelName + '-style';
	if (style.styleSheet)
		style.styleSheet.cssText = _cssRules;
	else
		style.innerHTML = _cssRules;
	_cssRules = '';
	document.head.appendChild(style);
}

function createFace(w, h, r, dia, ch, bn, bw, bh, ba, ta, color, opacity, cname, isSide) {
	var face = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
		shape, points = '', css, tx, ty, tz,
		cssText =
			'margin-left: ' + (-w / 2).toFixed(0) + 'px;' +
			'margin-top: ' + (-h / 2).toFixed(0) + 'px;';
	face.setAttribute('width', w.toFixed(0));
	face.setAttribute('height', h.toFixed(0));
	if (isSide) {
		var p0 = '0,0',
			p1 = (w / 2).toFixed(0) + ',' + (h).toFixed(0),
			p2 = w.toFixed(0) + ',0';
		points = p0 + ' ' + p1 + ' ' + p2;
		shape = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
		shape.setAttribute('points', points);
		shape.style.cssText = 'fill:' + color + '; opacity:' + opacity + '; stroke:white; stroke-width:1;';
		face.appendChild(shape);
		cssText += addVendorPrefix('transform-origin: top;');
		ty = (h - ch) / 2;
		tz = dia / 2;
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) rotateX(' + -ta + 'rad);';
	}
	else {
		var px = (w - bw) / 2, py = h,
			cx = w / 2, cy = h - dia /2,
			cxy = ' ' + cx.toFixed(0) + ',' + cy.toFixed(0),
			halfS = (bn - bn % 2) / 2;
		for (var i = 0; i < bn;  i++) {
			points = px.toFixed(0) + ',' + py.toFixed(0);
			px += Math.cos(i * ba) * bw;
			py -= Math.sin(i * ba) * bw;
			points += ' ' + px.toFixed(0) + ',' + py.toFixed(0) + cxy;
			shape = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
			shape.setAttribute('points', points);
			shape.style.cssText = 'fill:' + getRainbowColor((i + halfS) % bn, bn) + '; opacity:' + opacity + '; stroke:white; stroke-width:1;';
			face.appendChild(shape);
		}
		cssText += addVendorPrefix('transform-origin: bottom;');
		ty = dia / 2;
		tz = (ch + h) / 2;
		css = 'transform: rotateX(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px);';
	}
	cssText += addVendorPrefix(css);
	if (isSide)
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + (tz + dia / 2).toFixed(0) + 'px) rotateX(' + -ta + 'rad) !important;';
	else
		css = 'transform: rotateX(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + (tz + dia / 2).toFixed(0) + 'px) !important;';
	_cssRules += '.unpack-6 .' + cname + ' {' + addVendorPrefix(css) + '}';
	if (isSide) {
		tx = r / 2 / Math.PI * (w - 1) * bn;
		css = 'transform: translate3d(' + tx.toFixed(0) + 'px, 0px, ' + tz.toFixed(0) + 'px) !important;';
	}
	else {
		ty = (-bh - h) / 2;
		tz = dia / 2;
		css = 'transform: translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) !important;';
	}
	_cssRules += '.unpack-1 .' + cname + ' {' + addVendorPrefix(css) + '}';
	if (isSide) {
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) rotateX(90deg) !important;';
		_cssRules += '.unpack-2 .' + cname + ' {' + addVendorPrefix(css) + '}';
		ty += ch;
		tz = h;
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) rotateX(-90deg) !important;';
		_cssRules += '.unpack-3 .' + cname + ' {' + addVendorPrefix(css) + '}';
		tz += dia / 2;
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) rotateX(-90deg) !important;';
		_cssRules += '.unpack-4 .' + cname + ' {' + addVendorPrefix(css) + '}';
		ty = (h - ch) / 2;
		tz = dia;
		css = 'transform: rotateY(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) rotateX(' + -ta + 'rad) !important;';
		_cssRules += '.unpack-5 .' + cname + ' {' + addVendorPrefix(css) + '}';
	}
	else {
		ty = dia / 2;
		tz = (h - ch) / 2;
		css = 'transform: rotateX(' + r + 'rad) translate3d(0px, ' + ty.toFixed(0) + 'px, ' + tz.toFixed(0) + 'px) !important;';
		_cssRules += '.unpack-4 .' + cname + ' {' + addVendorPrefix(css) + '}';
		_cssRules += '.unpack-5 .' + cname + ' {' + addVendorPrefix(css) + '}';
	}
	face.className = (isSide) ? 'sides' : 'covers';
	face.classList.add(cname);
	face.style.cssText = cssText;
	return face;
}
<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>/* jslint asi:true, browser:true */

if (typeof Lexis == "undefined") var Lexis = {};

var Dictionary = {
    description: null,
    element: null,
    filter: function() {
        var i = 0;
        var current_element = null;
        for (i = 0; i < Dictionary.element.childElementCount; i++) {
            current_element = Dictionary.element.children.item(i);
            if (current_element.tagName !== "SECTION") continue;
            if (window.location.hash && (window.location.hash === "#:" || (window.location.hash.indexOf(":") === -1 && Dictionary.lemmaContainsForm(Dictionary.getLemmaFromId(current_element.id), window.location.hash.substr(1))) || current_element.id === window.location.hash.substr(1))) current_element.removeAttribute("hidden");
            else current_element.setAttribute("hidden", "");
        }
    },
    forms: {},
    getHTML: function(e) {
        var i = 0;
        var s = "";
        var current_node = null;
        for (i = 0; i < e.childNodes.length; i++) {
            current_node = e.childNodes.item(i);
            if (current_node.nodeType === 3) {
                s += current_node.textContent;
            }
            else if (current_node.nodeType === 1) {
                switch (current_node.tagName) {
                    case "wordref":
                        s += "" + current_node.textContent + "";
                        break;
                    case "etymon":
                    case "mention":
                        if (current_node.hasAttributeNS("http://www.w3.org/XML/1998/namespace", "lang")) s += "" + current_node.textContent + "";
                        else s += "" + current_node.textContent + "";
                        break;
                }
            }
        }
        return s;
    },
    getHumanReadableWordClass: function(word_class) {
        word_class = Dictionary.string(word_class);
        var class_list = word_class.split(" ");
        var class_item_list = null;
        var i = 0;
        var j = 0;
        var s = "";
        var q = null;
        for (i = 0; i < class_list.length; i++) {
            if (i) s += ", ";
            class_item_list = class_list[i].split(".");
            q = {};
            for (j = 0; j < class_item_list.length; j++) {
                q[class_item_list[j]] = true;
            }

            if (q.pfv) s += "perfective ";
            if (q.prog) s += "progressive ";
            if (q.cont) s += "continuous ";
            if (q["1"]) s += "first-person ";
            if (q["2"]) s += "second-person ";
            if (q["3"]) s += "third-person ";
            if (q.masc) s += "masculine ";
            if (q.fem) s += "feminine ";
            if (q.neut) s += "neuter ";
            if (q.sing) s += "singular ";
            if (q.pl) s += "plural ";
            if (q.inf) s += "infinitive ";
            if (q.mod) {
                if (q.mir) s += "mirative ";
                else if (q.opt) s += "optative ";
                else if (q.hort) s += "hortative ";
                else if (q.perm) s += "permissive ";
                else if (q.jus) s += "jussive ";
                else if (q.int) s += "interrogative ";
                else s += "modal ";
            }
            if (q.det) {
                if (q.qnt) s += "quantifier ";
                else if (q.num) s += "numeral ";
                else if (q.dem) s += "demonstrative ";
                else s += "determiner ";
            }
            if (q.post) s += "post-position ";
            if (q.ptcl) s += "particle ";
            if (q.adj) s += "adjective ";
            if (q.adv) s += "adverb ";
            if (q.pron) s += "pronoun ";
            if (q.n) s += "noun ";
            if (q.v) s += "verb ";
            s = s.trim();
        }
        return s;
    },
    getLemmaFromId: function(id) {
        return Dictionary.lemmas[id.split(":")[0]][Number(id.split(":")[1])]
    },
    getLemmaName: function(lemma) {
        return Dictionary.string(lemma).replace(/[:'"#\?]/g, "-");
    },
    ids: [],
    init: function() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.addEventListener("load", function() {Dictionary.load(document.documentElement.dataset.src + "?" + new Date().getTime())}, false);
        document.head.appendChild(script);
        script.src = "http://leaf.faint.xyz/langdev/!DATA!/master/!DATA!/LexisML/scripts/normalize.js";
    },
    lang: "",
    lemmaContainsForm: function(lemma, form) {
        var i;
        for (i = 0; i < lemma.forms.length; i++) {
            if (Dictionary.getLemmaName(lemma.forms.item(i).textContent) == form) return true;
        }
        return false;
    },
    lemmas: {},
    lexis: undefined,
    load: function(src) {
        Dictionary.Requester.addEventListener("load", Dictionary.setup, false);
        Dictionary.Requester.open("get", src, true);
        Dictionary.Requester.overrideMimeType("text/xml");
        Dictionary.Requester.send();
    },
    Requester: new XMLHttpRequest(),
    setup: function() {
        Dictionary.lang = document.documentElement.lang;
        Dictionary.lexis = Dictionary.Requester.responseXML;
        Lexis.normalize(Dictionary.lexis);
        var i = 0;
        var j = 0;
        var elements = Dictionary.lexis.documentElement.childNodes;
        var current_element;
        var current_lemma;
        var lemma_name;
        var lemma_id;
        var class_value;
        var article_html;
        var section_html;
        for (i = 0; i < elements.length; i++) {
            if (elements.item(i).nodeType !== 1) continue;
            current_element = elements.item(i);
            switch (current_element.tagName) {
                case "meta":
                    switch (current_element.getAttribute("name")) {
                        case "title":
                            Dictionary.title = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), current_element.textContent];
                            break;
                        case "description":
                            Dictionary.description = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), Dictionary.getHTML(current_element)];
                            break;
                        case "splash":
                            Dictionary.splashes[Dictionary.splashes.length] = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), Dictionary.getHTML(current_element)];
                            break;
                    }
                    break;
                case "affix":
                case "word":
                    lemma_name = Dictionary.getLemmaName(current_element.getAttribute("lemma"));
                    if (Dictionary.lemmas[lemma_name] === undefined) Dictionary.lemmas[lemma_name] = [];
                    lemma_id = lemma_name + ":" + Dictionary.lemmas[lemma_name].length;
                    current_lemma = Dictionary.lemmas[lemma_name][Dictionary.lemmas[lemma_name].length] = {
                        type: current_element.tagName,
                        name: current_element.getAttribute("lemma"),
                        id: lemma_id,
                        word_class: null,
                        lang: current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"),
                        form: null,
                        forms: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "form"),
                        etymology: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "etymology").item(0),
                        meanings: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "meaning")
                    }
                    class_value = "";
                    for (j = 0; j < current_lemma.forms.length; j++) {
                        if (current_lemma.forms.item(j).hasAttribute("class")) class_value += current_lemma.forms.item(j).getAttribute("class") + " ";
                        if (current_lemma.forms.item(j).textContent == current_lemma.name) current_lemma.form = current_lemma.forms.item(j);
                    }
                    if (class_value.trim() !== "") current_lemma.word_class = class_value.trim();
                    Dictionary.ids[Dictionary.ids.length] = lemma_id;
                    break;
            }
        }
        Dictionary.ids.sort(function (a, b) {return String(a).substr(String(a).search(/\w/)).localeCompare(String(b).substr(String(b).search(/\w/)));});
        Dictionary.element = document.createElement("article");
        document.title = Dictionary.title[1];
        document.getElementsByTagName("title").item(0).lang = Dictionary.title[0];
        article_html = "
";
        article_html += "
" + Dictionary.title[1] + "
";
        if (Dictionary.splashes.length) {
            i = Math.floor(Math.random()*Dictionary.splashes.length);
            article_html += "
" + Dictionary.splashes[i][1] + "
";
        }
        if (Dictionary.description !== null) article_html += "

" + Dictionary.description[1] + "
";
        article_html += "
search: <input id='filter-input' type='text' autocomplete='off' autofocus inputmode='latin' placeholder='enter search term…' spellcheck='false'> <button id='filter-button'>ok</button> <button id='unfilter-button'>show everything</button>
";
        article_html += "";
        Dictionary.element.innerHTML = article_html;
        for (i = 0; i < Dictionary.ids.length; i++) {
            current_element = document.createElement("section");
            current_lemma = Dictionary.getLemmaFromId(Dictionary.ids[i]);
            current_element.lang = current_lemma.lang;
            current_element.id = Dictionary.ids[i];
            current_element.setAttribute("hidden", "");
            section_html = "";
            section_html += "
";
            section_html += "<dfn>" + current_lemma.name + "</dfn>"
            class_value = "";
            for (j = 0; j < current_lemma.forms.length; j++) {
                if (current_lemma.forms.item(j) == current_lemma.form) {
                    if (current_lemma.forms.item(j).hasAttribute("pronunciation")) section_html += " " + current_lemma.forms.item(j).getAttribute("pronunciation") + "";
                }
                else {
                    if (class_value === "") class_value += " ";
                    else class_value += ", ";
                    class_value += (Dictionary.getHumanReadableWordClass(current_lemma.forms.item(j).getAttribute("class")) + " <dfn>" + current_lemma.forms.item(j).textContent + "</dfn>").trim();
                    if (current_lemma.forms.item(j).hasAttribute("pronunciation")) class_value += " " + Dictionary.string(current_lemma.forms.item(j).getAttribute("pronunciation")) + "";
                }
            }
            if (class_value !== "") class_value += ")";
            section_html += "
";
            if (current_lemma.type == "word") {
                section_html += "
" + Dictionary.getHumanReadableWordClass(current_lemma.form.getAttribute("class")) + class_value + "
";
            }
            else if (current_lemma.type == "affix") {
                section_html += "
" + (Dictionary.getHumanReadableWordClass(current_lemma.form.getAttribute("class")) + " affix").trim() + class_value + "
";
            }
            section_html += "";
            if (current_lemma.meanings.length > 1) {
                section_html += "
";
                for (j = 0; j < current_lemma.meanings.length; j++) {
                    section_html += "
";
                    if (current_lemma.meanings.item(j).getAttribute("class") != current_lemma.word_class) section_html += "(" + Dictionary.getHumanReadableWordClass(current_lemma.meanings.item(j).getAttribute("class")) + ") ";
                    section_html += Dictionary.getHTML(current_lemma.meanings.item(j));
                    section_html += "
";
                }
                section_html += "
";
            }
            else if (current_lemma.meanings.length == 1) {
                section_html += "
";
                if (current_lemma.meanings.item(0).getAttribute("class") != current_lemma.word_class) section_html += "(" + Dictionary.getHumanReadableWordClass(current_lemma.meanings.item(0).getAttribute("class")) + ") ";
                section_html += Dictionary.getHTML(current_lemma.meanings.item(0));
                section_html += "
";
            }
            if (current_lemma.etymology) section_html += "
etymology

" + Dictionary.getHTML(current_lemma.etymology) + "
";
            current_element.innerHTML = section_html;
            Dictionary.element.appendChild(current_element);
        }
        document.body.textContent = null;
        document.body.appendChild(document.createElement("main").appendChild(Dictionary.element).parentElement);
        document.getElementById("filter-button").addEventListener("click", function(){window.location.hash = Dictionary.getLemmaName(document.getElementById("filter-input").value);} ,false);
        document.getElementById("filter-input").addEventListener("keypress", function(e){if (e.key === "Enter" || e.keyCode === 13) window.location.hash = Dictionary.getLemmaName(document.getElementById("filter-input").value);} ,false);
        document.getElementById("unfilter-button").addEventListener("click", function(){window.location.hash = ":";}, false);
        Dictionary.filter();
    },
    splashes: [],
    string: function(n) {
        if (typeof n == "string") {
            return n;
        }
        else if (typeof n == "number") {
            return String(n);
        }
        return "";
    },
    title: "",
    title_lang: ""
}

window.addEventListener("load", Dictionary.init, false);
window.addEventListener("hashchange", Dictionary.filter, false);
<commit_msg>multi-class rendering fixes<commit_after>/* jslint asi:true, browser:true */

if (typeof Lexis == "undefined") var Lexis = {};

var Dictionary = {
    description: null,
    element: null,
    filter: function() {
        var i = 0;
        var current_element = null;
        for (i = 0; i < Dictionary.element.childElementCount; i++) {
            current_element = Dictionary.element.children.item(i);
            if (current_element.tagName !== "SECTION") continue;
            if (window.location.hash && (window.location.hash === "#:" || (window.location.hash.indexOf(":") === -1 && Dictionary.lemmaContainsForm(Dictionary.getLemmaFromId(current_element.id), window.location.hash.substr(1))) || current_element.id === window.location.hash.substr(1))) current_element.removeAttribute("hidden");
            else current_element.setAttribute("hidden", "");
        }
    },
    forms: {},
    getHTML: function(e) {
        var i = 0;
        var s = "";
        var current_node = null;
        for (i = 0; i < e.childNodes.length; i++) {
            current_node = e.childNodes.item(i);
            if (current_node.nodeType === 3) {
                s += current_node.textContent;
            }
            else if (current_node.nodeType === 1) {
                switch (current_node.tagName) {
                    case "wordref":
                        s += "" + current_node.textContent + "";
                        break;
                    case "etymon":
                    case "mention":
                        if (current_node.hasAttributeNS("http://www.w3.org/XML/1998/namespace", "lang")) s += "" + current_node.textContent + "";
                        else s += "" + current_node.textContent + "";
                        break;
                }
            }
        }
        return s;
    },
    getHumanReadableWordClass: function(word_class) {
        word_class = Dictionary.string(word_class);
        var class_list = word_class.split(" ");
        var class_item_list = null;
        var i = 0;
        var j = 0;
        var s = "";
        var q = null;
        for (i = 0; i < class_list.length; i++) {
            if (i) s += ", ";
            class_item_list = class_list[i].split(".");
            q = {};
            for (j = 0; j < class_item_list.length; j++) {
                q[class_item_list[j]] = true;
            }

            if (q.pfv) s += "perfective ";
            if (q.prog) s += "progressive ";
            if (q.cont) s += "continuous ";
            if (q["1"]) s += "first-person ";
            if (q["2"]) s += "second-person ";
            if (q["3"]) s += "third-person ";
            if (q.masc) s += "masculine ";
            if (q.fem) s += "feminine ";
            if (q.neut) s += "neuter ";
            if (q.sing) s += "singular ";
            if (q.pl) s += "plural ";
            if (q.inf) s += "infinitive ";
            if (q.mod) {
                if (q.mir) s += "mirative ";
                else if (q.opt) s += "optative ";
                else if (q.hort) s += "hortative ";
                else if (q.perm) s += "permissive ";
                else if (q.jus) s += "jussive ";
                else if (q.int) s += "interrogative ";
                else s += "modal ";
            }
            if (q.det) {
                if (q.qnt) s += "quantifier ";
                else if (q.num) s += "numeral ";
                else if (q.dem) s += "demonstrative ";
                else s += "determiner ";
            }
            if (q.post) s += "post-position ";
            if (q.ptcl) s += "particle ";
            if (q.adj) s += "adjective ";
            if (q.adv) s += "adverb ";
            if (q.pron) s += "pronoun ";
            if (q.n) s += "noun ";
            if (q.v) s += "verb ";
            s = s.trim();
        }
        return s;
    },
    getLemmaFromId: function(id) {
        return Dictionary.lemmas[id.split(":")[0]][Number(id.split(":")[1])]
    },
    getLemmaName: function(lemma) {
        return Dictionary.string(lemma).replace(/[:'"#\?]/g, "-");
    },
    ids: [],
    init: function() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.addEventListener("load", function() {Dictionary.load(document.documentElement.dataset.src + "?" + new Date().getTime())}, false);
        document.head.appendChild(script);
        script.src = "http://leaf.faint.xyz/langdev/!DATA!/master/!DATA!/LexisML/scripts/normalize.js";
    },
    lang: "",
    lemmaContainsForm: function(lemma, form) {
        var i;
        for (i = 0; i < lemma.forms.length; i++) {
            if (Dictionary.getLemmaName(lemma.forms.item(i).textContent) == form) return true;
        }
        return false;
    },
    lemmas: {},
    lexis: undefined,
    load: function(src) {
        Dictionary.Requester.addEventListener("load", Dictionary.setup, false);
        Dictionary.Requester.open("get", src, true);
        Dictionary.Requester.overrideMimeType("text/xml");
        Dictionary.Requester.send();
    },
    Requester: new XMLHttpRequest(),
    setup: function() {
        Dictionary.lang = document.documentElement.lang;
        Dictionary.lexis = Dictionary.Requester.responseXML;
        Lexis.normalize(Dictionary.lexis);
        var i = 0;
        var j = 0;
        var elements = Dictionary.lexis.documentElement.childNodes;
        var current_element;
        var current_lemma;
        var lemma_name;
        var lemma_id;
        var class_value;
        var article_html;
        var section_html;
        for (i = 0; i < elements.length; i++) {
            if (elements.item(i).nodeType !== 1) continue;
            current_element = elements.item(i);
            switch (current_element.tagName) {
                case "meta":
                    switch (current_element.getAttribute("name")) {
                        case "title":
                            Dictionary.title = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), current_element.textContent];
                            break;
                        case "description":
                            Dictionary.description = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), Dictionary.getHTML(current_element)];
                            break;
                        case "splash":
                            Dictionary.splashes[Dictionary.splashes.length] = [current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"), Dictionary.getHTML(current_element)];
                            break;
                    }
                    break;
                case "affix":
                case "word":
                    lemma_name = Dictionary.getLemmaName(current_element.getAttribute("lemma"));
                    if (Dictionary.lemmas[lemma_name] === undefined) Dictionary.lemmas[lemma_name] = [];
                    lemma_id = lemma_name + ":" + Dictionary.lemmas[lemma_name].length;
                    current_lemma = Dictionary.lemmas[lemma_name][Dictionary.lemmas[lemma_name].length] = {
                        type: current_element.tagName,
                        name: current_element.getAttribute("lemma"),
                        id: lemma_id,
                        word_class: null,
                        lang: current_element.getAttributeNS("http://www.w3.org/XML/1998/namespace", "lang"),
                        form: null,
                        forms: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "form"),
                        etymology: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "etymology").item(0),
                        meanings: current_element.getElementsByTagNameNS("http://leaf.faint.xyz/lexisml", "meaning")
                    }
                    class_value = "";
                    for (j = 0; j < current_lemma.forms.length; j++) {
                        if (current_lemma.forms.item(j).hasAttribute("class")) class_value += current_lemma.forms.item(j).getAttribute("class") + " ";
                        if (current_lemma.forms.item(j).textContent == current_lemma.name) current_lemma.form = current_lemma.forms.item(j);
                    }
                    if (class_value.trim() !== "") current_lemma.word_class = class_value.trim();
                    Dictionary.ids[Dictionary.ids.length] = lemma_id;
                    break;
            }
        }
        Dictionary.ids.sort(function (a, b) {return String(a).substr(String(a).search(/\w/)).localeCompare(String(b).substr(String(b).search(/\w/)));});
        Dictionary.element = document.createElement("article");
        document.title = Dictionary.title[1];
        document.getElementsByTagName("title").item(0).lang = Dictionary.title[0];
        article_html = "
";
        article_html += "
" + Dictionary.title[1] + "
";
        if (Dictionary.splashes.length) {
            i = Math.floor(Math.random()*Dictionary.splashes.length);
            article_html += "
" + Dictionary.splashes[i][1] + "
";
        }
        if (Dictionary.description !== null) article_html += "

" + Dictionary.description[1] + "
";
        article_html += "
search: <input id='filter-input' type='text' autocomplete='off' autofocus inputmode='latin' placeholder='enter search term…' spellcheck='false'> <button id='filter-button'>ok</button> <button id='unfilter-button'>show everything</button>
";
        article_html += "";
        Dictionary.element.innerHTML = article_html;
        for (i = 0; i < Dictionary.ids.length; i++) {
            current_element = document.createElement("section");
            current_lemma = Dictionary.getLemmaFromId(Dictionary.ids[i]);
            current_element.lang = current_lemma.lang;
            current_element.id = Dictionary.ids[i];
            current_element.setAttribute("hidden", "");
            section_html = "";
            section_html += "
";
            section_html += "<dfn>" + current_lemma.name + "</dfn>"
            class_value = "";
            for (j = 0; j < current_lemma.forms.length; j++) {
                if (current_lemma.forms.item(j) == current_lemma.form) {
                    if (current_lemma.forms.item(j).hasAttribute("pronunciation")) section_html += " " + current_lemma.forms.item(j).getAttribute("pronunciation") + "";
                }
                else {
                    if (class_value === "") class_value += " (";
                    else class_value += ", ";
                    class_value += (Dictionary.getHumanReadableWordClass(current_lemma.forms.item(j).getAttribute("class")) + " <dfn>" + current_lemma.forms.item(j).textContent + "</dfn>").trim();
                    if (current_lemma.forms.item(j).hasAttribute("pronunciation")) class_value += " " + Dictionary.string(current_lemma.forms.item(j).getAttribute("pronunciation")) + "";
                }
            }
            if (class_value !== "") class_value += ")";
            section_html += "
";
            if (current_lemma.type == "word") {
                section_html += "
" + Dictionary.getHumanReadableWordClass(current_lemma.form.getAttribute("class")) + class_value + "
";
            }
            else if (current_lemma.type == "affix") {
                section_html += "
" + (Dictionary.getHumanReadableWordClass(current_lemma.form.getAttribute("class")) + " affix").trim() + class_value + "
";
            }
            section_html += "";
            if (current_lemma.meanings.length > 1) {
                section_html += "
";
                for (j = 0; j < current_lemma.meanings.length; j++) {
                    section_html += "
";
                    if (current_lemma.meanings.item(j).getAttribute("class") != current_lemma.word_class) section_html += "(" + Dictionary.getHumanReadableWordClass(current_lemma.meanings.item(j).getAttribute("class")) + ") ";
                    section_html += Dictionary.getHTML(current_lemma.meanings.item(j));
                    section_html += "
";
                }
                section_html += "
";
            }
            else if (current_lemma.meanings.length == 1) {
                section_html += "
";
                if (current_lemma.meanings.item(0).getAttribute("class") != current_lemma.word_class) section_html += "(" + Dictionary.getHumanReadableWordClass(current_lemma.meanings.item(0).getAttribute("class")) + ") ";
                section_html += Dictionary.getHTML(current_lemma.meanings.item(0));
                section_html += "
";
            }
            if (current_lemma.etymology) section_html += "
etymology

" + Dictionary.getHTML(current_lemma.etymology) + "
";
            current_element.innerHTML = section_html;
            Dictionary.element.appendChild(current_element);
        }
        document.body.textContent = null;
        document.body.appendChild(document.createElement("main").appendChild(Dictionary.element).parentElement);
        document.getElementById("filter-button").addEventListener("click", function(){window.location.hash = Dictionary.getLemmaName(document.getElementById("filter-input").value);} ,false);
        document.getElementById("filter-input").addEventListener("keypress", function(e){if (e.key === "Enter" || e.keyCode === 13) window.location.hash = Dictionary.getLemmaName(document.getElementById("filter-input").value);} ,false);
        document.getElementById("unfilter-button").addEventListener("click", function(){window.location.hash = ":";}, false);
        Dictionary.filter();
    },
    splashes: [],
    string: function(n) {
        if (typeof n == "string") {
            return n;
        }
        else if (typeof n == "number") {
            return String(n);
        }
        return "";
    },
    title: "",
    title_lang: ""
}

window.addEventListener("load", Dictionary.init, false);
window.addEventListener("hashchange", Dictionary.filter, false);
<|endoftext|>


<commit_before>describe("StudentNotesController", function() {

  var helpers = {
    // Create a controller for test, with some defaults.
    createController: function(options) {
      var controller = new window.StudentNotesController(options || {
        $el: $('<div />'),
        studentNotes: []
      });
      controller.bindListeners();
      return controller;
    },

    extractFormParams: function($form) {
      return $form.serializeArray().reduce(function(params, pair) {
        params[pair.name] = pair.value;
        return params;
      }, {});
    }
  };

  it('renders "No student notes" when there are no student notes', function() {
    var $el = helpers.createController().render();
    expect($el.text()).toContain('No student notes.');
  });

  it('renders student notes correctly when there are student notes', function() {
    var $el = helpers.createController({
      $el: $('<div />'),
      studentNotes: [{
        content: 'Alejandra is doing great at algebra!',
        student_id: 2
      }]
    }).render();
    expect($el.text()).toContain('Alejandra is doing great at algebra!');
  });

  it('allows educator to fill out new student note form', function() {
    var $el = helpers.createController().render();
    $el.find('[name="student_note[content]"]').val('George is doing great in geometry!');
    $el.find('[name="student_note[student_id]"]').val(1);
    var form_params = helpers.extractFormParams($el.find('form'));
    expect(form_params).toEqual({
       'utf8': '✓',
       'student_note[content]': 'George is doing great in geometry!',
       'student_note[student_id]': '1'
    });
  });

});
<commit_msg>Test how controller responds to server sucess<commit_after>describe("StudentNotesController", function() {

  var helpers = {
    // Create a controller for test, with some defaults.
    createController: function(options) {
      var controller = new window.StudentNotesController(options || {
        $el: $('<div />'),
        studentNotes: []
      });
      controller.bindListeners();
      return controller;
    },

    extractFormParams: function($form) {
      return $form.serializeArray().reduce(function(params, pair) {
        params[pair.name] = pair.value;
        return params;
      }, {});
    }
  };

  it('renders "No student notes" when there are no student notes', function() {
    var $el = helpers.createController().render();
    expect($el.text()).toContain('No student notes.');
  });

  it('renders student notes correctly when there are student notes', function() {
    var $el = helpers.createController({
      $el: $('<div />'),
      studentNotes: [{
        content: 'Alejandra is doing great at algebra!',
        student_id: 2
      }]
    }).render();
    expect($el.text()).toContain('Alejandra is doing great at algebra!');
  });

  it('allows educator to fill out new student note form', function() {
    var $el = helpers.createController().render();
    $el.find('[name="student_note[content]"]').val('George is doing great in geometry!');
    $el.find('[name="student_note[student_id]"]').val(1);
    var form_params = helpers.extractFormParams($el.find('form'));
    expect(form_params).toEqual({
       'utf8': '✓',
       'student_note[content]': 'George is doing great in geometry!',
       'student_note[student_id]': '1'
    });
  });

  it('allows educator to create new student note', function () {
    // Setup controller and server fixture data
    var $el = helpers.createController().render();
    var serverResponse = {
      content: 'George is doing great in geometry!',
      student_id: 1
    };

    // No student notes before ajax:success trigger
    expect($('.student-note-content').length).toEqual(0);

    // Happy path response from server!
    $el.find('form').trigger('ajax:success', serverResponse);
    expect($el.find('.student-note-content').length).toEqual(1);
    expect($el.html()).toContain('George is doing great in geometry!');
  });

});
<|endoftext|>


<commit_before>var ZoomableImage = function(selector, options){
	var self = this;
	var original = $(selector);
	this.opts = $.extend({
		maxZoom: 2,
		deadarea: 0.1,
		appearDuration: 0.5,
		target: null
	}, options);
	if(this.opts.target && typeof this.opts.target == "object" && !(this.opts.target instanceof jQuery)){
		var topt = this.opts.target;
		if((!topt.width) || (!topt.height) || ((!topt.left) && (!topt.right) && (!topt.top) && (!topt.bottom))){
			console.warn("Missing position attributes for Zoomable Image target");
			this.opts.target = null;
		} else {
			var newDom = $($.parseHTML("

"));
			var resOpts = {
				height: topt.height,
				width: topt.width,
				top: original.position().top,
				left: original.position().left
			};
			if(!!topt.top)		resOpts.top		= original.position().top - (topt.height + topt.top);
			if(!!topt.bottom)	resOpts.top		= original.position().top + original.height() + topt.bottom;
			if(!!topt.left)		resOpts.left	= original.position().left - (topt.width + topt.left);
			if(!!topt.right)	resOpts.left	= original.position().left + original.width() + topt.right;
			newDom.css($.extend(resOpts, {
				position: "absolute"
			}));
			this.opts.target = newDom;
			original.parent().append(newDom);
		}
	}

	//this.zoomedImage;
	var original = $(selector);
	var wrapper = this.opts.target;
	var antiSubstractedProportions;
	var substractedDims;
	var offsetProportion;
	var proportion;
	var dims;
	var inPlace;
	var proportionFactor;
	var scrollOn;
	Object.defineProperties(this, {
		proportion: {
			get: function(){return proportion;}
		}
	});
	original.load(function(){
		self.zoomedImage = original.clone().addClass("zoomed");
		if(!wrapper){
			wrapper = self.zoomedImage.wrap('

').parent();
			original.parent().append(wrapper);
			inPlace = true;
		} else {
			wrapper.addClass("zoomable").append(self.zoomedImage);
			inPlace = false;
		}

		$(window).resize(self.recalcDimensions);
		self.recalcDimensions();
		var transitionString = "opacity " + self.opts.appearDuration + "s, top 0.1s, left 0.1s";
		self.zoomedImage.css({
			WebkitTransition: transitionString,
			MozTransition: transitionString,
			transition: transitionString,
		})
		self.enable();
	});
	this.enable = function(){
		original
			.bind("mousemove", recalcOffsets)
			.bind("mouseenter", setActive)
			.bind("mouseleave", setInactive);
	}
	this.disable = function(){
		original
			.unbind("mousemove", recalcOffsets)
			.unbind("mouseenter", setActive)
			.unbind("mouseleave", setInactive);
	}
	this.delete = function(){
		wrapper.remove();
	}
	function active(active){active?setActive():setInactive();}
	function setActive(){wrapper.addClass("active");}
	function setInactive(){wrapper.removeClass("active");}

	function recalcOffsets(e){
		wrapper.addClass("active");
		var axisNames = ["x", "y"];
		var offsets = {};
		for(var i = 0; i < 2; i++){
			var axis = axisNames[i];
			var offsetName = "offset" + axis.toUpperCase();
			var percentScroll;
			if(e[offsetName] < self.opts.deadarea * dims[axis]){
				percentScroll = 0;
			} else if(e[offsetName] > (1 - self.opts.deadarea) * dims[axis]){
				percentScroll = 100;
			} else {
				percentScroll = ((e[offsetName] - substractedDims[axis]) / scrollOn[axis]) * 100;
			}
			offsets[axis] = (percentScroll * proportionFactor[axis]) / 100;
			//console.log("Scroll " + axis + ": " + percentScroll + "%");
		}
		self.zoomedImage.css({
			top: -offsets.y,
			left: -offsets.x,
		});
	}
	this.recalcDimensions = function(){
		dims = {
			x: original.width(),
			y: original.height()
		};
		scrollOn = {
			x: dims.x * (1 - (2 * self.opts.deadarea)),
			y: dims.y * (1 - (2 * self.opts.deadarea))
		};
		if(inPlace){
			wrapper.css({
				top:	original.position().top,
				left:	original.position().left,
				width:	dims.x,
				height:	dims.y
			});
		}
		proportion = Math.min(
			self.zoomedImage[0].naturalWidth / dims.x,
			self.zoomedImage[0].naturalHeight / dims.y,
			self.opts.maxZoom
		);
		offsetProportion = (proportion - 1);
		self.zoomedImage.css({
			width: dims.x * proportion,
			height: dims.y * proportion
		});
		proportionFactor = {
			x: dims.x * proportion - wrapper.width(),
			y: dims.y * proportion - wrapper.height(),
		};
		substractedDims = {
			x: self.opts.deadarea * dims.x,
			y: self.opts.deadarea * dims.y
		};
		antiSubstractedProportions = offsetProportion / (1 - (self.opts.deadarea * 2));
	}
}<commit_msg>Add recalc resize & delete<commit_after>var ZoomableImage = function(selector, options){
	var self = this;
	var original = $(selector);
	this.opts = $.extend({
		maxZoom: 2,
		deadarea: 0.1,
		appearDuration: 0.5,
		target: null
	}, options);
	var position = null;
	if(this.opts.target && typeof this.opts.target == "object" && !(this.opts.target instanceof jQuery)){
		var topt = this.opts.target;
		if((!topt.width) || (!topt.height) || ((!topt.left) && (!topt.right) && (!topt.top) && (!topt.bottom))){
			console.warn("Missing position attributes for Zoomable Image target");
			this.opts.target = null;
		} else {
		position = topt;
			this.opts.target = $($.parseHTML("

"));
			original.parent().append(this.opts.target);
			// inPlace set when test wrapper
		}
	}

	//this.zoomedImage;
	var original = $(selector);
	var wrapper = this.opts.target;
	var antiSubstractedProportions;
	var substractedDims;
	var offsetProportion;
	var proportion;
	var dims;
	var inPlace;
	var proportionFactor;
	var scrollOn;
	Object.defineProperties(this, {
		proportion: {
			get: function(){return proportion;}
		}
	});
	original.load(function(){
		self.zoomedImage = original.clone().addClass("zoomed");
		if(!wrapper){
			wrapper = self.zoomedImage.wrap('

').parent();
			original.parent().append(wrapper);
			inPlace = true;
		} else {
			wrapper.addClass("zoomable").append(self.zoomedImage);
			inPlace = false;
		}

		$(window).resize(self.recalcDimensions);
		self.recalcDimensions();
		var transitionString = "opacity " + self.opts.appearDuration + "s, top 0.1s, left 0.1s";
		self.zoomedImage.css({
			WebkitTransition: transitionString,
			MozTransition: transitionString,
			transition: transitionString,
		})
		self.enable();
	});
	this.enable = function(){
		original
			.bind("mousemove", recalcOffsets)
			.bind("mouseenter", setActive)
			.bind("mouseleave", setInactive);
	}
	this.disable = function(){
		original
			.unbind("mousemove", recalcOffsets)
			.unbind("mouseenter", setActive)
			.unbind("mouseleave", setInactive);
	}
	this.delete = function(){
		wrapper.remove();
	}
	function active(active){active?setActive():setInactive();}
	function setActive(){wrapper.addClass("active");}
	function setInactive(){wrapper.removeClass("active");}

	function recalcOffsets(e){
		wrapper.addClass("active");
		var axisNames = ["x", "y"];
		var offsets = {};
		for(var i = 0; i < 2; i++){
			var axis = axisNames[i];
			var offsetName = "offset" + axis.toUpperCase();
			var percentScroll;
			if(e[offsetName] < self.opts.deadarea * dims[axis]){
				percentScroll = 0;
			} else if(e[offsetName] > (1 - self.opts.deadarea) * dims[axis]){
				percentScroll = 100;
			} else {
				percentScroll = ((e[offsetName] - substractedDims[axis]) / scrollOn[axis]) * 100;
			}
			offsets[axis] = (percentScroll * proportionFactor[axis]) / 100;
			//console.log("Scroll " + axis + ": " + percentScroll + "%");
		}
		self.zoomedImage.css({
			top: -offsets.y,
			left: -offsets.x,
		});
	}
	this.recalcDimensions = function(){
		if(position){
			var resOpts = {
				height: position.height,
				width: position.width,
				top: original.position().top,
				left: original.position().left
			};
			if(!!position.top)		resOpts.top		= original.position().top - (position.height + position.top);
			if(!!position.bottom)	resOpts.top		= original.position().top + original.height() + position.bottom;
			if(!!position.left)		resOpts.left	= original.position().left - (position.width + position.left);
			if(!!position.right)	resOpts.left	= original.position().left + original.width() + position.right;
			this.opts.target.css($.extend(resOpts, {
				position: "absolute"
			}));
		}
		dims = {
			x: original.width(),
			y: original.height()
		};
		scrollOn = {
			x: dims.x * (1 - (2 * self.opts.deadarea)),
			y: dims.y * (1 - (2 * self.opts.deadarea))
		};
		if(inPlace){
			wrapper.css({
				top:	original.position().top,
				left:	original.position().left,
				width:	dims.x,
				height:	dims.y
			});
		}
		proportion = Math.min(
			self.zoomedImage[0].naturalWidth / dims.x,
			self.zoomedImage[0].naturalHeight / dims.y,
			self.opts.maxZoom
		);
		offsetProportion = (proportion - 1);
		self.zoomedImage.css({
			width: dims.x * proportion,
			height: dims.y * proportion
		});
		proportionFactor = {
			x: dims.x * proportion - wrapper.width(),
			y: dims.y * proportion - wrapper.height(),
		};
		substractedDims = {
			x: self.opts.deadarea * dims.x,
			y: self.opts.deadarea * dims.y
		};
		antiSubstractedProportions = offsetProportion / (1 - (self.opts.deadarea * 2));
	}
	this.delete = function(){
		self.disable();
		self.zoomedImage.remove();
		if(!inPlace)
			wrapper.remove();
	}
}<|endoftext|>


<commit_before>b6bdfb4e-973a-11e6-b514-8086f2004150<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>b6be8dc0-973a-11e6-b514-8086f2004150<|endoftext|>


<commit_before>(function () {
    "use strict";

    angular
        .module('summary')
        .component('summaryMetrics', {
            templateUrl: 'partials/summary-metrics.html',
            controller: SummaryMetricsComponent,
            controllerAs: 'vm',
            bindings: {
                chartsData: '<'
            },
            require: {
                profileSummary: '^profileSummary'
            }
        });

    SummaryMetricsComponent.$inject = [
        'ChartService',
        'ModalService'
    ];

    function SummaryMetricsComponent(ChartService, ModalService) {
        const vm = this;

        vm.name = 'metrics';
        vm.charts = {};

        vm.showInfo = showInfo;

        vm.$onInit = () => {
            vm.profileSummary.registerTab(vm);
            vm.reload();
        };

        vm.reload = (chartsData) => {
            vm.charts = {};
            vm.charts.documentTotals = ChartService.getDocumentTotals(chartsData);
            vm.charts.hindexPerYear = ChartService.getHindexPerYear(chartsData);
            vm.charts.citationsPerDocumentYear = ChartService.getCitationsPerDocumentYear(chartsData);
            vm.charts.citationsPerYear = ChartService.getCitationsPerYear(chartsData);
            vm.charts.journalMetricsPerYearLineChart = ChartService.getJournalMetricsPerYearLineChart(chartsData);
            vm.charts.getJournalMetricsPerYearBarChart = ChartService.getJournalMetricsPerYearBarChart(chartsData);
            vm.charts.filteredDocumentsByYear = ChartService.getFilteredDocumentsByYear(chartsData);
            vm.charts.filteredDocumentsSourceTypeByYear = ChartService.getFilteredDocumentsSourceTypeByYear(chartsData);

            const totalDocuments = ChartService.getTotalFilteredDocuments(chartsData);
            const hIndex = ChartService.getHindex(chartsData);
            const totalCitations = ChartService.getTotalCitations(chartsData);
            const totalImpactFactor = ChartService.getTotalImpactFactor(chartsData);

            vm.documentsChartToShow = vm.charts.filteredDocumentsSourceTypeByYear;
            vm.citationsChartToShow = vm.charts.citationsPerYear;

            vm.documentsCharts = [
                {
                    icon: 'fas fa-chart-pie',
                    chartSettings: vm.charts.filteredDocumentsSourceTypeByYear,
                    default: true,
                    title: vm.charts.filteredDocumentsSourceTypeByYear.title
                },
                {
                    icon: 'fas fa-university',
                    chartSettings: vm.charts.filteredDocumentsByYear,
                    title: vm.charts.filteredDocumentsSourceTypeByYear.title
                }
            ];

            vm.citationsCharts = [
                {
                    icon: 'fas fa-quote-right',
                    chartSettings: vm.charts.citationsPerYear,
                    default: true,
                    title: vm.charts.citationsPerYear.title
                },
                {
                    icon: 'fas fa-quote-left',
                    chartSettings: vm.charts.citationsPerDocumentYear,
                    title: vm.charts.citationsPerDocumentYear.title
                }
            ];

            vm.metricsCharts = [
                {
                    icon: 'fas fa-chart-line',
                    chartSettings: vm.charts.journalMetricsPerYearLineChart,
                    id: 'scientilla-chart-journalMetricsPerYear',
                    default: true,
                    title: 'Line chart'
                },
                {
                    icon: 'fas fa-chart-bar',
                    chartSettings: vm.charts.getJournalMetricsPerYearBarChart,
                    title: 'Bar chart'
                }

            ];

            vm.indexes = [];
            vm.indexes.push({
                label: 'Documents',
                value: totalDocuments,
                icons: ['far fa-file-alt icon-documents'],
                format: 0
            });
            vm.indexes.push({
                label: 'h-index',
                value: hIndex,
                icons: ['fas fa-chart-line icon-h-index'],
                format: 0
            });
            vm.indexes.push({
                label: 'Citations',
                value: totalCitations,
                icons: ['fas fa-quote-right icon-citations'],
                format: 0
            });
            vm.indexes.push({
                label: 'Citations per document',
                value: (totalCitations / totalDocuments) || 0,
                icons: ['fas fa-quote-right icon-citations','far fa-file-alt icon-citations'],
                format: 2
            });
            vm.indexes.push({
                label: 'Total IF',
                value: totalImpactFactor,
                icons: ['icons-if icon-if'],
                format: 2
            });
            vm.indexes.push({
                label: 'IF per document',
                value: (totalImpactFactor / totalDocuments) || 0,
                icons: ['icons-if icon-if', 'icons-if far fa-file-alt'],
                format: 2
            });
        };

        function showInfo() {
            ModalService.openWizard(['summary-metrics'], {isClosable: true});
        }
    }
})();<commit_msg>Remove reload on init<commit_after>(function () {
    "use strict";

    angular
        .module('summary')
        .component('summaryMetrics', {
            templateUrl: 'partials/summary-metrics.html',
            controller: SummaryMetricsComponent,
            controllerAs: 'vm',
            bindings: {
                chartsData: '<'
            },
            require: {
                profileSummary: '^profileSummary'
            }
        });

    SummaryMetricsComponent.$inject = [
        'ChartService',
        'ModalService'
    ];

    function SummaryMetricsComponent(ChartService, ModalService) {
        const vm = this;

        vm.name = 'metrics';
        vm.charts = {};

        vm.showInfo = showInfo;

        vm.$onInit = () => {
            vm.profileSummary.registerTab(vm);
        };

        vm.reload = (chartsData) => {
            vm.charts = {};
            vm.charts.documentTotals = ChartService.getDocumentTotals(chartsData);
            vm.charts.hindexPerYear = ChartService.getHindexPerYear(chartsData);
            vm.charts.citationsPerDocumentYear = ChartService.getCitationsPerDocumentYear(chartsData);
            vm.charts.citationsPerYear = ChartService.getCitationsPerYear(chartsData);
            vm.charts.journalMetricsPerYearLineChart = ChartService.getJournalMetricsPerYearLineChart(chartsData);
            vm.charts.getJournalMetricsPerYearBarChart = ChartService.getJournalMetricsPerYearBarChart(chartsData);
            vm.charts.filteredDocumentsByYear = ChartService.getFilteredDocumentsByYear(chartsData);
            vm.charts.filteredDocumentsSourceTypeByYear = ChartService.getFilteredDocumentsSourceTypeByYear(chartsData);

            const totalDocuments = ChartService.getTotalFilteredDocuments(chartsData);
            const hIndex = ChartService.getHindex(chartsData);
            const totalCitations = ChartService.getTotalCitations(chartsData);
            const totalImpactFactor = ChartService.getTotalImpactFactor(chartsData);

            vm.documentsChartToShow = vm.charts.filteredDocumentsSourceTypeByYear;
            vm.citationsChartToShow = vm.charts.citationsPerYear;

            vm.documentsCharts = [
                {
                    icon: 'fas fa-chart-pie',
                    chartSettings: vm.charts.filteredDocumentsSourceTypeByYear,
                    default: true,
                    title: vm.charts.filteredDocumentsSourceTypeByYear.title
                },
                {
                    icon: 'fas fa-university',
                    chartSettings: vm.charts.filteredDocumentsByYear,
                    title: vm.charts.filteredDocumentsSourceTypeByYear.title
                }
            ];

            vm.citationsCharts = [
                {
                    icon: 'fas fa-quote-right',
                    chartSettings: vm.charts.citationsPerYear,
                    default: true,
                    title: vm.charts.citationsPerYear.title
                },
                {
                    icon: 'fas fa-quote-left',
                    chartSettings: vm.charts.citationsPerDocumentYear,
                    title: vm.charts.citationsPerDocumentYear.title
                }
            ];

            vm.metricsCharts = [
                {
                    icon: 'fas fa-chart-line',
                    chartSettings: vm.charts.journalMetricsPerYearLineChart,
                    id: 'scientilla-chart-journalMetricsPerYear',
                    default: true,
                    title: 'Line chart'
                },
                {
                    icon: 'fas fa-chart-bar',
                    chartSettings: vm.charts.getJournalMetricsPerYearBarChart,
                    title: 'Bar chart'
                }

            ];

            vm.indexes = [];
            vm.indexes.push({
                label: 'Documents',
                value: totalDocuments,
                icons: ['far fa-file-alt icon-documents'],
                format: 0
            });
            vm.indexes.push({
                label: 'h-index',
                value: hIndex,
                icons: ['fas fa-chart-line icon-h-index'],
                format: 0
            });
            vm.indexes.push({
                label: 'Citations',
                value: totalCitations,
                icons: ['fas fa-quote-right icon-citations'],
                format: 0
            });
            vm.indexes.push({
                label: 'Citations per document',
                value: (totalCitations / totalDocuments) || 0,
                icons: ['fas fa-quote-right icon-citations','far fa-file-alt icon-citations'],
                format: 2
            });
            vm.indexes.push({
                label: 'Total IF',
                value: totalImpactFactor,
                icons: ['icons-if icon-if'],
                format: 2
            });
            vm.indexes.push({
                label: 'IF per document',
                value: (totalImpactFactor / totalDocuments) || 0,
                icons: ['icons-if icon-if', 'icons-if far fa-file-alt'],
                format: 2
            });
        };

        function showInfo() {
            ModalService.openWizard(['summary-metrics'], {isClosable: true});
        }
    }
})();<|endoftext|>


<commit_before>"use strict";
/* puredate.js
 *
 * The most 'pure' date without time information. No timezone hell.
 * 2014-12-02
 *
 * By Sergio M C Figueiredo
 *
 * http://sergio.figueiredo.nom.br
 *
 */

var PureDate = PureDate
    || (function () {
    "use strict";

        var lastDaysArray = [31,28,31,30,31,30,31,31,30,31,30,31];
        /**
         * Returns the number of days since March 01, 0000.
         *
         * Credits: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
         */
        function g(y, m, d) {
            m = (m + 9) % 12;
            y = y - (~~(m/10)); // (~~(a/b)) forces integer division at a/b
            return 365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)) + (~~((m*306 + 5)/10)) + ( d - 1 );
        }

        function PureDateInstance(year, month, day, gDate) {
            Object.defineProperties(this, {
                /* public read-only properties */
                'day':{value:day,writable:false},
                'month':{value:month,writable:false},
                'year':{value:year,writable:false},
                'gdate':{value:gDate,writable:false}
            });
        }

        var PureDateFromG = function (gDate) {
            gDate=+gDate; // unary + converts string to number, if needed
            /* Credits: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
            var y = ~~(((10000*gDate) + 14780)/3652425);
            var ddd = gDate - (365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)));
            if (ddd < 0) {
             y = y - 1;
             ddd = gDate - (365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)));
            }
            var mi = ~~((100*ddd + 52)/3060);
            var mm = (mi + 2)%12 + 1;
            y = y + (~~((mi + 2)/12));
            var dd = ddd - (~~((mi*306 + 5)/10)) + 1;

            return new PureDateInstance(y, mm, dd, gDate);
        }

        var PureDateFromYMD = function (year, month, day) {
            year=+year;month=+month;day=+day; // 'unary +' to convert string to integer if needed
            var gDate = g(year, month, day);
            return new PureDateInstance(year, month, day, gDate);
        }

        var Today = function () {
           var today = new Date();
           var day = today.getDate();
           var month = today.getMonth()+1; //January is 0!
           var year = today.getFullYear();

           return PureDateFromYMD(year, month, day);
       }

        PureDateInstance.prototype.addDays=function (numDays) {
            return PureDateFromG(this.gdate+numDays);
        }

        /**
         * Create a new PureDate adding months to this.
         *
         * @param numMonths to add. Can be negative to subtract months.
         * @return new PureDate
         */
        PureDateInstance.prototype.addMonths=function(numMonths) {

            var gM = (this.year*12)+this.month+numMonths;
            var newYear = ~~(gM/12);
            var newMonth = (gM%12);

            var gD=this.g(newYear, newMonth, this.day);

            var newPureDate = PureDateFromG(gD);
            if (newPureDate.month!=newMonth) {
                newPureDate=newPureDate.addDays(-newPureDate.day);
            }
            return newPureDate;
        }
        /**
         *
         * @return true if is leap year.
         */
        PureDateInstance.prototype.isLeapYear=function() {
            return (this.year%400==0) || (this.year%4==0 && this.year%100!=0);
        }
        PureDateInstance.prototype.dayOfWeek = function() {
            /* Only works for Gregorian Calendar (after year 1800)
            returns 0 for Sunday, 6-Saturday */
            var sundayOfReference = 4; /* day=5/March/year=00 */
            return (this.gdate - sundayOfReference) % 7;
        }
        PureDateInstance.prototype.getFirstDayOfMonth=function() {
            return PureDateFromYMD(this.year, this.month, 1);
        }
        PureDateInstance.prototype.getFirstDayOfYear=function() {
            return PureDateFromYMD(this.year, PureDate.JANUARY, 1);
        }
        PureDateInstance.prototype.getLastDayOfMonth=function() {
            var lastDayOfMonth = lastDaysArray[this.month-1];
            if (this.month===PureDate.FEBRUARY && this.isLeapYear()) {
                lastDayOfMonth = 29;
            }
            return PureDateFromYMD(this.year, this.month, lastDayOfMonth);
        }
        PureDateInstance.prototype.getLastDayOfYear=function() {
            return PureDateFromYMD(this.year, PureDate.DECEMBER, 31);
        }

        // returns PureDate 'Builder' obj
        return {
           gdate: PureDateFromG,
           ymd: PureDateFromYMD,
           today: Today,
           JANUARY:1,
            FEBRUARY:2,
            MARCH:3,
            APRIL:4,
            MAY:5,
            JUNE:6,
            JULY:7,
            AUGUST:8,
            SEPTEMBER:9,
            OCTOBER:10,
            NOVEMBER:11,
            DECEMBER:12,
           SUNDAY:0,
            MONDAY:1,
            TUESDAY:2,
            WEDNESDAY:3,
            THURSDAY:4,
            FRIDAY:5,
            SATURDAY:6
        };
})();

// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

if (typeof module !== "undefined" && module !== null) {
  module.exports = PureDate;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  define([], function() {
    return PureDate;
  });
}
<commit_msg>Bug Fix at 'addMonths()' method.<commit_after>"use strict";
/* puredate.js
 *
 * The most 'pure' date without time information. No timezone hell.
 * 2014-12-02
 *
 * By Sergio M C Figueiredo
 *
 * http://sergio.figueiredo.nom.br
 *
 */

var PureDate = PureDate
    || (function () {
    "use strict";

        var lastDaysArray = [31,28,31,30,31,30,31,31,30,31,30,31];
        /**
         * Returns the number of days since March 01, 0000.
         *
         * Credits: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
         */
        function g(y, m, d) {
            m = (m + 9) % 12;
            y = y - (~~(m/10)); // (~~(a/b)) forces integer division at a/b
            return 365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)) + (~~((m*306 + 5)/10)) + ( d - 1 );
        }

        function PureDateInstance(year, month, day, gDate) {
            Object.defineProperties(this, {
                /* public read-only properties */
                'day':{value:day,writable:false},
                'month':{value:month,writable:false},
                'year':{value:year,writable:false},
                'gdate':{value:gDate,writable:false}
            });
        }

        var PureDateFromG = function (gDate) {
            gDate=+gDate; // unary + converts string to number, if needed
            /* Credits: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html */
            var y = ~~(((10000*gDate) + 14780)/3652425);
            var ddd = gDate - (365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)));
            if (ddd < 0) {
             y = y - 1;
             ddd = gDate - (365*y + (~~(y/4)) - (~~(y/100)) + (~~(y/400)));
            }
            var mi = ~~((100*ddd + 52)/3060);
            var mm = (mi + 2)%12 + 1;
            y = y + (~~((mi + 2)/12));
            var dd = ddd - (~~((mi*306 + 5)/10)) + 1;

            return new PureDateInstance(y, mm, dd, gDate);
        }

        var PureDateFromYMD = function (year, month, day) {
            year=+year;month=+month;day=+day; // 'unary +' to convert string to integer if needed
            var gDate = g(year, month, day);
            return new PureDateInstance(year, month, day, gDate);
        }

        var Today = function () {
           var today = new Date();
           var day = today.getDate();
           var month = today.getMonth()+1; //January is 0!
           var year = today.getFullYear();

           return PureDateFromYMD(year, month, day);
       }

        PureDateInstance.prototype.addDays=function (numDays) {
            return PureDateFromG(this.gdate+numDays);
        }

        /**
         * Create a new PureDate adding months to this.
         *
         * @param numMonths to add. Can be negative to subtract months.
         * @return new PureDate
         */
        PureDateInstance.prototype.addMonths=function(numMonths) {

            var gM = (this.year*12)+this.month+numMonths;
            var newYear = ~~(gM/12);
            var newMonth = (gM%12);

            var newPureDate = PureDateFromYMD(newYear, newMonth, this.day);
            if (newPureDate.month!=newMonth) {
                newPureDate=newPureDate.addDays(-newPureDate.day);
            }
            return newPureDate;
        }
        /**
         *
         * @return true if is leap year.
         */
        PureDateInstance.prototype.isLeapYear=function() {
            return (this.year%400==0) || (this.year%4==0 && this.year%100!=0);
        }
        PureDateInstance.prototype.dayOfWeek = function() {
            /* Only works for Gregorian Calendar (after year 1800)
            returns 0 for Sunday, 6-Saturday */
            var sundayOfReference = 4; /* day=5/March/year=00 */
            return (this.gdate - sundayOfReference) % 7;
        }
        PureDateInstance.prototype.getFirstDayOfMonth=function() {
            return PureDateFromYMD(this.year, this.month, 1);
        }
        PureDateInstance.prototype.getFirstDayOfYear=function() {
            return PureDateFromYMD(this.year, PureDate.JANUARY, 1);
        }
        PureDateInstance.prototype.getLastDayOfMonth=function() {
            var lastDayOfMonth = lastDaysArray[this.month-1];
            if (this.month===PureDate.FEBRUARY && this.isLeapYear()) {
                lastDayOfMonth = 29;
            }
            return PureDateFromYMD(this.year, this.month, lastDayOfMonth);
        }
        PureDateInstance.prototype.getLastDayOfYear=function() {
            return PureDateFromYMD(this.year, PureDate.DECEMBER, 31);
        }

        // returns PureDate 'Builder' obj
        return {
           gdate: PureDateFromG,
           ymd: PureDateFromYMD,
           today: Today,
           JANUARY:1,
            FEBRUARY:2,
            MARCH:3,
            APRIL:4,
            MAY:5,
            JUNE:6,
            JULY:7,
            AUGUST:8,
            SEPTEMBER:9,
            OCTOBER:10,
            NOVEMBER:11,
            DECEMBER:12,
           SUNDAY:0,
            MONDAY:1,
            TUESDAY:2,
            WEDNESDAY:3,
            THURSDAY:4,
            FRIDAY:5,
            SATURDAY:6
        };
})();

// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

if (typeof module !== "undefined" && module !== null) {
  module.exports = PureDate;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
  define([], function() {
    return PureDate;
  });
}
<|endoftext|>