<commit_before>(function () {
    function Calque(inputEl, outputEl) {
        var calque = this;

        calque.inputEl = inputEl;
        calque.outputEl = outputEl;
        calque.parentEl = inputEl.parentNode;

        calque.raw = '';
        calque.lines = [];
        calque.cache = {};

        calque.selection = '';
        calque.selectionStart = 0;
        calque.selectionEnd = 0;

        var last = 0;
        var handler = function (delayed) {
            if (last === Date.now()) return;
            else last = Date.now();

            calque.input();
            calque.inputEl.style.height = Math.max(calque.outputEl.clientHeight, calque.parentEl.clientHeight) + 'px';
        };

        handler();

        calque.inputEl.oninput = handler;

        calque.inputEl.onmousedown = function () {
            window.requestAnimationFrame(handler);
        };

        calque.inputEl.onkeydown = function (event) {
            if (event.key === 'Enter') {
                var line = calque.lines.filter(line =>  line.selected).pop();

                var insert = '\n';
                if (line.summing) insert += '  ';
                for (var i = 0; i < line.indent; i++) insert += '  ';

                calque.replaceSelection(insert, false);
                event.preventDefault();
            }

            if (event.metaKey || event.ctrlKey) {
                if (event.key === 'd' || event.key === 'в') {
                    calque.duplicateSelection();
                    event.preventDefault();
                }
            }

            if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
                var selectionStart = calque.inputEl.selectionStart;
                var selectionEnd = calque.inputEl.selectionEnd;

                var selection = calque.raw.substring(selectionStart, selectionEnd);

                if (selection.match(/^-?\d+\.?\d*$/)) {
                    var newValue = selection * 1;

                    if (event.key === 'ArrowUp') newValue += event.shiftKey ? 10 : 1;
                    if (event.key === 'ArrowDown') newValue -= event.shiftKey ? 10 : 1;

                    calque.replaceSelection(newValue);
                    event.preventDefault();
                }
            }

            if (event.key === 'Tab') {
                if (event.shiftKey) {
                    calque.removeIndent();
                } else {
                    calque.addIndent();
                }

                event.preventDefault();
            }

            window.requestAnimationFrame(handler);
        };

        setTimeout(function fn() {
            setTimeout(fn, 50);
            handler();
        });

        calque.outputEl.scrollTop = calque.inputEl.scrollTop;
    }

    Calque.prototype.input = function () {
        var calque = this;

        var raw = calque.inputEl.value;
        if (raw !== calque.raw) {
            calque.raw = raw;
            calque.recalc();

            localStorage.setItem("input", calque.raw);
        }

        calque.readSelection();

        calque.repaint();
    };

    Calque.prototype.recalc = function () {
        var calque = this;

        calque.lines = [];

        var scope = {
            last: null
        };

        var position = 0;
        calque.raw.split("\n").forEach(function (code, index) {
            var line = {
                index: index,
                code: code,
                positionStart: position,
                positionEnd: position + code.length,
                result: null,
                error: null,
                indent: 0,
                summing: null,
                closed: false,
            };

            position += code.length + 1;

            calque.lines.push(line);

            if (line.code.substr(0, 2) === '  ') {
                line.indent = line.code.match(/\s+/)[0].match(/\s\s/g).length;
            }

            calque.lines.forEach(function (line2) {
                if (line2.summing && line2.indent >= line.indent) {
                    line2.closed = true;
                    scope[line2.summing] = line2.result;
                }
            });

            if (line.code.trim().slice(-1) === ':' && line.code.indexOf('#') < 0) {
                line.summing = line.code.trim().slice(0, -1).trim();
                line.result = 0;
                line.closed = false;
                line.children = [];
            } else {
                try {
                    var cached = calque.cache[line.code];
                    if (!cached) {
                        cached = {};
                        calque.cache[line.code] = cached;
                        cached.parsed = math.parse(line.code);
                        cached.compiled = cached.parsed.compile();
                    }

                    line.parsed = cached.parsed;
                    line.compiled = cached.compiled;
                    line.result = line.compiled.eval(scope);
                } catch (e) {
                    line.error = e.toString();
                }
            }

            if (line.result !== undefined) {
                calque.lines.forEach(function (line2) {
                    if (line2.summing && !line2.closed && line2.indent < line.indent) {
                        line2.children.push(line);

                        try {
                            line2.result = math.add(line2.result, line.result);
                        } catch (e) {
                            line2.error = e.toString();
                        }
                    }
                });

                scope.last = line.result;
            }
        });
    };

    Calque.prototype.readActiveLine = function () {
        var calque = this;

        var value = calque.inputEl.value;
        var selectionStart = calque.inputEl.selectionStart;

        var match = value.substr(0, selectionStart).match(/\n/g);
        var index = match ? match.length : 0;
        calque.line = calque.lines[index];
    };

    Calque.prototype.readSelection = function () {
        var calque = this;

        calque.selectionStart = calque.inputEl.selectionStart;
        calque.selectionEnd = calque.inputEl.selectionEnd;

        calque.selection = calque.raw.substring(calque.selectionStart, calque.selectionEnd);

        calque.lines.forEach(function (line) {
            line.selected = false;

            var leftCheck = line.positionEnd >= calque.selectionStart;
            var rightCheck = line.positionStart <= calque.selectionEnd;
            if (leftCheck && rightCheck) line.selected = true;
        });
    };

    Calque.prototype.replaceSelection = function (replacement, select) {
        var calque = this;

        calque.readSelection();

        select = select === false ? false : true;
        replacement = replacement.toString();

        var newSelectionStart = calque.selectionStart;
        var newSelectionEnd = calque.selectionStart + replacement.length;

        if (!document.execCommand('insertText', false, replacement)) {
            calque.inputEl.setRangeText(replacement, calque.selectionStart, calque.selectionEnd, 'end');
            calque.input();
        }

        if (select) {
            calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
        } else {
            calque.inputEl.setSelectionRange(newSelectionEnd, newSelectionEnd);
        }
    };

    Calque.prototype.duplicateSelection = function () {
        var calque = this;

        if (calque.selection === '') {
            var line = calque.lines.find(function (line) {
                return line.selected;
            });

            calque.inputEl.setSelectionRange(line.positionEnd, line.positionEnd);
            calque.replaceSelection('\n' + line.code);
            calque.inputEl.setSelectionRange(calque.selectionStart, calque.selectionStart);
         } else {
            var selection = calque.selection;

            calque.inputEl.setSelectionRange(calque.selectionEnd, calque.selectionEnd);
            calque.replaceSelection(selection);
            calque.inputEl.setSelectionRange(calque.selectionStart - selection.length, calque.selectionStart);
        }
    };

    Calque.prototype.addIndent = function () {
        var calque = this;

        var selectionStart = Infinity;
        var selectionEnd = 0;

        var affected = 0;
        var replacement = '';

        calque.lines.forEach(function (line) {
            if (!line.selected) return false;

            affected++;
            replacement += '  ' + line.code + '\n';

            if (line.positionStart <= selectionStart) {
                selectionStart = line.positionStart;
            }

            if (line.positionEnd > selectionEnd) {
                selectionEnd = line.positionEnd;
            }
        });

        if (affected === 0) return;

        replacement = replacement.substr(0, replacement.length - 1);

        var newSelectionStart = calque.selectionStart + 2;
        var newSelectionEnd = calque.selectionEnd + affected * 2;

        calque.inputEl.setSelectionRange(selectionStart, selectionEnd);
        calque.replaceSelection(replacement);
        calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
    };

    Calque.prototype.removeIndent = function () {
        var calque = this;

        var selectionStart = Infinity;
        var selectionEnd = 0;

        var affected = 0;
        var replacement = '';

        calque.lines.forEach(function (line) {
            if (!line.selected) return false;
            if (line.code.substr(0, 2) !== '  ') return;

            affected++;
            replacement += line.code.substr(2) + '\n';

            if (line.positionStart <= selectionStart) {
                selectionStart = line.positionStart;
            }

            if (line.positionEnd > selectionEnd) {
                selectionEnd = line.positionEnd;
            }
        });

        if (affected === 0) return;

        replacement = replacement.substr(0, replacement.length - 1);

        var newSelectionStart = calque.selectionStart - 2;
        var newSelectionEnd = calque.selectionEnd - affected * 2;

        calque.inputEl.setSelectionRange(selectionStart, selectionEnd);
        calque.replaceSelection(replacement);
        calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
    };

    Calque.prototype.repaint = function () {
        var calque = this;

        var html = '';

        calque.lines.forEach(function (line, index) {
            if (line.error) {
                if (line.selected) {
                    var type = 'empty';
                } else {
                    if (line.summing && line.children.find(line => line.error)) {
                        var type = 'empty';
                    } else {
                        var type = 'error';
                    }
                }
            } else if (line.summing) {
                var type = 'result';
            } else if (line.result === undefined) {
                var type = 'empty';
            } else if (line.parsed.isFunctionAssignmentNode) {
                var type = 'empty';
            } else if (line.parsed.isConstantNode) {
                var type = 'empty';
            } else if (line.parsed.isAssignmentNode && line.parsed.value.isConstantNode) {
                var type = 'empty';
            } else {
                var type = 'result';
            }

            var code = line.code || ' ';
            var prefix = ' ';
            for (var i = 0; i < line.indent; i++) code = code.replace(/(\| )?  /, '$1| ');

            if (type === 'result') prefix += '= ';
            else if (type === 'error') prefix += '// ';

            var data = '';
            if (type === 'result') data = line.result.toString();
            else if (type === 'error') data = line.error;

            data = data.replace(/\n/g, '\\n');

            if (line.selected) type += ' highlight';

            var lineHtml = '
';
            lineHtml += '';
            lineHtml += '' + data + '';
            lineHtml += '
';

            html += lineHtml;
        });

        calque.outputEl.innerHTML = html;
    };

    window.Calque = Calque;
})();<commit_msg>Round float numbers<commit_after>(function () {
    function Calque(inputEl, outputEl) {
        var calque = this;

        calque.inputEl = inputEl;
        calque.outputEl = outputEl;
        calque.parentEl = inputEl.parentNode;

        calque.raw = '';
        calque.lines = [];
        calque.cache = {};

        calque.selection = '';
        calque.selectionStart = 0;
        calque.selectionEnd = 0;

        var last = 0;
        var handler = function (delayed) {
            if (last === Date.now()) return;
            else last = Date.now();

            calque.input();
            calque.inputEl.style.height = Math.max(calque.outputEl.clientHeight, calque.parentEl.clientHeight) + 'px';
        };

        handler();

        calque.inputEl.oninput = handler;

        calque.inputEl.onmousedown = function () {
            window.requestAnimationFrame(handler);
        };

        calque.inputEl.onkeydown = function (event) {
            if (event.key === 'Enter') {
                var line = calque.lines.filter(line =>  line.selected).pop();

                var insert = '\n';
                if (line.summing) insert += '  ';
                for (var i = 0; i < line.indent; i++) insert += '  ';

                calque.replaceSelection(insert, false);
                event.preventDefault();
            }

            if (event.metaKey || event.ctrlKey) {
                if (event.key === 'd' || event.key === 'в') {
                    calque.duplicateSelection();
                    event.preventDefault();
                }
            }

            if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
                var selectionStart = calque.inputEl.selectionStart;
                var selectionEnd = calque.inputEl.selectionEnd;

                var selection = calque.raw.substring(selectionStart, selectionEnd);

                if (selection.match(/^-?\d+\.?\d*$/)) {
                    var newValue = selection * 1;

                    if (event.key === 'ArrowUp') newValue += event.shiftKey ? 10 : 1;
                    if (event.key === 'ArrowDown') newValue -= event.shiftKey ? 10 : 1;

                    calque.replaceSelection(newValue);
                    event.preventDefault();
                }
            }

            if (event.key === 'Tab') {
                if (event.shiftKey) {
                    calque.removeIndent();
                } else {
                    calque.addIndent();
                }

                event.preventDefault();
            }

            window.requestAnimationFrame(handler);
        };

        setTimeout(function fn() {
            setTimeout(fn, 50);
            handler();
        });

        calque.outputEl.scrollTop = calque.inputEl.scrollTop;
    }

    Calque.prototype.input = function () {
        var calque = this;

        var raw = calque.inputEl.value;
        if (raw !== calque.raw) {
            calque.raw = raw;
            calque.recalc();

            localStorage.setItem("input", calque.raw);
        }

        calque.readSelection();

        calque.repaint();
    };

    Calque.prototype.recalc = function () {
        var calque = this;

        calque.lines = [];

        var scope = {
            last: null
        };

        var position = 0;
        calque.raw.split("\n").forEach(function (code, index) {
            var line = {
                index: index,
                code: code,
                positionStart: position,
                positionEnd: position + code.length,
                result: null,
                error: null,
                indent: 0,
                summing: null,
                closed: false,
            };

            position += code.length + 1;

            calque.lines.push(line);

            if (line.code.substr(0, 2) === '  ') {
                line.indent = line.code.match(/\s+/)[0].match(/\s\s/g).length;
            }

            calque.lines.forEach(function (line2) {
                if (line2.summing && line2.indent >= line.indent) {
                    line2.closed = true;
                    scope[line2.summing] = line2.result;
                }
            });

            if (line.code.trim().slice(-1) === ':' && line.code.indexOf('#') < 0) {
                line.summing = line.code.trim().slice(0, -1).trim();
                line.result = 0;
                line.closed = false;
                line.children = [];
            } else {
                try {
                    var cached = calque.cache[line.code];
                    if (!cached) {
                        cached = {};
                        calque.cache[line.code] = cached;
                        cached.parsed = math.parse(line.code);
                        cached.compiled = cached.parsed.compile();
                    }

                    line.parsed = cached.parsed;
                    line.compiled = cached.compiled;
                    line.result = line.compiled.eval(scope);
                } catch (e) {
                    line.error = e.toString();
                }
            }

            if (line.result !== undefined) {
                calque.lines.forEach(function (line2) {
                    if (line2.summing && !line2.closed && line2.indent < line.indent) {
                        line2.children.push(line);

                        try {
                            line2.result = math.add(line2.result, line.result);
                        } catch (e) {
                            line2.error = e.toString();
                        }
                    }
                });

                scope.last = line.result;
            }
        });
    };

    Calque.prototype.readActiveLine = function () {
        var calque = this;

        var value = calque.inputEl.value;
        var selectionStart = calque.inputEl.selectionStart;

        var match = value.substr(0, selectionStart).match(/\n/g);
        var index = match ? match.length : 0;
        calque.line = calque.lines[index];
    };

    Calque.prototype.readSelection = function () {
        var calque = this;

        calque.selectionStart = calque.inputEl.selectionStart;
        calque.selectionEnd = calque.inputEl.selectionEnd;

        calque.selection = calque.raw.substring(calque.selectionStart, calque.selectionEnd);

        calque.lines.forEach(function (line) {
            line.selected = false;

            var leftCheck = line.positionEnd >= calque.selectionStart;
            var rightCheck = line.positionStart <= calque.selectionEnd;
            if (leftCheck && rightCheck) line.selected = true;
        });
    };

    Calque.prototype.replaceSelection = function (replacement, select) {
        var calque = this;

        calque.readSelection();

        select = select === false ? false : true;
        replacement = replacement.toString();

        var newSelectionStart = calque.selectionStart;
        var newSelectionEnd = calque.selectionStart + replacement.length;

        if (!document.execCommand('insertText', false, replacement)) {
            calque.inputEl.setRangeText(replacement, calque.selectionStart, calque.selectionEnd, 'end');
            calque.input();
        }

        if (select) {
            calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
        } else {
            calque.inputEl.setSelectionRange(newSelectionEnd, newSelectionEnd);
        }
    };

    Calque.prototype.duplicateSelection = function () {
        var calque = this;

        if (calque.selection === '') {
            var line = calque.lines.find(function (line) {
                return line.selected;
            });

            calque.inputEl.setSelectionRange(line.positionEnd, line.positionEnd);
            calque.replaceSelection('\n' + line.code);
            calque.inputEl.setSelectionRange(calque.selectionStart, calque.selectionStart);
         } else {
            var selection = calque.selection;

            calque.inputEl.setSelectionRange(calque.selectionEnd, calque.selectionEnd);
            calque.replaceSelection(selection);
            calque.inputEl.setSelectionRange(calque.selectionStart - selection.length, calque.selectionStart);
        }
    };

    Calque.prototype.addIndent = function () {
        var calque = this;

        var selectionStart = Infinity;
        var selectionEnd = 0;

        var affected = 0;
        var replacement = '';

        calque.lines.forEach(function (line) {
            if (!line.selected) return false;

            affected++;
            replacement += '  ' + line.code + '\n';

            if (line.positionStart <= selectionStart) {
                selectionStart = line.positionStart;
            }

            if (line.positionEnd > selectionEnd) {
                selectionEnd = line.positionEnd;
            }
        });

        if (affected === 0) return;

        replacement = replacement.substr(0, replacement.length - 1);

        var newSelectionStart = calque.selectionStart + 2;
        var newSelectionEnd = calque.selectionEnd + affected * 2;

        calque.inputEl.setSelectionRange(selectionStart, selectionEnd);
        calque.replaceSelection(replacement);
        calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
    };

    Calque.prototype.removeIndent = function () {
        var calque = this;

        var selectionStart = Infinity;
        var selectionEnd = 0;

        var affected = 0;
        var replacement = '';

        calque.lines.forEach(function (line) {
            if (!line.selected) return false;
            if (line.code.substr(0, 2) !== '  ') return;

            affected++;
            replacement += line.code.substr(2) + '\n';

            if (line.positionStart <= selectionStart) {
                selectionStart = line.positionStart;
            }

            if (line.positionEnd > selectionEnd) {
                selectionEnd = line.positionEnd;
            }
        });

        if (affected === 0) return;

        replacement = replacement.substr(0, replacement.length - 1);

        var newSelectionStart = calque.selectionStart - 2;
        var newSelectionEnd = calque.selectionEnd - affected * 2;

        calque.inputEl.setSelectionRange(selectionStart, selectionEnd);
        calque.replaceSelection(replacement);
        calque.inputEl.setSelectionRange(newSelectionStart, newSelectionEnd);
    };

    Calque.prototype.repaint = function () {
        var calque = this;

        var html = '';

        calque.lines.forEach(function (line, index) {
            if (line.error) {
                if (line.selected) {
                    var type = 'empty';
                } else {
                    if (line.summing && line.children.find(line => line.error)) {
                        var type = 'empty';
                    } else {
                        var type = 'error';
                    }
                }
            } else if (line.summing) {
                var type = 'result';
            } else if (line.result === undefined) {
                var type = 'empty';
            } else if (line.parsed.isFunctionAssignmentNode) {
                var type = 'empty';
            } else if (line.parsed.isConstantNode) {
                var type = 'empty';
            } else if (line.parsed.isAssignmentNode && line.parsed.value.isConstantNode) {
                var type = 'empty';
            } else {
                var type = 'result';
            }

            var code = line.code || ' ';
            var prefix = ' ';
            for (var i = 0; i < line.indent; i++) code = code.replace(/(\| )?  /, '$1| ');

            if (type === 'result') prefix += '= ';
            else if (type === 'error') prefix += '// ';

            var data = '';
            if (type === 'result') {
                if (typeof line.result === 'number') {
                    data = math.round(line.result, 10).toString();
                } else {
                    data = line.result.toString();
                }
            }
            else if (type === 'error') data = line.error;

            data = data.replace(/\n/g, '\\n');

            if (line.selected) type += ' highlight';

            var lineHtml = '
';
            lineHtml += '';
            lineHtml += '' + data + '';
            lineHtml += '
';

            html += lineHtml;
        });

        calque.outputEl.innerHTML = html;
    };

    window.Calque = Calque;
})();<|endoftext|>


<commit_before>var Coord = function (x, y) {
    return {x:x, y:y};
};

var Color = function (red, green, blue) {
    return {red: red, green: green, blue: blue};
};

var Pad = function (canvas) {
    var DEFAULT_CIRCLE_RADIUS = 5;
    var DEFAULT_LINE_WIDTH = 2;

    var context = canvas.getContext('2d');
    var width = canvas.width;
    var height = canvas.height;

    var apply_line_width = function (ctx, line_width) {
        ctx.lineWidth = (line_width) ? line_width : DEFAULT_LINE_WIDTH;
    }

    var apply_color = function (ctx, color) {
        if (color) {
            ctx.strokeStyle = 'rgba(' + color.red + ',' + color.green + ',' + color.blue + ', 1)';
        }
    }

    var apply_fill_color = function (ctx, color) {
        if (color) {
            ctx.fillStyle = 'rgba(' + color.red + ',' + color.green + ',' + color.blue + ', 1)';
	    ctx.fill();
        }
    }

    return {
	// Draws a circle at the given coordinate (as returned by the
	// Coord function) of the given radius (defaulting to
	// DEFAULT_CIRCLE_RADIUS if the radius is 0 or omitted). An
	// optional line width can be supplied (defaults to
	// DEFAULT_LINE_WIDTH otherwise), as well as an optional color
	// and fill color (both objects returned by the Color
	// function).
        draw_circle: function (coord, radius, line_width, color, fill_color) {
            context.beginPath();
            context.arc(coord.x, coord.y,
                        (radius) ? radius : DEFAULT_CIRCLE_RADIUS,
                        0, Math.PI*2, true);
            context.closePath();
            apply_line_width(context, line_width);
            apply_color(context, color);
            apply_fill_color(context, fill_color);
            context.stroke();
        },

	// Draws a line between the given coordinates (as returned by
	// the Coord function). An optional line width can be supplied
	// (defaults to DEFAULT_LINE_WIDTH otherwise), as well as an
	// optional color (returned by the Color function).
        draw_line: function (from, to, line_width, color) {
            context.beginPath();
            context.moveTo(from.x, from.y);
            context.lineTo(to.x, to.y);
            apply_line_width(context, line_width);
            apply_color(context, color);
            context.lineWidth = (line_width) ? line_width : DEFAULT_LINE_WIDTH;
            context.fill();
            context.closePath();
            context.stroke();
        },

	// Draws a rectangle starting at the top left corner (as
	// returned by the Coord function) of the given width and
	// height. An optional line width can be supplied (defaults to
	// DEFAULT_LINE_WIDTH otherwise), as well as an optional color
	// and fill color (both returned by the Color function).
            context.beginPath();
            context.rect(top_left.x, top_left.y, width, height);
            apply_line_width(context, line_width);
            apply_color(context, color);
            context.closePath();
            context.stroke();
        },

	// Clears the entire board
        clear: function () {
            context.clearRect(0, 0, width, height);
        },

        get_width: function () {return width;},
        get_height: function () {return height;}
    }
}<commit_msg>Removed fill from draw_line (since it doesn't make any sense) and added it to draw_rectangle<commit_after>var Coord = function (x, y) {
    return {x:x, y:y};
};

var Color = function (red, green, blue) {
    return {red: red, green: green, blue: blue};
};

var Pad = function (canvas) {
    var DEFAULT_CIRCLE_RADIUS = 5;
    var DEFAULT_LINE_WIDTH = 2;

    var context = canvas.getContext('2d');
    var width = canvas.width;
    var height = canvas.height;

    var apply_line_width = function (ctx, line_width) {
        ctx.lineWidth = (line_width) ? line_width : DEFAULT_LINE_WIDTH;
    }

    var apply_color = function (ctx, color) {
        if (color) {
            ctx.strokeStyle = 'rgba(' + color.red + ',' + color.green + ',' + color.blue + ', 1)';
        }
    }

    var apply_fill_color = function (ctx, color) {
        if (color) {
            ctx.fillStyle = 'rgba(' + color.red + ',' + color.green + ',' + color.blue + ', 1)';
	    ctx.fill();
        }
    }

    return {
	// Draws a circle at the given coordinate (as returned by the
	// Coord function) of the given radius (defaulting to
	// DEFAULT_CIRCLE_RADIUS if the radius is 0 or omitted). An
	// optional line width can be supplied (defaults to
	// DEFAULT_LINE_WIDTH otherwise), as well as an optional color
	// and fill color (both objects returned by the Color
	// function).
        draw_circle: function (coord, radius, line_width, color, fill_color) {
            context.beginPath();
            context.arc(coord.x, coord.y,
                        (radius) ? radius : DEFAULT_CIRCLE_RADIUS,
                        0, Math.PI*2, true);
            context.closePath();
            apply_line_width(context, line_width);
            apply_color(context, color);
            apply_fill_color(context, fill_color);
            context.stroke();
        },

	// Draws a line between the given coordinates (as returned by
	// the Coord function). An optional line width can be supplied
	// (defaults to DEFAULT_LINE_WIDTH otherwise), as well as an
	// optional color (returned by the Color function).
        draw_line: function (from, to, line_width, color) {
            context.beginPath();
            context.moveTo(from.x, from.y);
            context.lineTo(to.x, to.y);
            apply_line_width(context, line_width);
            apply_color(context, color);
            context.lineWidth = (line_width) ? line_width : DEFAULT_LINE_WIDTH;
            context.closePath();
            context.stroke();
        },

	// Draws a rectangle starting at the top left corner (as
	// returned by the Coord function) of the given width and
	// height. An optional line width can be supplied (defaults to
	// DEFAULT_LINE_WIDTH otherwise), as well as an optional color
	// and fill color (both returned by the Color function).
        draw_rectangle: function (top_left, width, height, line_width, color, fill_color) {
            context.beginPath();
            context.rect(top_left.x, top_left.y, width, height);
            apply_line_width(context, line_width);
            apply_color(context, color);
	    apply_fill_color(context, fill_color);
            context.closePath();
            context.stroke();
        },

	// Clears the entire board
        clear: function () {
            context.clearRect(0, 0, width, height);
        },

        get_width: function () {return width;},
        get_height: function () {return height;}
    }
}<|endoftext|>


<commit_before>app.config([
    '$stateProvider', '$urlRouterProvider', '$contentProvider', '$httpProvider', '$locationProvider', 'toastrConfig', 'markedProvider',
    function($stateProvider, $urlRouterProvider, $contentProvider, $httpProvider, $locationProvider, toastrConfig, markedProvider) {
        // Configure content base url.
        $contentProvider.urlPrefix = staticUrl;

        // Markdown library setup.
        markedProvider.setOptions({
            gfm: true,
            tables: true,
            highlight: function (code, lang) {
                if (lang) {
                    return hljs.highlight(lang, code, true).value;
                } else {
                    return hljs.highlightAuto(code).value;
                }
            }
        });

        // Toastr configurations.
        angular.extend(toastrConfig, {
            target: 'body',
            allowHtml: false,
            closeButton: false,
            closeHtml: '<button>×</button>',
            extendedTimeOut: 1000,
            iconClasses: {
                error: 'toast-error',
                info: 'toast-info',
                success: 'toast-success',
                warning: 'toast-warning'
            },
            messageClass: 'toast-message',
            onHidden: null,
            onShown: null,
            onTap: null,
            progressBar: false,
            tapToDismiss: true,
            templates: {
                toast: $contentProvider.url('angular/directives/toast/toast.html'),
                progressbar: $contentProvider.url('angular/directives/toast/progressbar.html'),
            },
            timeOut: 5000,
            titleClass: 'toast-title',
            toastClass: 'toast'
        });

        // Token interceptor.
        $httpProvider.interceptors.push(function($q, $localStorage, $rootScope) {
            return {
                request: function(config) {
                    config.headers = config.headers || {};
                    if ($localStorage.token) {
                        config.headers.Authorization = "jwt " + $localStorage.token;
                    }
                    return config;
                },
                responseError: function(response) {
                    if (response.status === 401 || response.status === 403) {
                        $rootScope.$emit("unauthorized");
                    }
                    return $q.reject(response);
                }
            };
        });

        /*
         * States.
         */
        $stateProvider
            /*
             * Login states
             */
            .state('login', {
                url: '/login',
                templateUrl: $contentProvider.url('angular/views/login/main.html'),
                controller: "AuthCtrl"
            })
            /*
             * Panel states
             */
            .state('panel', {
                url: '/panel',
                abstract: true,
                views: {
                    "": {
                        templateUrl: $contentProvider.url('angular/views/panel/main.html'),
                    },
                    "header@panel": {
                        templateUrl: $contentProvider.url('angular/views/panel/header.html'),
                    },
                    "sidenav@panel": {
                        templateUrl: $contentProvider.url('angular/views/panel/sidenav.html'),
                    }
                }
            })
            .state('panel.areas', {
                url: '/areas',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/areas.html'),
                        controller: "AreaCtrl"
                    }
                }
            })
            .state('panel.subjects', {
                url: '/areas/:areaId/subjects',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/subjects.html'),
                        controller: "SubjectCtrl"
                    }
                }
            })
            .state('panel.posts', {
                url: '/areas/:areaId/subjects/:subjectId/posts',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/posts.html'),
                        controller: "PostsCtrl"
                    }
                }
            })
            .state('panel.post', {
                url: '/areas/:areaId/subjects/:subjectId/posts/:id',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/post.html'),
                        controller: "PostCtrl"
                    }
                }
            })
            .state('panel.addPost', {
                url: '/areas/:areaId/subjects/:subjectId/add-contribution',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "CreatePostCtrl"
                    }
                }
            })

            .state('panel.contributions', {
                url: '/contributions',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/list.html'),
                        controller: "ContributionsCtrl"
                    }
                }
            })

            .state('panel.contribution', {
                url: '/contribution/:postId',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/detail.html'),
                        controller: "ContributionCtrl"
                    }
                }
            })
            .state('panel.addContribution', {
                url: '/add-contribution',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "CreateContributionCtrl"
                    }
                }
            })
            .state('panel.editContribution', {
                url: '/edit-contribution/:postId',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "EditContributionCtrl"
                    }
                }
            })

            .state('panel.editProfile', {
                url: '/edit-profile',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/profile/edit.html'),
                        controller: "EditProfileCtrl"
                    }
                }
            });

        return $urlRouterProvider.otherwise('/panel/areas');
    }
]).run(['$rootScope', '$content', '$state',
    function($rootScope, $content, $state){
        // Importing vo-content provider to the entire project.
        $rootScope.$content = $content;

        $rootScope.$on('unauthorized', function() {
            $state.transitionTo('login');
        });
    }
]);
<commit_msg>Changing default route for project.<commit_after>app.config([
    '$stateProvider', '$urlRouterProvider', '$contentProvider', '$httpProvider', '$locationProvider', 'toastrConfig', 'markedProvider',
    function($stateProvider, $urlRouterProvider, $contentProvider, $httpProvider, $locationProvider, toastrConfig, markedProvider) {
        // Configure content base url.
        $contentProvider.urlPrefix = staticUrl;

        // Markdown library setup.
        markedProvider.setOptions({
            gfm: true,
            tables: true,
            highlight: function (code, lang) {
                if (lang) {
                    return hljs.highlight(lang, code, true).value;
                } else {
                    return hljs.highlightAuto(code).value;
                }
            }
        });

        // Toastr configurations.
        angular.extend(toastrConfig, {
            target: 'body',
            allowHtml: false,
            closeButton: false,
            closeHtml: '<button>×</button>',
            extendedTimeOut: 1000,
            iconClasses: {
                error: 'toast-error',
                info: 'toast-info',
                success: 'toast-success',
                warning: 'toast-warning'
            },
            messageClass: 'toast-message',
            onHidden: null,
            onShown: null,
            onTap: null,
            progressBar: false,
            tapToDismiss: true,
            templates: {
                toast: $contentProvider.url('angular/directives/toast/toast.html'),
                progressbar: $contentProvider.url('angular/directives/toast/progressbar.html'),
            },
            timeOut: 5000,
            titleClass: 'toast-title',
            toastClass: 'toast'
        });

        // Token interceptor.
        $httpProvider.interceptors.push(function($q, $localStorage, $rootScope) {
            return {
                request: function(config) {
                    config.headers = config.headers || {};
                    if ($localStorage.token) {
                        config.headers.Authorization = "jwt " + $localStorage.token;
                    }
                    return config;
                },
                responseError: function(response) {
                    if (response.status === 401 || response.status === 403) {
                        $rootScope.$emit("unauthorized");
                    }
                    return $q.reject(response);
                }
            };
        });

        /*
         * States.
         */
        $stateProvider
            /*
             * Login states
             */
            .state('login', {
                url: '/login',
                templateUrl: $contentProvider.url('angular/views/login/main.html'),
                controller: "AuthCtrl"
            })
            /*
             * Panel states
             */
            .state('panel', {
                url: '/panel',
                abstract: true,
                views: {
                    "": {
                        templateUrl: $contentProvider.url('angular/views/panel/main.html'),
                    },
                    "header@panel": {
                        templateUrl: $contentProvider.url('angular/views/panel/header.html'),
                    },
                    "sidenav@panel": {
                        templateUrl: $contentProvider.url('angular/views/panel/sidenav.html'),
                    }
                }
            })
            .state('panel.areas', {
                url: '/areas',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/areas.html'),
                        controller: "AreaCtrl"
                    }
                }
            })
            .state('panel.subjects', {
                url: '/areas/:areaId/subjects',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/subjects.html'),
                        controller: "SubjectCtrl"
                    }
                }
            })
            .state('panel.posts', {
                url: '/areas/:areaId/subjects/:subjectId/posts',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/posts.html'),
                        controller: "PostsCtrl"
                    }
                }
            })
            .state('panel.post', {
                url: '/areas/:areaId/subjects/:subjectId/posts/:id',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/catalogues/post.html'),
                        controller: "PostCtrl"
                    }
                }
            })
            .state('panel.addPost', {
                url: '/areas/:areaId/subjects/:subjectId/add-contribution',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "CreatePostCtrl"
                    }
                }
            })

            .state('panel.contributions', {
                url: '/contributions',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/list.html'),
                        controller: "ContributionsCtrl"
                    }
                }
            })

            .state('panel.contribution', {
                url: '/contribution/:postId',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/detail.html'),
                        controller: "ContributionCtrl"
                    }
                }
            })
            .state('panel.addContribution', {
                url: '/add-contribution',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "CreateContributionCtrl"
                    }
                }
            })
            .state('panel.editContribution', {
                url: '/edit-contribution/:postId',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/contributions/action.html'),
                        controller: "EditContributionCtrl"
                    }
                }
            })

            .state('panel.editProfile', {
                url: '/edit-profile',
                views: {
                    "content": {
                        templateUrl: $contentProvider.url('angular/views/profile/edit.html'),
                        controller: "EditProfileCtrl"
                    }
                }
            });

        return $urlRouterProvider.otherwise('/login');
    }
]).run(['$rootScope', '$content', '$state',
    function($rootScope, $content, $state){
        // Importing vo-content provider to the entire project.
        $rootScope.$content = $content;

        $rootScope.$on('unauthorized', function() {
            $state.transitionTo('login');
        });
    }
]);
<|endoftext|>


<commit_before>angular.module('Aggie')

.directive('ngSelectAll', function () {
  return {
    restrict: 'A',
    scope: {
      items: "="
    },

    link: function ($scope, $el, attrs) {
      $el.on('click', function () {
        var checked = $el[0].checked;

        angular.forEach($scope.items, function (item) {
          item.selected = checked;
        });

        $scope.$apply();
      });
    }
  };
});
<commit_msg>fixed ng-select-all directive<commit_after>angular.module('Aggie')

.directive('ngSelectAll', function() {
  return {
    restrict: 'A',
    scope: {
      items: "="
    },

    link: function($scope, $el, attrs) {
      $el.on('click', function() {
        var checked = $el[0].checked;

        angular.forEach($scope.items, function(item) {
          item.selected = checked;
        });

        $scope.$apply();
      });
    }
  };
});
<|endoftext|>


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

  var elasticsearch = require('elasticsearch'),
      clients = {},
      client = new elasticsearch.Client({
        host: 'localhost:9200',
      });

  module.exports = function(socket) {
      clients[socket.id] = socket;

      console.log('client connected');
      socket.on('disconnect', disconnect);
      socket.on('close', function() {
        disconnect();
      });

      /*chat*/
      socket.on('send_message', function(data) {
        socket.broadcast.to(data.room).emit('receive_message', data.message);
      });

      socket.on('videoRemoved', function(room) {
        socket.broadcast.to(room).emit('videoRemoved');
      });

      socket.on('stop', function(data) {
        socket.broadcast.to(data.room).emit('stop');
      });

      socket.on('find', function(data) {
        /* search for common interest */
        if (data.lat !== undefined && data.lon !== undefined && data.range !== undefined) {
          if (data.interest !== undefined) {
            /* location = true*/
            /* interest(tags) = true */
            console.log('location with interest');
            io.elastic_search_location_with_interest(client, clients, socket, data);
          } else {
            /* location = true*/
            /* interest(tags) = false */
            io.elastic_search_location(client, clients, socket, data);
          }
        } else {
          if (data.interest !== undefined) {
            io.elastic_search_interest(client, clients, socket, data);
          } else {
            /* make a random choice */
            io.elastic_search_random(client, clients, socket, data);
          }
        }
      });

      function disconnect() {
        /*search if we have this document*/
        client.search({
          index: 'webrtc',
          type: 'data',
          body: {
            query: {
              filtered: {
                /* first step we must know if the socket id is present*/
                filter: { term: { _id: socket.id }}
              }
            }
          }
        }).then(function (body) {
          var hits = body.hits.hits;
          if (hits.length !== 0) {
            var otherRoom = hits[0]._source.room;
            /* if we have document delete it*/
            client.delete({
              index: 'webrtc',
              type: 'data',
              id: socket.id
            }).then(function(body) {
              socket.broadcast.to(otherRoom).emit('stop');
              if (hits[0]._source.match_id !== 'null') {
                client.delete({
                  index: 'webrtc',
                  type: 'data',
                  id : hits[0]._source.match_id.toString()
                });
              }
            }, function(err) {
              return;
            });
          }
        }, function(error) {
          return;
        });
        console.log('client disconnected');
      }
  };
}());
<commit_msg>adding undefined<commit_after>(function() {
  'use strict';

  var elasticsearch = require('elasticsearch'),
      clients = {},
      client = new elasticsearch.Client({
        host: 'localhost:9200',
      });

  module.exports = function(socket) {
      clients[socket.id] = socket;

      console.log('client connected');
      socket.on('disconnect', disconnect);
      socket.on('close', function() {
        disconnect();
      });

      /*chat*/
      socket.on('send_message', function(data) {
        socket.broadcast.to(data.room).emit('receive_message', data.message);
      });

      socket.on('videoRemoved', function(room) {
        socket.broadcast.to(room).emit('videoRemoved');
      });

      socket.on('stop', function(data) {
        socket.broadcast.to(data.room).emit('stop');
      });

      socket.on('find', function(data) {
        /* search for common interest */
        if (data.lat !== undefined && data.lon !== undefined && data.range !== undefined) {
          if (data.interest !== undefined || data.interest === '') {
            /* location = true*/
            /* interest(tags) = true */
            console.log('location with interest');
            io.elastic_search_location_with_interest(client, clients, socket, data);
          } else {
            /* location = true*/
            /* interest(tags) = false */
            io.elastic_search_location(client, clients, socket, data);
          }
        } else {
          if (data.interest !== undefined || data.interest === '') {
            io.elastic_search_interest(client, clients, socket, data);
          } else {
            /* make a random choice */
            io.elastic_search_random(client, clients, socket, data);
          }
        }
      });

      function disconnect() {
        /*search if we have this document*/
        client.search({
          index: 'webrtc',
          type: 'data',
          body: {
            query: {
              filtered: {
                /* first step we must know if the socket id is present*/
                filter: { term: { _id: socket.id }}
              }
            }
          }
        }).then(function (body) {
          var hits = body.hits.hits;
          if (hits.length !== 0) {
            var otherRoom = hits[0]._source.room;
            /* if we have document delete it*/
            client.delete({
              index: 'webrtc',
              type: 'data',
              id: socket.id
            }).then(function(body) {
              socket.broadcast.to(otherRoom).emit('stop');
              if (hits[0]._source.match_id !== 'null') {
                client.delete({
                  index: 'webrtc',
                  type: 'data',
                  id : hits[0]._source.match_id.toString()
                });
              }
            }, function(err) {
              return;
            });
          }
        }, function(error) {
          return;
        });
        console.log('client disconnected');
      }
  };
}());
<|endoftext|>


<commit_before>(function() {
	var ua = navigator.userAgent.toLowerCase(),
		ie = !!window.ActiveXObject,
		webkit = ua.indexOf("webkit") != -1,
		mobile = typeof orientation != 'undefined' ? true : false,
		android = ua.indexOf("android") != -1,
		opera = window.opera;

	L.Browser = {
		ie: ie,
		ie6: ie && !window.XMLHttpRequest,

		webkit: webkit,
		webkit3d: webkit && ('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()),

		gecko: ua.indexOf("gecko") != -1,

		opera: opera,

		android: android,
		mobileWebkit: mobile && webkit,
		mobileOpera: mobile && opera,

		mobile: mobile,
		touch: ('ontouchstart' in document.documentElement)
	};
})();<commit_msg>Better touch feature detection<commit_after>(function() {
	var ua = navigator.userAgent.toLowerCase(),
		ie = !!window.ActiveXObject,
		webkit = ua.indexOf("webkit") != -1,
		mobile = typeof orientation != 'undefined' ? true : false,
		android = ua.indexOf("android") != -1,
		opera = window.opera;

	L.Browser = {
		ie: ie,
		ie6: ie && !window.XMLHttpRequest,

		webkit: webkit,
		webkit3d: webkit && ('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()),

		gecko: ua.indexOf("gecko") != -1,

		opera: opera,

		android: android,
		mobileWebkit: mobile && webkit,
		mobileOpera: mobile && opera,

		mobile: mobile,
		touch: (function() {
			var touchSupported = false;;

			// WebKit, etc
			if ('ontouchstart' in document.documentElement) {
				return true;
			}

			// Firefox/Gecko
			var e = document.createElement('div');

			// If no support for basic event stuff, unlikely to have touch support
			if (!e.setAttribute || !e.removeAttribute) {
				return false;
			}

			e.setAttribute('ontouchstart', 'return;');
			if (typeof e['ontouchstart'] == 'function') {
				touchSupported = true;
			}

			e.removeAttribute('ontouchstart');
			e = null;

			return touchSupported;
		})()
	};
})();
<|endoftext|>


<commit_before>
//var fc = $.eventCalendar = { version: "1.0.0" };

$.fn.eventCalendar = function(options) {

  // method calling
  if (typeof options == 'string') {
    var args = Array.prototype.slice.call(arguments, 1);
    var res;
    this.each(function() {
      var calendar = $.data(this, 'eventCalendar');
      if (calendar && $.isFunction(calendar[options])) {
        var r = calendar[options].apply(calendar, args);
        if (res === undefined) {
          res = r;
        }
        if (options == 'destroy') {
          $.removeData(this, 'eventCalendar');
        }
      }
      else alert("no function: "+options)
    });
    if (res !== undefined) {
      return res;
    }
    return this;
  }

  this.each(function(i, _element) {
    var element = $(_element);
    var calendar = new eventCalendar(element, options);
    element.data('eventCalendar', calendar);
  });
  return this;
};

function eventCalendar(element, options, eventSources) {
  var t = this;
  var timer=null;
  t.render=render;
  t.addEventSource=addEventSource;
  t.removeEventSource=removeEventSource;
  t.startdate=new Date();
  t.startdate=t.startdate.withoutTime();

  t.eventSources=new Array();

  function addEventSource(s) {
    t.eventSources.push(s);
    t.render();
  }
  function removeEventSource(s) {
    $.each(t.eventSources, function(k,a) {
      if (a==s) delete t.eventSources[k];
    });
    t.render();
  }

  function render() {
    if (timer!=null) window.clearTimeout(timer);
    timer=window.setTimeout(function() {
      renderCalendar();
      var d2 = new Date();
      var d = new Date(d2.getFullYear()+"");
      var year=d.getFullYear();
      var rows = new Array();

      var allData= new Array();
      $.each(t.eventSources, function(k,s) {
        if (s!=null) {
          $.each(s.events, function(i,event) {
            event.container=s.container;
            event.category_id=s.category_id;
            var i=event.start.getFullYear()+""+event.start.getMonth()+""+event.start.getDate();
            if (allData[i]==null)
              allData[i]=new Array();
            else {

            }
            allData[i].push(event);
          });
        }
      });
      console.log(allData);

      rows.push('
');
      var _filter=filterName.toUpperCase();
      var count=0;
      $.each(churchcore_sortData(allData, "start"), function(k,a) {
        if (a.start>=t.startdate) {
          if ((filterName=="") || (a.title.toUpperCase().indexOf(_filter)>=0)
                || (a.notizen!=null && a.notizen.toUpperCase().indexOf(_filter)>=0)) {
            rows.push('
');

            if (!minical) {
              if ((a.notizen!=null) || (a.link!=null))
                rows.push(''+a.title+'');
              else
                rows.push(a.title);
              rows.push(' ('+a.container.getName(a.category_id)+')

');
              rows.push(a.start.toStringDe(!a.allDay));
              if (a.end!=null) {
                if (a.end.getDate()!=a.start.getDate()) {
                  rows.push(" - "+a.end.toStringDe(!a.allDay));
                }
                else
                  rows.push(" - "+a.end.toStringDeTime());
              }
              rows.push('');
            }
            else {
              rows.push('
');
              rows.push(a.start.toStringDe(!a.allDay));
              if (a.end!=null) {
                if (a.end.getDate()!=a.start.getDate()) {
                  rows.push(" - "+a.end.toStringDe(!a.allDay));
                }
                else
                  rows.push(" - "+a.end.toStringDeTime());
              }
              rows.push('
');
              if (a.link!=null)
                rows.push(''+a.title+'');
              else
                rows.push(a.title);
              if (a.notizen!=null) rows.push("
"+a.notizen.trim(100)+'');

            }

            var notizen="";
            if ((a.notizen!=null) && (a.notizen!="")) {
              notizen=a.notizen.replace(/(http:\/\/\S*)/g, '$1<\/a>');
              notizen=notizen.replace(/(https:\/\/\S*)/g, '$1<\/a>');
              notizen=notizen.replace(/\n/g, '
');
            }

            if ((a.link!=null) && (a.link!="")) {
              if (notizen!="") notizen=notizen+'

';
              notizen=notizen+'Weitere Informationen »';
            }

            rows.push('

'+notizen+'

');
            count++;
            if (count>=max_entries) return false;
          }
        }
      });
      if ((count>max_entries) && (!minical)) rows.push("
...");
      rows.push('
');
      if (count==0) rows.push("Keine Einträge gefunden.");

      $("#calendar").html(rows.join(""));

      $("#calendar a.event").click(function() {
        var id=$(this).attr("data-id");
        var elem=$("#entry"+id);
        elem.animate({ height: 'toggle'}, "fast");
        return false;
      });

      timer=null;
    },50);
  }

  function renderCalendar() {
    $("#minicalendar").datepicker({
      dateFormat: 'dd.mm.yy',
      showButtonPanel: true,
      dayNamesMin: dayNamesMin,
      monthNames: monthNames,
      currentText: "Heute",
      firstDay: 1,
      onSelect : function(dateText, inst) {
        t.startdate=dateText.toDateDe();
        if (embedded)  $("#minicalendar").hide();
        render();
      },
      onChangeMonthYear:function(year, month, inst) {
        var dt = new Date();
        // Wenn es der aktuelle Monat ist, dann gehe auf den heutigen Tag
        if ((dt.getFullYear()==year) && (dt.getMonth()+1==month))
          t.startdate=dt;
        else
          t.startdate=new Date(year, month-1);
        render();
      }

    });
    $("#minicalendar").datepicker($.datepicker.regional['de']);
    //$("#minicalendar").datepicker('setDate', t.startDate.toStringDe());
    shortcut.add("esc", function() {
      $("#minicalendar").hide();
    });

  };

}
<commit_msg>(Cal) Aggregates events in same day and same name to one in MiniCal-Embedded view<commit_after>
//var fc = $.eventCalendar = { version: "1.0.0" };

$.fn.eventCalendar = function(options) {

  // method calling
  if (typeof options == 'string') {
    var args = Array.prototype.slice.call(arguments, 1);
    var res;
    this.each(function() {
      var calendar = $.data(this, 'eventCalendar');
      if (calendar && $.isFunction(calendar[options])) {
        var r = calendar[options].apply(calendar, args);
        if (res === undefined) {
          res = r;
        }
        if (options == 'destroy') {
          $.removeData(this, 'eventCalendar');
        }
      }
      else alert("no function: "+options)
    });
    if (res !== undefined) {
      return res;
    }
    return this;
  }

  this.each(function(i, _element) {
    var element = $(_element);
    var calendar = new eventCalendar(element, options);
    element.data('eventCalendar', calendar);
  });
  return this;
};

function eventCalendar(element, options, eventSources) {
  var t = this;
  var timer=null;
  t.render=render;
  t.addEventSource=addEventSource;
  t.removeEventSource=removeEventSource;
  t.startdate=new Date();
  t.startdate=t.startdate.withoutTime();

  t.eventSources=new Array();

  function addEventSource(s) {
    t.eventSources.push(s);
    t.render();
  }
  function removeEventSource(s) {
    $.each(t.eventSources, function(k,a) {
      if (a==s) delete t.eventSources[k];
    });
    t.render();
  }

  function render() {
    if (timer!=null) window.clearTimeout(timer);
    timer=window.setTimeout(function() {
      renderCalendar();
      var d2 = new Date();
      var d = new Date(d2.getFullYear()+"");
      var year=d.getFullYear();
      var rows = new Array();

      var allData= new Array();
      $.each(t.eventSources, function(k,s) {
        if (s!=null) {
          $.each(s.events, function(i,event) {
            event.container=s.container;
            event.category_id=s.category_id;
            event.compare=s.category_id+"_"+event.start.toStringEn(false)+"_"+event.title;
            var drin=false;
            $.each(allData, function(i,b) {
              if (b.start!=event.start && b.compare==event.compare) {
                drin=true;
                if (b.multi==null) {
                  b.multi=new Array();
                  b.multi.push(b.start);
                }
                b.multi.push(event.start);
                return false;
              }
            });
            if (!drin)
              allData.push(event);
          });
        }
      });

      rows.push('
');
      var _filter=filterName.toUpperCase();
      var count=0;
      $.each(churchcore_sortData(allData, "start"), function(k,a) {
        if (a.start>=t.startdate) {
          if ((filterName=="") || (a.title.toUpperCase().indexOf(_filter)>=0)
                || (a.notizen!=null && a.notizen.toUpperCase().indexOf(_filter)>=0)) {
            rows.push('
');

            if (!minical) {
              if ((a.notizen!=null) || (a.link!=null))
                rows.push(''+a.title+'');
              else
                rows.push(a.title);
              rows.push(' ('+a.container.getName(a.category_id)+')

');
              rows.push(a.start.toStringDe(!a.allDay));
              if (a.end!=null) {
                if (a.end.getDate()!=a.start.getDate()) {
                  rows.push(" - "+a.end.toStringDe(!a.allDay));
                }
                else
                  rows.push(" - "+a.end.toStringDeTime());
              }
              rows.push('');
            }
            // MiniCalender
            else {
              rows.push('
');
              if (a.multi==null) {
                rows.push(a.start.toStringDe(!a.allDay));
                if (a.end!=null) {
                  if (a.end.getDate()!=a.start.getDate()) {
                    rows.push(" - "+a.end.toStringDe(!a.allDay));
                  }
                  else
                    rows.push(" - "+a.end.toStringDeTime());
                }
              }
              else {
                rows.push(a.start.toStringDe()+" - ");
                $.each(churchcore_sortData(a.multi, null, true), function(i,b) {
                  rows.push(b.toStringDeTime()+" | ");
                });
              }
              rows.push('
');
              if (a.link!=null)
                rows.push(''+a.title+'');
              else
                rows.push(a.title);
              if (a.notizen!=null) rows.push("
"+a.notizen.trim(100)+'');

            }

            var notizen="";
            if ((a.notizen!=null) && (a.notizen!="")) {
              notizen=a.notizen.replace(/(http:\/\/\S*)/g, '$1<\/a>');
              notizen=notizen.replace(/(https:\/\/\S*)/g, '$1<\/a>');
              notizen=notizen.replace(/\n/g, '
');
            }

            if ((a.link!=null) && (a.link!="")) {
              if (notizen!="") notizen=notizen+'

';
              notizen=notizen+'Weitere Informationen »';
            }

            rows.push('

'+notizen+'

');
            count++;
            if (count>=max_entries) return false;
          }
        }
      });
      if ((count>max_entries) && (!minical)) rows.push("
...");
      rows.push('
');
      if (count==0) rows.push("Keine Einträge gefunden.");

      $("#calendar").html(rows.join(""));

      $("#calendar a.event").click(function() {
        var id=$(this).attr("data-id");
        var elem=$("#entry"+id);
        elem.animate({ height: 'toggle'}, "fast");
        return false;
      });

      timer=null;
    },50);
  }

  function renderCalendar() {
    $("#minicalendar").datepicker({
      dateFormat: 'dd.mm.yy',
      showButtonPanel: true,
      dayNamesMin: dayNamesMin,
      monthNames: monthNames,
      currentText: "Heute",
      firstDay: 1,
      onSelect : function(dateText, inst) {
        t.startdate=dateText.toDateDe();
        if (embedded)  $("#minicalendar").hide();
        render();
      },
      onChangeMonthYear:function(year, month, inst) {
        var dt = new Date();
        // Wenn es der aktuelle Monat ist, dann gehe auf den heutigen Tag
        if ((dt.getFullYear()==year) && (dt.getMonth()+1==month))
          t.startdate=dt;
        else
          t.startdate=new Date(year, month-1);
        render();
      }

    });
    $("#minicalendar").datepicker($.datepicker.regional['de']);
    //$("#minicalendar").datepicker('setDate', t.startDate.toStringDe());
    shortcut.add("esc", function() {
      $("#minicalendar").hide();
    });

  };

}
<|endoftext|>


<commit_before>
var _ = require('lodash');
var Client = require('../lib/client');

var Utils = function() {};

var die = Utils.die = function(err) {
  if (err) {
    console.error(err);
    process.exit(1);
  }
};

Utils.parseMN = function(MN) {
  if (!MN)
    die('No m-n parameter');
  var mn = MN.split('-');

  var m = parseInt(mn[0]);
  var n = parseInt(mn[1]);

  if (!m || ! n) {
    die('Bad m-n parameter');
  }

  return [m, n];
};

Utils.shortID = function(id) {
  return id.substr(id.length - 4);
};

Utils.getClient = function(args) {
  var storage = new Client.FileStorage({
    filename: args.config
  });
  return new Client({
    storage: storage,
    verbose: args.verbose
  });
}

Utils.findOneTxProposal = function(txps, id) {
  var matches = _.filter(txps, function(tx) {
    return _.endsWith(Utils.shortID(tx.id), id);
  });

  if (!matches.length)
    Utils.die('Could not find TX Proposal:' + id);

  if (matches.length > 1)
    Utils.die('More than one TX Proposals match:' + id + ' : ' + _.map(matches, function(tx) {
      return tx.id;
    }).join(' '));;

  return matches[0];
};

module.exports = Utils;
<commit_msg>reads files from BIT_FILE if none given<commit_after>
var _ = require('lodash');
var Client = require('../lib/client');

var Utils = function() {};

var die = Utils.die = function(err) {
  if (err) {
    console.error(err);
    process.exit(1);
  }
};

Utils.parseMN = function(MN) {
  if (!MN)
    die('No m-n parameter');
  var mn = MN.split('-');

  var m = parseInt(mn[0]);
  var n = parseInt(mn[1]);

  if (!m || ! n) {
    die('Bad m-n parameter');
  }

  return [m, n];
};

Utils.shortID = function(id) {
  return id.substr(id.length - 4);
};

Utils.getClient = function(args) {
  var storage = new Client.FileStorage({
    filename: args.config || process.env['BIT_FILE'],
  });
  return new Client({
    storage: storage,
    verbose: args.verbose
  });
}

Utils.findOneTxProposal = function(txps, id) {
  var matches = _.filter(txps, function(tx) {
    return _.endsWith(Utils.shortID(tx.id), id);
  });

  if (!matches.length)
    Utils.die('Could not find TX Proposal:' + id);

  if (matches.length > 1)
    Utils.die('More than one TX Proposals match:' + id + ' : ' + _.map(matches, function(tx) {
      return tx.id;
    }).join(' '));;

  return matches[0];
};

module.exports = Utils;
<|endoftext|>


<commit_before>import React from 'react';
import MediaUploader from '../MediaUploader';
import FormMessage from '../FormMessage';
import './reportback-uploader.scss';

class ReportbackUploader extends React.Component {
  constructor(props) {
    super(props);

    this.handleOnSubmitForm = this.handleOnSubmitForm.bind(this);
    this.handleOnFileUpload = this.handleOnFileUpload.bind(this);
    this.handleOnCaptionUpdate = this.handleOnCaptionUpdate.bind(this);
    this.handleOnQuantityUpdate = this.handleOnQuantityUpdate.bind(this);
    this.handleOnWhyParticipatedUpdate = this.handleOnWhyParticipatedUpdate.bind(this);

    this.defaultMediaState = {
      file: null,
      filePreviewUrl: null,
      type: null,
      uri: null,
    };

    this.state = {
      media: this.defaultMediaState,
      caption: null,
    };
  }

  handleOnFileUpload(media) {
    this.setState({ media });
  }

  handleOnCaptionUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnQuantityUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnWhyParticipatedUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnSubmitForm(event) {
    event.preventDefault();

    const reportback = {
      media: this.state.media,
      caption: this.caption.value,
      campaignId: this.props.campaignId,
      campaignRunId: this.props.campaignRunId,
      northstarId: this.props.northstarId,
      source: this.props.source,
      status: 'accepted',
    };

    if (this.quantity.value) {
      reportback.impact = this.quantity.value;
    }

    if (this.why_participated.value) {
      reportback.whyParticipated = this.why_participated.value;
    }

    const fileType = reportback.media.file ? reportback.media.file.type : null;

    reportback.media.type = fileType ? fileType.substring(0, fileType.indexOf('/')) : null;

    this.props.submitReportback(reportback);

    // @TODO: only reset form AFTER successful RB submission.
    this.form.reset();
    this.setState({
      media: this.defaultMediaState,
    });
  }

  render() {
    const submissions = this.props.submissions;

    return (

Upload photo

Warning: after uploading a photo, it will automatically be approved. You will still need to add tags in Rogue. No email will trigger telling the user we received their photo.

          { submissions.messaging ? <FormMessage messaging={submissions.messaging} /> : null }

          <form className="reportback-form" onSubmit={this.handleOnSubmitForm} ref={form => (this.form = form)}>
            <MediaUploader label="Add photo here" media={this.state.media} onChange={this.handleOnFileUpload} />

                Add a caption for the photo:
                <input className="text-field" id="caption" name="caption" type="text" onChange={this.handleOnCaptionUpdate} placeholder="60 characters or less" ref={input => (this.caption = input)} />

                Update quantity:
                <input className="text-field" id="quantity" name="quantity" type="text" onChange={this.handleOnQuantityUpdate} placeholder="Quantity # (300)" ref={input => (this.quantity = input)} />

                Update why participated:
                <input className="text-field" id="why_participated" name="why_participated" type="text" onChange={this.handleOnWhyParticipatedUpdate} placeholder="60 characters or less" ref={input => (this.why_participated = input)} />

            <button className="button" disabled={!this.state.media.filePreviewUrl || !this.state.caption} type="submit">Submit a new photo</button>
          </form>

    );
  }
}

ReportbackUploader.defaultProps = {
  noun: {
    plural: 'items',
  },
};

export default ReportbackUploader;
<commit_msg>adds helpers in the box<commit_after>import React from 'react';
import MediaUploader from '../MediaUploader';
import FormMessage from '../FormMessage';
import './reportback-uploader.scss';

class ReportbackUploader extends React.Component {
  constructor(props) {
    super(props);

    this.handleOnSubmitForm = this.handleOnSubmitForm.bind(this);
    this.handleOnFileUpload = this.handleOnFileUpload.bind(this);
    this.handleOnCaptionUpdate = this.handleOnCaptionUpdate.bind(this);
    this.handleOnQuantityUpdate = this.handleOnQuantityUpdate.bind(this);
    this.handleOnWhyParticipatedUpdate = this.handleOnWhyParticipatedUpdate.bind(this);

    this.defaultMediaState = {
      file: null,
      filePreviewUrl: null,
      type: null,
      uri: null,
    };

    this.state = {
      media: this.defaultMediaState,
      caption: null,
    };
  }

  handleOnFileUpload(media) {
    this.setState({ media });
  }

  handleOnCaptionUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnQuantityUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnWhyParticipatedUpdate(event) {
    this.setState({ caption: event.target.value });
  }

  handleOnSubmitForm(event) {
    event.preventDefault();

    const reportback = {
      media: this.state.media,
      caption: this.caption.value,
      campaignId: this.props.campaignId,
      campaignRunId: this.props.campaignRunId,
      northstarId: this.props.northstarId,
      source: this.props.source,
      status: 'accepted',
    };

    if (this.quantity.value) {
      reportback.impact = this.quantity.value;
    }

    if (this.why_participated.value) {
      reportback.whyParticipated = this.why_participated.value;
    }

    const fileType = reportback.media.file ? reportback.media.file.type : null;

    reportback.media.type = fileType ? fileType.substring(0, fileType.indexOf('/')) : null;

    this.props.submitReportback(reportback);

    // @TODO: only reset form AFTER successful RB submission.
    this.form.reset();
    this.setState({
      media: this.defaultMediaState,
    });
  }

  render() {
    const submissions = this.props.submissions;

    return (

Upload photo

Warning: after uploading a photo, it will automatically be approved. You will still need to add tags in Rogue. No email will trigger telling the user we received their photo.

          { submissions.messaging ? <FormMessage messaging={submissions.messaging} /> : null }

          <form className="reportback-form" onSubmit={this.handleOnSubmitForm} ref={form => (this.form = form)}>
            <MediaUploader label="Add photo here" media={this.state.media} onChange={this.handleOnFileUpload} />

                Add a caption for the photo:
                <input className="text-field" id="caption" name="caption" type="text" onChange={this.handleOnCaptionUpdate} placeholder="60 characters or less" ref={input => (this.caption = input)} />

                Update quantity:
                <input className="text-field" id="quantity" name="quantity" type="text" onChange={this.handleOnQuantityUpdate} placeholder="Optional if it already exists" ref={input => (this.quantity = input)} />

                Update why participated:
                <input className="text-field" id="why_participated" name="why_participated" type="text" onChange={this.handleOnWhyParticipatedUpdate} placeholder="Optional if it already exists" ref={input => (this.why_participated = input)} />

            <button className="button" disabled={!this.state.media.filePreviewUrl || !this.state.caption} type="submit">Submit a new photo</button>
          </form>

    );
  }
}

ReportbackUploader.defaultProps = {
  noun: {
    plural: 'items',
  },
};

export default ReportbackUploader;
<|endoftext|>


<commit_before>const path = require('path');

const zcBtnSelector = '.listenEngagement .sc-button-share + button.zc-button-download';
const trackItemSelector = '.listenDetails .trackList__item:last-of-type';

module.exports = {
  '@tags': ['playlist-page'],

  before(browser) {
    browser
      .url('https://soundcloud.com/xtangle/sets/test-playlist')
      .dismissCookiePolicyNotification();
  },

  after(browser) {
    browser.end();
  },

  'Adds a Download button to a SoundCloud playlist page': function (browser) {
    browser
      .waitForElementVisible(zcBtnSelector)
      .assert.containsText(zcBtnSelector, 'Download');
  },

  'Downloads all tracks in the playlist when clicked': function (browser) {
    const playlistDir = path.join(browser.globals.downloadDir, 'xtangle - test playlist');
    // track 1: uses the download_url method, does not have a .mp3 file extension
    // (but should download in mp3 format anyways because of 'always download mp3' option enabled by default),
    // has cover art, and original track title has '__FREE DOWNLOAD__' as a suffix which should be removed
    const track1Path = path.join(playlistDir, 'Rather Be (Marimba Remix).mp3');
    // track 2: uses the stream_url method, does not have cover art
    const track2Path = path.join(playlistDir, '23. M2U - Blythe.mp3');
    // track 3: uses the a1_api method
    const track3Path = path.join(playlistDir, 'Ryuusei.mp3');
    // track 4: uses the stream_url method, has a long track title with weird characters
    // with some that are unsuitable for filenames, has cover art
    const track4Path = path.join(playlistDir,
      'مهرجان _ رب الكون ميزنا بميزه _ حمو بيكا - علي قدوره - نور التوت - توزيع فيجو الدخلاوي 2019.mp3');

    browser
      .click(zcBtnSelector)
      .assert.fileDownloaded(track1Path)
      .verify.fileHasSize(track1Path, 523662)
      .assert.fileDownloaded(track2Path)
      .verify.fileHasSize(track2Path, 2189492)
      .assert.fileDownloaded(track3Path)
      .verify.fileHasSize(track3Path, 5099728)
      .assert.fileDownloaded(track4Path)
      .verify.fileHasSize(track4Path, 5551831);
  },

  'Adds a Download button for every item in the track list': function (browser) {
    browser
      .elements('css selector', '.listenDetails .trackList__item'
        + ' .sc-button-share + button.zc-button-download', (result) => {
        browser.assert.strictEqual(result.value.length, 4,
          'Should add a download button for every track item');
      })
      .assert.hidden(`${trackItemSelector} button.zc-button-download`, 'Download button is hidden on a track item')
      .moveToElement(trackItemSelector, 100, 20)
      .assert.visible(`${trackItemSelector} button.zc-button-download`,
        'Download button is visible when hovering over a track item');
  },

  'Downloads the track when a Download button in the track list is clicked': function (browser) {
    const trackPath = path.join(browser.globals.downloadDir,
      'مهرجان _ رب الكون ميزنا بميزه _ حمو بيكا - علي قدوره - نور التوت - توزيع فيجو الدخلاوي 2019.mp3');
    browser
      .click(`${trackItemSelector} button.zc-button-download`)
      .assert.fileDownloaded(trackPath)
      .verify.fileHasSize(trackPath, 5551832); // not sure where the extra byte comes from
  },
};
<commit_msg>fix(e2e): remove deleted track in playlist (#8)<commit_after>const path = require('path');

const zcBtnSelector = '.listenEngagement .sc-button-share + button.zc-button-download';
const trackItemSelector = '.listenDetails .trackList__item:last-of-type';

module.exports = {
  '@tags': ['playlist-page'],

  before(browser) {
    browser
      .url('https://soundcloud.com/xtangle/sets/test-playlist')
      .dismissCookiePolicyNotification();
  },

  after(browser) {
    browser.end();
  },

  'Adds a Download button to a SoundCloud playlist page': function (browser) {
    browser
      .waitForElementVisible(zcBtnSelector)
      .assert.containsText(zcBtnSelector, 'Download');
  },

  'Downloads all tracks in the playlist when clicked': function (browser) {
    const playlistDir = path.join(browser.globals.downloadDir, 'xtangle - test playlist');
    // track 1: uses the download_url method, does not have a .mp3 file extension
    // (but should download in mp3 format anyways because of 'always download mp3' option enabled by default),
    // has cover art, and original track title has '__FREE DOWNLOAD__' as a suffix which should be removed
    const track1Path = path.join(playlistDir, 'Rather Be (Marimba Remix).mp3');
    // track 2: uses the stream_url method, does not have cover art
    const track2Path = path.join(playlistDir, '23. M2U - Blythe.mp3');
    // track 3: uses the a1_api method
    const track3Path = path.join(playlistDir, 'Ryuusei.mp3');

    browser
      .click(zcBtnSelector)
      .assert.fileDownloaded(track1Path)
      .verify.fileHasSize(track1Path, 523662)
      .assert.fileDownloaded(track2Path)
      .verify.fileHasSize(track2Path, 2189492)
      .assert.fileDownloaded(track3Path)
      .verify.fileHasSize(track3Path, 5099728);
  },

  'Adds a Download button for every item in the track list': function (browser) {
    browser
      .elements('css selector', '.listenDetails .trackList__item'
        + ' .sc-button-share + button.zc-button-download', (result) => {
        browser.assert.strictEqual(result.value.length, 3,
          'Should add a download button for every track item');
      })
      .assert.hidden(`${trackItemSelector} button.zc-button-download`, 'Download button is hidden on a track item')
      .moveToElement(trackItemSelector, 100, 20)
      .assert.visible(`${trackItemSelector} button.zc-button-download`,
        'Download button is visible when hovering over a track item');
  },

  'Downloads the track when a Download button in the track list is clicked': function (browser) {
    const trackPath = path.join(browser.globals.downloadDir, 'Ryuusei.mp3');
    browser
      .click(`${trackItemSelector} button.zc-button-download`)
      .assert.fileDownloaded(trackPath)
      .verify.fileHasSize(trackPath, 5099729); // not sure where the extra byte comes from
  },
};
<|endoftext|>


<commit_before>if("document"in self){if(!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g"))){(function(t){"use strict";if(!("Element"in t))return;var e="classList",i="prototype",n=t.Element[i],s=Object,r=String[i].trim||function(){return this.replace(/^\s+|\s+$/g,"")},a=Array[i].indexOf||function(t){var e=0,i=this.length;for(;e<i;e++){if(e in this&&this[e]===t){return e}}return-1},o=function(t,e){this.name=t;this.code=DOMException[t];this.message=e},l=function(t,e){if(e===""){throw new o("SYNTAX_ERR","An invalid or illegal string was specified")}if(/\s/.test(e)){throw new o("INVALID_CHARACTER_ERR","String contains an invalid character")}return a.call(t,e)},c=function(t){var e=r.call(t.getAttribute("class")||""),i=e?e.split(/\s+/):[],n=0,s=i.length;for(;n<s;n++){this.push(i[n])}this._updateClassName=function(){t.setAttribute("class",this.toString())}},u=c[i]=[],f=function(){return new c(this)};o[i]=Error[i];u.item=function(t){return this[t]||null};u.contains=function(t){t+="";return l(this,t)!==-1};u.add=function(){var t=arguments,e=0,i=t.length,n,s=false;do{n=t[e]+"";if(l(this,n)===-1){this.push(n);s=true}}while(++e<i);if(s){this._updateClassName()}};u.remove=function(){var t=arguments,e=0,i=t.length,n,s=false,r;do{n=t[e]+"";r=l(this,n);while(r!==-1){this.splice(r,1);s=true;r=l(this,n)}}while(++e<i);if(s){this._updateClassName()}};u.toggle=function(t,e){t+="";var i=this.contains(t),n=i?e!==true&&"remove":e!==false&&"add";if(n){this[n](t)}if(e===true||e===false){return e}else{return!i}};u.toString=function(){return this.join(" ")};if(s.defineProperty){var h={get:f,enumerable:true,configurable:true};try{s.defineProperty(n,e,h)}catch(d){if(d.number===-2146823252){h.enumerable=false;s.defineProperty(n,e,h)}}}else if(s[i].__defineGetter__){n.__defineGetter__(e,f)}})(self)}else{(function(){"use strict";var t=document.createElement("_");t.classList.add("c1","c2");if(!t.classList.contains("c2")){var e=function(t){var e=DOMTokenList.prototype[t];DOMTokenList.prototype[t]=function(t){var i,n=arguments.length;for(i=0;i<n;i++){t=arguments[i];e.call(this,t)}}};e("add");e("remove")}t.classList.toggle("c3",false);if(t.classList.contains("c3")){var i=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(t,e){if(1 in arguments&&!this.contains(t)===!e){return e}else{return i.call(this,t)}}}t=null})()}}
<commit_msg>Remove generated files<commit_after><|endoftext|>


<commit_before>angular.module("ngGapi").
	provider('GapiClient', {

		clients: {},

		gapiDeferred: angular.injector(['ng']).get('$q').defer(),
		authDeferred: null,

		// FIXME: Instantiated on service $get. How to get an instance in the provider config function?
		_$rootScope: null,

		load: function(name,version,root){

			var thisProvider = this;

			if (!thisProvider.clients[name]) {

				var clientDeferred = thisProvider._get$q().defer();

				thisProvider.clients[name] = thisProvider._buildClientDraft(name,clientDeferred.promise);
				thisProvider.clients[name].$promise.then(function(){
					angular.extend(thisProvider.clients[name],thisProvider._getGapi().gapi().client[name]);
				});

				// when gapi is ready, load client
				thisProvider._getGapi().gapi$promise().then(function(){
					thisProvider._getGapi().gapi().client.load(name,version,function(){
						clientDeferred.resolve(thisProvider.clients[name]);
					},root);
				});

			}
			return thisProvider.clients[name];
		},

		_get$q: function(){
			return angular.injector(['ng']).get('$q');
		},

		_getGapi: function(){
			return angular.injector(['ngGapi']).get('Gapi');
		},

		_buildClientDraft: function(name,clientPromise){

			var thisProvider = this;

			return{
				exec: function(methodName,payload){

					function traverse(o,path) {
						var pieces = path.split(".");
						for (var i=0; i<pieces.length; i++)
							o = o[pieces[i]];
						return o;
					}

					var execResultDeferred = thisProvider._get$q().defer();

					var execStartPromise = thisProvider._get$q().all( thisProvider._getGapi().auth$promise() ? [clientPromise,thisProvider._getGapi().auth$promise()] : [clientPromise] );

					execStartPromise.then(function(){
						var client = thisProvider.clients[name];
						var method = traverse(client,methodName);
						var execCallback = function(response) {
							if (response && response.error)
								 execResultDeferred.reject(response.error);
							 else
								 execResultDeferred.resolve(response);
						}
						// finally, exec method
						method(payload).execute(execCallback);
					});

					var execResult = thisProvider._buildExecResultDraft(payload,execResultDeferred.promise);
					execResult.$promise.then(function(result){
						thisProvider._$rootScope.$apply(function(){
							angular.extend(execResult,result);
						});
					});

					return execResult;
				},
				$promise: clientPromise
			};
		},

		_buildExecResultDraft: function(requestPayload,execResultPromise){
			var payload = !requestPayload || typeof requestPayload !== "object" ? {} : requestPayload;
			payload.$promise = execResultPromise;
			return payload
		},

		$get: function($rootScope) {

			var thisProvider = this;

			// FIXME: workaround to get and instance of $rootScope in the provider config function
			thisProvider._$rootScope = $rootScope;

			return {
				gapi: function(){return thisProvider._getGapi().gapi();},
				client: function(name,version,root){return thisProvider.load(name,version,root);}
			};
		}
	});<commit_msg>added  and / in gapi client responses<commit_after>angular.module("ngGapi").
	provider('GapiClient', {

		clients: {},

		gapiDeferred: angular.injector(['ng']).get('$q').defer(),
		authDeferred: null,

		// FIXME: Instantiated on service $get. How to get an instance in the provider config function?
		_$rootScope: null,

		load: function(name,version,root){

			var thisProvider = this;

			if (!thisProvider.clients[name]) {

				var clientDeferred = thisProvider._get$q().defer();

				thisProvider.clients[name] = thisProvider._buildClientDraft(name,clientDeferred.promise);
				thisProvider.clients[name].$promise.then(function(){
					angular.extend(thisProvider.clients[name],thisProvider._getGapi().gapi().client[name]);
				});

				// when gapi is ready, load client
				thisProvider._getGapi().gapi$promise().then(function(){
					thisProvider._getGapi().gapi().client.load(name,version,function(){
						clientDeferred.resolve(thisProvider.clients[name]);
					},root);
				});

			}
			return thisProvider.clients[name];
		},

		_get$q: function(){
			return angular.injector(['ng']).get('$q');
		},

		_getGapi: function(){
			return angular.injector(['ngGapi']).get('Gapi');
		},

		_buildClientDraft: function(name,clientPromise){

			var thisProvider = this;

			return{
				exec: function(methodName,payload){

					function traverse(o,path) {
						var pieces = path.split(".");
						for (var i=0; i<pieces.length; i++)
							o = o[pieces[i]];
						return o;
					}

					var execResultDeferred = thisProvider._get$q().defer();
					execResultDeferred.promise.then(function(){
						execResultDeferred.promise.$resolved = true;
						execResultDeferred.promise.$sucess = true;
					},function(){
						execResultDeferred.promise.$resolved = true;
						execResultDeferred.promise.$error = true;
					})

					var execStartPromise = thisProvider._get$q().all( thisProvider._getGapi().auth$promise() ? [clientPromise,thisProvider._getGapi().auth$promise()] : [clientPromise] );

					execStartPromise.then(function(){
						var client = thisProvider.clients[name];
						var method = traverse(client,methodName);
						var execCallback = function(response) {
							if (response && response.error)
								 execResultDeferred.reject(response.error);
							 else
								 execResultDeferred.resolve(response);
						}
						// finally, exec method
						method(payload).execute(execCallback);
					});

					var execResult = thisProvider._buildExecResultDraft(payload,execResultDeferred.promise);
					execResult.$promise.then(function(result){
						thisProvider._$rootScope.$apply(function(){
							angular.extend(execResult,result);
						});
					});

					return execResult;
				},
				$promise: clientPromise
			};
		},

		_buildExecResultDraft: function(requestPayload,execResultPromise){
			var payload = !requestPayload || typeof requestPayload !== "object" ? {} : requestPayload;
			payload.$promise = execResultPromise;
			return payload
		},

		$get: function($rootScope) {

			var thisProvider = this;

			// FIXME: workaround to get and instance of $rootScope in the provider config function
			thisProvider._$rootScope = $rootScope;

			return {
				gapi: function(){return thisProvider._getGapi().gapi();},
				client: function(name,version,root){return thisProvider.load(name,version,root);}
			};
		}
	});<|endoftext|>


<commit_before>(function () {

    var allSelect = document.querySelectorAll('.select');
    var allToDisplay = document.querySelectorAll('.toDisplay');
    var allToDisplayBig = document.querySelectorAll('.toDisplayBig');

    var removeAllOptions = function () {
        for (var index = 0; index < allToDisplay.length; index++) {
            var a = allToDisplay[index];
            if (a.style.display == 'block') {
                a.style.display = 'none';
            }
        }
        for (var index = 0; index < allToDisplayBig.length; index++) {
            var b = allToDisplayBig[index];
            if (b.style.display == 'block') {
                b.style.display = 'none';
            }
        }
    }

    // Remove displayed options
    window.addEventListener('click', function () {
        removeAllOptions();
    });

    // Handle click on select elements
    for (var index = 0; index < allSelect.length; index++) {
        var s = allSelect[index];
        // Get child called to display
        var displayItems = function (e) {
            var toDisplay = this.querySelector('.toDisplay');
            if (toDisplay) {
                if (toDisplay.style.display == 'block') {
                    toDisplay.style.display = 'none';
                } else {
                    removeAllOptions();
                    toDisplay.style.display = 'block';
                }
            }
            toDisplay = this.querySelector('.toDisplayBig');
            if (toDisplay) {
                if (toDisplay.style.display == 'block') {
                    toDisplay.style.display = 'none';
                } else {
                    removeAllOptions();
                    toDisplay.style.display = 'block';
                }
            }
            e.preventDefault();
            e.stopPropagation();
        }
        s.addEventListener('click', displayItems);

        // Handle mouseover on subSelect
        var allSubItems = document.querySelectorAll('.toDisplaySub');
        var removeAllSubItems = function () {
            for (var index = 0; index < allSubItems.length; index++) {
                var tds = allSubItems[index];
                if (tds.style.display == 'block') {
                    tds.style.display = 'none';
                }
            }
        }

        var allSubSelect = document.querySelectorAll('.subSelect');
        for (var index = 0; index < allSubSelect.length; index++) {
            var ss = allSubSelect[index];
            ss.addEventListener('mouseenter', function () {
                var toDisplay = this.querySelector('.toDisplaySub');
                if (toDisplay) {
                    if (toDisplay.style.display == 'block') {
                        toDisplay.style.display = 'none';
                    } else {
                        removeAllSubItems();
                        toDisplay.style.display = 'block';
                    }
                }
            })

        }
    }

    document.querySelector('#safemodeToggle').addEventListener('click', function () {
        this.classList.toggle('checked');
        if (this.classList.contains('checked')) {
            this.innerHTML = 'Safe mode ';
        } else {
            this.innerHTML = 'Safe mode ';
        }
    })
})();<commit_msg>PG - fixed bug on select<commit_after>(function () {

    var allSelect = document.querySelectorAll('.select');
    var allToDisplay = document.querySelectorAll('.toDisplay');
    var allToDisplayBig = document.querySelectorAll('.toDisplayBig');

    var removeAllOptions = function () {
        for (var index = 0; index < allToDisplay.length; index++) {
            var a = allToDisplay[index];
            if (a.style.display == 'block') {
                a.style.display = 'none';
            }
        }
        for (var index = 0; index < allToDisplayBig.length; index++) {
            var b = allToDisplayBig[index];
            if (b.style.display == 'block') {
                b.style.display = 'none';
            }
        }
    }

    // Remove displayed options
    window.addEventListener('click', function () {
        removeAllOptions();
    });

    // Handle click on select elements
    for (var index = 0; index < allSelect.length; index++) {
        var s = allSelect[index];
        // Get child called to display
        var displayItems = function (e) {
            var toDisplay = this.querySelector('.toDisplay');
            if (toDisplay) {
                if (toDisplay.style.display == 'block') {
                    toDisplay.style.display = 'none';
                } else {
                    removeAllOptions();
                    toDisplay.style.display = 'block';
                }
            }
            toDisplay = this.querySelector('.toDisplayBig');
            if (toDisplay) {
                if (toDisplay.style.display == 'block') {
                    toDisplay.style.display = 'none';
                } else {
                    removeAllOptions();
                    toDisplay.style.display = 'block';
                }
            }
            e.preventDefault();
            e.stopPropagation();
        }
        s.addEventListener('click', displayItems);
    }

    // Handle mouseover on subSelect
    var allSubItems = document.querySelectorAll('.toDisplaySub');
    var removeAllSubItems = function () {
        for (var index = 0; index < allSubItems.length; index++) {
            var tds = allSubItems[index];
            if (tds.style.display == 'block') {
                tds.style.display = 'none';
            }
        }
    }

    var allSubSelect = document.querySelectorAll('.subSelect');
    for (var index = 0; index < allSubSelect.length; index++) {
        var ss = allSubSelect[index];
        ss.addEventListener('mouseenter', function () {
            var toDisplay = this.querySelector('.toDisplaySub');
            if (toDisplay) {
                if (toDisplay.style.display == 'block') {
                    toDisplay.style.display = 'none';
                } else {
                    removeAllSubItems();
                    toDisplay.style.display = 'block';
                }
            }
        })

    }

    document.querySelector('#safemodeToggle').addEventListener('click', function () {
        this.classList.toggle('checked');
        if (this.classList.contains('checked')) {
            this.innerHTML = 'Safe mode ';
        } else {
            this.innerHTML = 'Safe mode ';
        }
    })
})();<|endoftext|>


<commit_before>app.directive('navbarDirective', function() {
    return {
        templateUrl: '_core/directives/navbar/navbarDirective.html',
        transclude: true,
        replace: true,
        link: function(scope, elm, attr) {

        }
    };
});<commit_msg>Dummy<commit_after>app.directive('navbarDirective', function() {
    return {
        templateUrl: '_core/directives/navbar/navbarDirective.html',
        transclude: true,
        replace: true
    };
});<|endoftext|>


<commit_before>define('regs-fixed-el-view', ['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
    'use strict';
    var RegsFixedElView = Backbone.View.extend({
        expand: function() {
            this.$el.addClass('fixed');
        },

        contract: function() {
            this.$el.removeClass('fixed');
        }
    });

    return RegsFixedElView;
});
<commit_msg>cleanup<commit_after><|endoftext|>