<commit_before>var tape = {
    head_at: 0,
    contents: [],

    load: function(contents) {
        contents = contents.replace(/\s/, "_");
        this.contents = contents.split("");
        this.seek(0);
    },

    write: function(value) {
        this.extend_to(this.head_at);
        this.contents[this.head_at] = value;
        this.render();
    },

    read: function() {
        this.extend_to(this.head_at);
        var value = this.contents[this.head_at] || "_";
        return value;
    },

    left: function() {
        this.head_at--;
        this.extend_to(this.head_at);
        this.render();
    },

    right: function() {
        this.head_at++;
        this.extend_to(this.head_at);
        this.render();
    },

    seek: function(position) {
        this.head_at = position;
        this.render();
    },

    render: function() {
        var cells = [];
        for (var i = 0; i < this.contents.length; i++) {
            var cell = $("");
            cell.text(this.contents[i]);
            if (this.head_at === i) {
                cell.addClass("head");
            }
            cells.push(cell);
        }
        $("#tape").children().remove();
        $("#tape").append(cells);
    },

    /**
     * Extend the size of the tape to ensure that the head can point at index
     **/
    extend_to: function(index) {
        if (index === 0 && this.contents.length === 0) {
            this.contents.push("_");
            return;
        }
        while (index < 0) {
            this.contents.splice(0, 0, '_');
            index++;
            this.head_at++;
        }
        while (index >= this.contents.length) {
            this.contents.push('_');
        }
    }
};

var machine = {
    pause: true,
    states: {},
    start_state: null,
    halting_states: [],
    name: null,
    current_state: null,
    current_state_name: null,
    step: 0,

    play: function() {
        machine.transition(tape.read());
        setTimeout(function() {
            if(!machine.pause) {
                machine.play();
            }
        }, parseInt($('.speed select').val()));
    },

    hard_reset: function() {
        this.states = {};
        this.start_state = null;
        this.halting_states = [];
        this.name = null;
        this.soft_reset();
    },

    soft_reset: function() {
        this.current_state = this.states[this.start_state];
        this.current_state_name = this.start_state;
        this.step = 0;
    },

    compile: function(code) {
        this.hard_reset();
        var lines = code.split(/\r\n|\r|\n|\n\r/);
        for (var i = 0; i < lines.length; i++) {
            var raw_line = lines[i];
            var line = raw_line.replace(/\s+/g, '');
            if (line.indexOf('//') === 0 || line.length === 0) {
                continue;
            }
            if (line.indexOf('start:') === 0) {
                this.start_state = line.split(":").pop();
            } else if (line.indexOf('halt:') === 0){
                this.halting_states = line.split(":").pop().split(",");
            } else if (line.indexOf('name:') === 0) {
                this.name = raw_line.split(':').slice(1).join(":").trim();
            } else if (line.indexOf('description:') === 0) {
                this.description = raw_line.split(':').slice(1).join(":").trim();
            } else {
                var transition = line.split(","),
                    from = transition[0],
                    read = transition[1],
                    to = transition[2],
                    write = transition[3],
                    move = transition[4];
                if (!this.states[from]) {
                    this.states[from] = {};
                }
                if (!this.states[to]) {
                    this.states[to] = {};
                }
                this.states[from][read] = {write: write, state: to, move: move};
            }
            this.current_state_name = this.start_state;
            this.current_state = this.states[this.start_state];
        }
        this.render();
    },

    transition: function(input) {
        if (this.halting_states.indexOf(this.current_state_name) !== -1) {
            // Don't do anything, we're in a halting state, there's nowhere to go
            return;
        }
        var instructions = this.current_state[input];
        if (!instructions) {
            messages.error("Error no transition from " + this.current_state_name + " reading " + input);
        } else {
            this.current_state_name = instructions.state;
            this.current_state = this.states[instructions.state];
            tape.write(instructions.write);
            switch (instructions.move) {
                case ">":
                    tape.right();
                    break;
                case "<":
                    tape.left();
                    break;
            }
            this.step++;
            this.render();
        }
    },

    render: function() {
        $("#machine-name").text(this.name || "Unnamed");
        $("#machine-description").text(this.description || "");
        $("#machine-state").text(this.current_state_name || "No state");
        $("#machine-step").text(this.step);
    }
};

$(document).ready(function() {
    $('.ui.dropdown.speed').dropdown();

    $('.action.load-tape').click(function() {
        tape.load($("#tape-input").val());
        machine.soft_reset();
        machine.render();
    });

    $('#play').click(function() {
        machine.pause = false;
        machine.play();
    });

    $('#pause').click(function() {
        machine.pause = true;
    });

    $('#stop').click(function() {
        if (!machine.pause) {
            machine.pause = true;
        } else {
            tape.load("");
            machine.soft_reset();
            machine.render();
        }
    });

    $('#step').click(function() {
        machine.transition(tape.read());
    });
});
<commit_msg>midhead function<commit_after>var tape = {
    head_at: 0,
    contents: [],

    load: function(contents) {
        contents = contents.replace(/\s/, "_");
        this.contents = contents.split("");
        this.seek(0);
    },

    write: function(value) {
        this.extend_to(this.head_at);
        this.contents[this.head_at] = value;
        this.render();
    },

    read: function() {
        this.extend_to(this.head_at);
        var value = this.contents[this.head_at] || "_";
        return value;
    },

    left: function() {
        this.head_at--;
        this.extend_to(this.head_at);
        this.render();
    },

    right: function() {
        this.head_at++;
        this.extend_to(this.head_at);
        this.render();
    },

    seek: function(position) {
        this.head_at = position;
        this.render();
    },

    render: function() {
        var cells = [];
        for (var i = 0; i < this.contents.length; i++) {
            var cell = $("");
            cell.text(this.contents[i]);
            if (this.head_at === i) {
                cell.addClass("head");
            }
            cells.push(cell);
        }
        $("#tape").children().remove();
        $("#tape").append(cells);
    },

    midhead: function(index) {
		returned = ("head_at").css (position);
		windwidth = (window.width / 2);
		if returned > windwidth {
			window.scrollBy(returned - windwidth, 0);
		} else {
			window.scrollBy(returned - windwidth, 0);
		}
	},
    /**
     * Extend the size of the tape to ensure that the head can point at index
     **/
    extend_to: function(index) {
        if (index === 0 && this.contents.length === 0) {
            this.contents.push("_");
            return;
        }
        while (index < 0) {
            this.contents.splice(0, 0, '_');
            index++;
            this.head_at++;
        }
        while (index >= this.contents.length) {
            this.contents.push('_');
        }
    }
};

var machine = {
    pause: true,
    states: {},
    start_state: null,
    halting_states: [],
    name: null,
    current_state: null,
    current_state_name: null,
    step: 0,

    play: function() {
        machine.transition(tape.read());
        setTimeout(function() {
            if(!machine.pause) {
                machine.play();
            }
        }, parseInt($('.speed select').val()));
    },

    hard_reset: function() {
        this.states = {};
        this.start_state = null;
        this.halting_states = [];
        this.name = null;
        this.soft_reset();
    },

    soft_reset: function() {
        this.current_state = this.states[this.start_state];
        this.current_state_name = this.start_state;
        this.step = 0;
    },

    compile: function(code) {
        this.hard_reset();
        var lines = code.split(/\r\n|\r|\n|\n\r/);
        for (var i = 0; i < lines.length; i++) {
            var raw_line = lines[i];
            var line = raw_line.replace(/\s+/g, '');
            if (line.indexOf('//') === 0 || line.length === 0) {
                continue;
            }
            if (line.indexOf('start:') === 0) {
                this.start_state = line.split(":").pop();
            } else if (line.indexOf('halt:') === 0){
                this.halting_states = line.split(":").pop().split(",");
            } else if (line.indexOf('name:') === 0) {
                this.name = raw_line.split(':').slice(1).join(":").trim();
            } else if (line.indexOf('description:') === 0) {
                this.description = raw_line.split(':').slice(1).join(":").trim();
            } else {
                var transition = line.split(","),
                    from = transition[0],
                    read = transition[1],
                    to = transition[2],
                    write = transition[3],
                    move = transition[4];
                if (!this.states[from]) {
                    this.states[from] = {};
                }
                if (!this.states[to]) {
                    this.states[to] = {};
                }
                this.states[from][read] = {write: write, state: to, move: move};
            }
            this.current_state_name = this.start_state;
            this.current_state = this.states[this.start_state];
        }
        this.render();
    },

    transition: function(input) {
        if (this.halting_states.indexOf(this.current_state_name) !== -1) {
            // Don't do anything, we're in a halting state, there's nowhere to go
            return;
        }
        var instructions = this.current_state[input];
        if (!instructions) {
            messages.error("Error no transition from " + this.current_state_name + " reading " + input);
        } else {
            this.current_state_name = instructions.state;
            this.current_state = this.states[instructions.state];
            tape.write(instructions.write);
            switch (instructions.move) {
                case ">":
                    tape.right();
                    break;
                case "<":
                    tape.left();
                    break;
            }
            this.step++;
            this.render();
        }
    },

    render: function() {
        $("#machine-name").text(this.name || "Unnamed");
        $("#machine-description").text(this.description || "");
        $("#machine-state").text(this.current_state_name || "No state");
        $("#machine-step").text(this.step);
    }
};

$(document).ready(function() {
    $('.ui.dropdown.speed').dropdown();

    $('.action.load-tape').click(function() {
        tape.load($("#tape-input").val());
        machine.soft_reset();
        machine.render();
    });

    $('#play').click(function() {
        machine.pause = false;
        machine.play();
    });

    $('#pause').click(function() {
        machine.pause = true;
    });

    $('#stop').click(function() {
        if (!machine.pause) {
            machine.pause = true;
        } else {
            tape.load("");
            machine.soft_reset();
            machine.render();
        }
    });

    $('#step').click(function() {
        machine.transition(tape.read());
    });
});
<|endoftext|>


<commit_before>/**
 * Created by sens on 2017/2/17.
 */
var addEvent = (function(window, undefined) {
    var _eventCompat = function(event) {
        var type = event.type;
        if (type == 'DOMMouseScroll' || type == 'mousewheel') {
            event.delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
        }
        //alert(event.delta);
        if (event.srcElement && !event.target) {
            event.target = event.srcElement;
        }
        if (!event.preventDefault && event.returnValue !== undefined) {
            event.preventDefault = function() {
                event.returnValue = false;
            };
        }
        /*
         ......其他一些兼容性处理 */
        return event;
    };
    if (window.addEventListener) {
        return function(el, type, fn, capture) {
            if (type === "mousewheel" && document.mozHidden !== undefined) {
                type = "DOMMouseScroll";
            }
            el.addEventListener(type, function(event) {
                fn.call(this, _eventCompat(event));
            }, capture || false);
        }
    } else if (window.attachEvent) {
        return function(el, type, fn) {
            el.attachEvent("on" + type, function(event) {
                event = event || window.event;
                fn.call(el, _eventCompat(event));
            });
        }
    }
    return function() {};
})(window);

var makeSky = (function (doc, window, addEvent) {
    var REQ = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
    var cvs = doc.getElementById('wrapper-cvs');
    var ctx = cvs.getContext('2d');
    cvs.width = doc.documentElement.clientWidth;
    cvs.height = doc.documentElement.clientHeight;

    var stageBack = doc.getElementById('j-stage-block-back'),
        hue = 217,
        stars = [],
        count = 0,
        far = 0,
        maxStars = 500,
        canvas2 = document.createElement('canvas'),
        ctx2 = canvas2.getContext('2d');

    canvas2.width = 100;
    canvas2.height = 100;
    var half = canvas2.width / 2;
    var gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);
    var flagRestartStar = false;
    var flagRestartSky = false;

    gradient2.addColorStop(0.025, '#CCC');
    gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
    gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
    gradient2.addColorStop(1, 'transparent');

    ctx2.fillStyle = gradient2;
    ctx2.beginPath();
    ctx2.arc(half, half, half, 0, Math.PI * 2);
    ctx2.fill();

    function random(min, max) {
        if (arguments.length < 2) {
            max = min;
            min = 0;
        }

        if (min > max) {
            var hold = max;
            max = min;
            min = hold;
        }

        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    function maxOrbit(x, y) {
        var max = Math.max(x, y),
            diameter = Math.round(Math.sqrt(max * max + max * max));
        return diameter / 2;
    }

    Star = function (w,h) {
        this.orbitRadius = random(maxOrbit(w, h));
        this.radius = random(60, this.orbitRadius) / 8;
        this.orbitX = w / 2;
        this.orbitY = h / 2;
        this.timePassed = random(0, maxStars);
        this.speed = random(this.orbitRadius) / 50000;
        this.alpha = random(2, 10) / 10;

        count++;
        stars[count] = this;
    };

    Star.prototype.draw = function () {
        var x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
            y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
            twinkle = random(10);

        if (twinkle === 1 && this.alpha > 0) {
            this.alpha -= 0.05;
        } else if (twinkle === 2 && this.alpha < 1) {
            this.alpha += 0.05;
        }

        ctx.globalAlpha = this.alpha;
        ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
        if (mouseAniSpeed > minAniSpeed) {
            this.timePassed += this.speed * mouseAniSpeed * ratioAniSpeed;
        }
        else {
            this.timePassed += this.speed;
        }
    };

    var isMouseWheel = false;
    var synMouseWheel;
    var minAniSpeed = 0.2;
    var ratioAniSpeed = 1 / minAniSpeed;
    var maxAniSpeed = 1;
    var mouseAniSpeed = minAniSpeed;

    function animation(w,h) {
        if(flagRestartStar) {
            flagRestartStar = false;
            return;
        }
        ctx.globalCompositeOperation = 'source-over';
        ctx.globalAlpha = 0.3;

        ctx.fillRect(0, 0, w, h);

        ctx.globalCompositeOperation = 'lighter';
        for (var i = 1, l = stars.length; i < l; i++) {
            stars[i].draw();
        }

        console.log(w,h);
        REQ(function () {
            animation(w,h);
        });
    }

    function skyAnimation() {
        if(flagRestartSky) {
            flagRestartSky = false;
            return;
        }
        if (far < 800) {
            if (isMouseWheel) {
                mouseAniSpeed = maxAniSpeed;
                far += maxAniSpeed;
            }
            else {
                mouseAniSpeed = mouseAniSpeed > minAniSpeed ? mouseAniSpeed - 0.01 : minAniSpeed;
                far += mouseAniSpeed;
            }
            stageBack.style.transform = 'translate3d(0,0,' + far + 'px)';
            REQ(skyAnimation);
        }
    }

    function makeStars(w,h) {
        count = 0;
        for (var i = 0; i < maxStars; i++) {
            new Star(w,h);
        }
    }

    function init() {
        addEvent(doc.body, "mousewheel", function (event) {
            if (event.delta < 0 && far < 800) {
                clearTimeout(synMouseWheel);
                synMouseWheel = setTimeout(function () {
                    isMouseWheel = false;
                    mouseAniSpeed = maxAniSpeed;
                }, 500);
                if (isMouseWheel) {
                    return;
                }
                isMouseWheel = true;
            }
        });
        cvs.width = doc.documentElement.clientWidth;
        cvs.height = doc.documentElement.clientHeight;
        makeStars(cvs.width,cvs.height);
        REQ(function () {
            animation(cvs.width, cvs.height);
            skyAnimation();
        })
    }
    function restart() {
        flagRestartStar = true;
        flagRestartSky = true;
        cvs.width = doc.documentElement.clientWidth;
        cvs.height = doc.documentElement.clientHeight;
        makeStars(cvs.width, cvs.height);
        REQ(function () {
            animation(cvs.width, cvs.height);
            skyAnimation();
        })
    }

    return {
        init: init,
        restart: restart
    };

})(document, window, addEvent);<commit_msg>修复req传w、h不生效的问题，深坑<commit_after>/**
 * Created by sens on 2017/2/17.
 */
var addEvent = (function(window, undefined) {
    var _eventCompat = function(event) {
        var type = event.type;
        if (type == 'DOMMouseScroll' || type == 'mousewheel') {
            event.delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
        }
        //alert(event.delta);
        if (event.srcElement && !event.target) {
            event.target = event.srcElement;
        }
        if (!event.preventDefault && event.returnValue !== undefined) {
            event.preventDefault = function() {
                event.returnValue = false;
            };
        }
        /*
         ......其他一些兼容性处理 */
        return event;
    };
    if (window.addEventListener) {
        return function(el, type, fn, capture) {
            if (type === "mousewheel" && document.mozHidden !== undefined) {
                type = "DOMMouseScroll";
            }
            el.addEventListener(type, function(event) {
                fn.call(this, _eventCompat(event));
            }, capture || false);
        }
    } else if (window.attachEvent) {
        return function(el, type, fn) {
            el.attachEvent("on" + type, function(event) {
                event = event || window.event;
                fn.call(el, _eventCompat(event));
            });
        }
    }
    return function() {};
})(window);

var makeSky = (function (doc, window, addEvent) {
    var REQ = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
    var cvs = doc.getElementById('wrapper-cvs');
    var ctx = cvs.getContext('2d');
    cvs.width = doc.documentElement.clientWidth;
    cvs.height = doc.documentElement.clientHeight;

    var stageBack = doc.getElementById('j-stage-block-back'),
        hue = 217,
        stars = [],
        count = 0,
        far = 0,
        maxStars = 500,
        canvas2 = document.createElement('canvas'),
        ctx2 = canvas2.getContext('2d');

    canvas2.width = 100;
    canvas2.height = 100;
    var half = canvas2.width / 2;
    var gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);
    var flagRestartStar = false;
    var flagRestartSky = false;

    gradient2.addColorStop(0.025, '#CCC');
    gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
    gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
    gradient2.addColorStop(1, 'transparent');

    ctx2.fillStyle = gradient2;
    ctx2.beginPath();
    ctx2.arc(half, half, half, 0, Math.PI * 2);
    ctx2.fill();

    function random(min, max) {
        if (arguments.length < 2) {
            max = min;
            min = 0;
        }

        if (min > max) {
            var hold = max;
            max = min;
            min = hold;
        }

        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    function maxOrbit(x, y) {
        var max = Math.max(x, y),
            diameter = Math.round(Math.sqrt(max * max + max * max));
        return diameter / 2;
    }

    Star = function (w,h) {
        this.orbitRadius = random(maxOrbit(w, h));
        this.radius = random(60, this.orbitRadius) / 8;
        this.orbitX = w / 2;
        this.orbitY = h / 2;
        this.timePassed = random(0, maxStars);
        this.speed = random(this.orbitRadius) / 50000;
        this.alpha = random(2, 10) / 10;

        count++;
        stars[count] = this;
    };

    Star.prototype.draw = function () {
        var x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
            y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
            twinkle = random(10);

        if (twinkle === 1 && this.alpha > 0) {
            this.alpha -= 0.05;
        } else if (twinkle === 2 && this.alpha < 1) {
            this.alpha += 0.05;
        }

        ctx.globalAlpha = this.alpha;
        ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
        if (mouseAniSpeed > minAniSpeed) {
            this.timePassed += this.speed * mouseAniSpeed * ratioAniSpeed;
        }
        else {
            this.timePassed += this.speed;
        }
    };

    var isMouseWheel = false;
    var synMouseWheel;
    var minAniSpeed = 0.2;
    var ratioAniSpeed = 1 / minAniSpeed;
    var maxAniSpeed = 1;
    var mouseAniSpeed = minAniSpeed;

    function animation(w,h) {
        if(flagRestartStar) {
            flagRestartStar = false;
            return;
        }
        ctx.globalCompositeOperation = 'source-over';
        ctx.globalAlpha = 0.3;

        ctx.fillRect(0, 0, w, h);

        ctx.globalCompositeOperation = 'lighter';
        for (var i = 1, l = stars.length; i < l; i++) {
            stars[i].draw();
        }

        REQ(function () {
            animation(w,h);
        });
    }

    function skyAnimation() {
        if(flagRestartSky) {
            flagRestartSky = false;
            return;
        }
        if (far < 800) {
            if (isMouseWheel) {
                mouseAniSpeed = maxAniSpeed;
                far += maxAniSpeed;
            }
            else {
                mouseAniSpeed = mouseAniSpeed > minAniSpeed ? mouseAniSpeed - 0.01 : minAniSpeed;
                far += mouseAniSpeed;
            }
            stageBack.style.transform = 'translate3d(0,0,' + far + 'px)';
            REQ(skyAnimation);
        }
    }

    function makeStars(w,h) {
        count = 0;
        for (var i = 0; i < maxStars; i++) {
            new Star(w,h);
        }
    }

    function init() {
        addEvent(doc.body, "mousewheel", function (event) {
            if (event.delta < 0 && far < 800) {
                clearTimeout(synMouseWheel);
                synMouseWheel = setTimeout(function () {
                    isMouseWheel = false;
                    mouseAniSpeed = maxAniSpeed;
                }, 500);
                if (isMouseWheel) {
                    return;
                }
                isMouseWheel = true;
            }
        });
        cvs.width = doc.documentElement.clientWidth;
        cvs.height = doc.documentElement.clientHeight;
        makeStars(cvs.width,cvs.height);
        REQ(function () {
            animation(cvs.width, cvs.height);
            skyAnimation();
        })
    }
    function restart() {
        flagRestartStar = true;
        flagRestartSky = true;
        cvs.width = doc.documentElement.clientWidth;
        cvs.height = doc.documentElement.clientHeight;
        makeStars(cvs.width, cvs.height);
        REQ(function () {
            animation(cvs.width, cvs.height);
            skyAnimation();
        })
    }

    return {
        init: init,
        restart: restart
    };

})(document, window, addEvent);<|endoftext|>


<commit_before>'use strict';

window.define(['react', 'form-collection', 'sidebar-menu', 'search-store'], function (React, FormCollection, SidebarMenu, SearchStore) {

  var Sidebar = React.createClass({
    componentWillUnmount: function () {
      SearchStore.unbind('setSearchTerm', this.getSearchTerm);
    },

    componentWillMount: function () {
      SearchStore.bind('setSearchTerm', this.getSearchTerm);
    },

    setActiveCollection: function (index) {
      index = this.state.activeIndex === index ? undefined : index;

      this.setState({
        activeIndex: index
      });
    },

    getSearchTerm: function () {
      this.setState({
        searchTerm: SearchStore.getSearchTerm()
      });
    },

    getInitialState: function () {
      return {
        activeIndex: 0,
        searchTerm: SearchStore.getSearchTerm()
      };
    },

    render: function () {
      var self = this;

      var formControls = this.props.variables.map(function (item, index) {
        if (item.element === 'collection') {
          return React.createElement(
            FormCollection,
            {
              group: item,
              index: index,
              activeIndex: self.state.activeIndex,
              setActiveCollection: self.setActiveCollection,
              updateVariable: self.props.updateVariable,
              searchTerm: self.state.searchTerm
            }
          );
        }
      });

      return React.createElement(
        'div',
        {
          className: 'sidebar-container'
        },
        React.createElement(
          SidebarMenu,
          {
            setFrameSize: self.props.setFrameSize,
            frameSizes: self.props.frameSizes,
            currentFrameSize: self.props.currentFrameSize,
            preview: self.props.preview,
            reset: self.props.reset,
            searchTerm: self.state.searchTerm
          }
        ),
        React.createElement(
          'div',
          {
            className: 'sidebar'
          },
          React.createElement(
            'div',
            null,
            formControls
          )
        )
      );
    }
  });

  return Sidebar;

});
<commit_msg>Default active index undefined<commit_after>'use strict';

window.define(['react', 'form-collection', 'sidebar-menu', 'search-store'], function (React, FormCollection, SidebarMenu, SearchStore) {

  var Sidebar = React.createClass({
    componentWillUnmount: function () {
      SearchStore.unbind('setSearchTerm', this.getSearchTerm);
    },

    componentWillMount: function () {
      SearchStore.bind('setSearchTerm', this.getSearchTerm);
    },

    setActiveCollection: function (index) {
      index = this.state.activeIndex === index ? undefined : index;

      this.setState({
        activeIndex: index
      });
    },

    getSearchTerm: function () {
      this.setState({
        searchTerm: SearchStore.getSearchTerm()
      });
    },

    getInitialState: function () {
      return {
        activeIndex: undefined,
        searchTerm: SearchStore.getSearchTerm()
      };
    },

    render: function () {
      var self = this;

      var formControls = this.props.variables.map(function (item, index) {
        if (item.element === 'collection') {
          return React.createElement(
            FormCollection,
            {
              group: item,
              index: index,
              activeIndex: self.state.activeIndex,
              setActiveCollection: self.setActiveCollection,
              updateVariable: self.props.updateVariable,
              searchTerm: self.state.searchTerm
            }
          );
        }
      });

      return React.createElement(
        'div',
        {
          className: 'sidebar-container'
        },
        React.createElement(
          SidebarMenu,
          {
            setFrameSize: self.props.setFrameSize,
            frameSizes: self.props.frameSizes,
            currentFrameSize: self.props.currentFrameSize,
            preview: self.props.preview,
            reset: self.props.reset,
            searchTerm: self.state.searchTerm
          }
        ),
        React.createElement(
          'div',
          {
            className: 'sidebar'
          },
          React.createElement(
            'div',
            null,
            formControls
          )
        )
      );
    }
  });

  return Sidebar;

});
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/momentjs/moment.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'app/views/*.html',
      'app/views/directives/*.html',
      //'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    preprocessors: {
      'app/views/*.html': 'html2js',
      'app/views/**/*.html': 'html2js',
      'app/scripts/**/*.js': 'coverage'
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Firefox', 'PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    reporters: ['progress','coverage'],

    //coverage reporter type
    coverageReporter: {
        type : 'html'
    }
  });
};
<commit_msg>Added angular-route in karma.conf<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/momentjs/moment.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'app/views/*.html',
      'app/views/directives/*.html',
      //'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

    preprocessors: {
      'app/views/*.html': 'html2js',
      'app/views/**/*.html': 'html2js',
      'app/scripts/**/*.js': 'coverage'
    },

    // list of files / patterns to exclude
    exclude: [],

    // web server port
    port: 8080,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Firefox', 'PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    reporters: ['progress','coverage'],

    //coverage reporter type
    coverageReporter: {
        type : 'html'
    }
  });
};
<|endoftext|>


<commit_before>/**
 * Created by swhite on 6/9/14.
 */

var app = angular.module(
    'ReFlowApp',
    [
        'ngSanitize',
        'ngCookies',
        'ui.router',
        'ui.bootstrap',
        'ui.select2',
        'ncy-angular-breadcrumb',
        'reflowService',
        'modelService',
        'angularFileUpload'
    ]
);

app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/");

    $stateProvider.state({
        name: 'home',
        url: '/',
        templateUrl: '/static/ng-app/partials/home.html',
        data: {
            ncyBreadcrumbLabel: 'Projects'
        }
    }).state({
        name: 'project-detail',
        url: '/project/',
        templateUrl: '/static/ng-app/partials/project-detail.html',
        controller: 'ProjectDetailController',
        data: {
            ncyBreadcrumbLabel: '{{current_project.project_name}}',
            ncyBreadcrumbParent: 'home'
        }
    }).state({
        name: 'subject-group-list',
        url: '/subject-groups/',
        templateUrl: '/static/ng-app/partials/subject-group-list.html',
        controller: 'SubjectGroupController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'subject-group-add',
        url: '/subject-groups/add',
        templateUrl: '/static/ng-app/partials/subject-group-add.html',
        controller: 'SubjectGroupController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'subject-group-list'
        }
    }).state({
        name: 'subject-list',
        url: '/subjects/',
        templateUrl: '/static/ng-app/partials/subject-list.html',
        controller: 'SubjectController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'subject-add',
        url: '/subjects/add',
        templateUrl: '/static/ng-app/partials/subject-add.html',
        controller: 'SubjectController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'subject-list'
        }
    }).state({
        name: 'site-list',
        url: '/sites/',
        templateUrl: '/static/ng-app/partials/site-list.html',
        controller: 'SiteController',
        data: {
            ncyBreadcrumbLabel: 'Sites',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'site-add',
        url: '/sites/add',
        templateUrl: '/static/ng-app/partials/site-add.html',
        controller: 'SiteController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'site-list'
        }
    }).state({
        name: 'cytometer-list',
        url: '/cytometers/',
        templateUrl: '/static/ng-app/partials/cytometer-list.html',
        controller: 'CytometerController',
        data: {
            ncyBreadcrumbLabel: 'Cytometers',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'cytometer-add',
        url: '/cytometers/add',
        templateUrl: '/static/ng-app/partials/cytometer-add.html',
        controller: 'CytometerController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'cytometer-list'
        }
    }).state({
        name: 'visit-type-list',
        url: '/visit-types/',
        templateUrl: '/static/ng-app/partials/visit-type-list.html',
        controller: 'VisitTypeController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'visit-type-add',
        url: '/visit-types/add',
        templateUrl: '/static/ng-app/partials/visit-type-add.html',
        controller: 'VisitTypeController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'visit-type-list'
        }
    }).state({
        name: 'stimulation-list',
        url: '/stimulations/',
        templateUrl: '/static/ng-app/partials/stimulation-list.html',
        controller: 'StimulationController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'stimulation-add',
        url: '/stimulations/add',
        templateUrl: '/static/ng-app/partials/stimulation-add.html',
        controller: 'StimulationController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'stimulation-list'
        }
    }).state({
        name: 'panel-template-list',
        url: '/panel-templates/',
        templateUrl: '/static/ng-app/partials/panel-template-list.html',
        controller: 'PanelTemplateController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'panel-template-add',
        url: '/panel-templates/add',
        templateUrl: '/static/ng-app/partials/panel-template-add.html',
        controller: 'PanelTemplateController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'panel-template-list'
        }
    }).state({
        name: 'site-panel-list',
        url: '/site-panels/',
        templateUrl: '/static/ng-app/partials/site-panel-list.html',
        controller: 'SitePanelController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'sample-list',
        url: '/samples/',
        templateUrl: '/static/ng-app/partials/sample-list.html',
        controller: 'SampleController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'sample-add',
        url: '/samples/add',
        templateUrl: '/static/ng-app/partials/sample-add.html',
        controller: 'SampleController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'sample-list'
        }
    }).state({
        name: 'bead-sample-list',
        url: '/bead-samples/',
        templateUrl: '/static/ng-app/partials/bead-sample-list.html',
        controller: 'BeadSampleController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'bead-sample-add',
        url: '/bead-samples/add',
        templateUrl: '/static/ng-app/partials/bead-sample-add.html',
        controller: 'BeadSampleController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'bead-sample-list'
        }
    }).state({
        name: 'compensation-list',
        url: '/compensations/',
        templateUrl: '/static/ng-app/partials/compensation-list.html',
        controller: 'CompensationController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'compensation-add',
        url: '/compensations/add',
        templateUrl: '/static/ng-app/partials/compensation-add.html',
        controller: 'CompensationController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'compensation-list'
        }
    });
});

app.run(function ($http, $cookies) {
    $http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});

app.filter('bytes', function() {
	return function(bytes, precision) {
		if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-';
		if (typeof precision === 'undefined') precision = 1;
		var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'],
			number = Math.floor(Math.log(bytes) / Math.log(1024));
		return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) +  ' ' + units[number];
	}
});

app.directive('closeModal', function (){
   return function(scope, elem, attrs) {
     scope.$watch('model.close_modal', function(val) {
        if(val) {
           elem.modal('hide');
        }
     });
   }
});<commit_msg>start project editing in ng<commit_after>/**
 * Created by swhite on 6/9/14.
 */

var app = angular.module(
    'ReFlowApp',
    [
        'ngSanitize',
        'ngCookies',
        'ui.router',
        'ui.bootstrap',
        'ui.select2',
        'ncy-angular-breadcrumb',
        'reflowService',
        'modelService',
        'angularFileUpload'
    ]
);

app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/");

    $stateProvider.state({
        name: 'home',
        url: '/',
        templateUrl: '/static/ng-app/partials/home.html',
        data: {
            ncyBreadcrumbLabel: 'Projects'
        }
    }).state({
        name: 'project-detail',
        url: '/project/',
        templateUrl: '/static/ng-app/partials/project-detail.html',
        controller: 'ProjectDetailController',
        data: {
            ncyBreadcrumbLabel: '{{current_project.project_name}}',
            ncyBreadcrumbParent: 'home'
        }
    }).state({
        name: 'project-edit',
        url: '/project/edit',
        templateUrl: '/static/ng-app/partials/project-edit.html',
        controller: 'ProjectDetailController',
        data: {
            ncyBreadcrumbLabel: 'Edit',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'subject-group-list',
        url: '/subject-groups/',
        templateUrl: '/static/ng-app/partials/subject-group-list.html',
        controller: 'SubjectGroupController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'subject-group-add',
        url: '/subject-groups/add',
        templateUrl: '/static/ng-app/partials/subject-group-add.html',
        controller: 'SubjectGroupController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'subject-group-list'
        }
    }).state({
        name: 'subject-list',
        url: '/subjects/',
        templateUrl: '/static/ng-app/partials/subject-list.html',
        controller: 'SubjectController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'subject-add',
        url: '/subjects/add',
        templateUrl: '/static/ng-app/partials/subject-add.html',
        controller: 'SubjectController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'subject-list'
        }
    }).state({
        name: 'site-list',
        url: '/sites/',
        templateUrl: '/static/ng-app/partials/site-list.html',
        controller: 'SiteController',
        data: {
            ncyBreadcrumbLabel: 'Sites',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'site-add',
        url: '/sites/add',
        templateUrl: '/static/ng-app/partials/site-add.html',
        controller: 'SiteController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'site-list'
        }
    }).state({
        name: 'cytometer-list',
        url: '/cytometers/',
        templateUrl: '/static/ng-app/partials/cytometer-list.html',
        controller: 'CytometerController',
        data: {
            ncyBreadcrumbLabel: 'Cytometers',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'cytometer-add',
        url: '/cytometers/add',
        templateUrl: '/static/ng-app/partials/cytometer-add.html',
        controller: 'CytometerController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'cytometer-list'
        }
    }).state({
        name: 'visit-type-list',
        url: '/visit-types/',
        templateUrl: '/static/ng-app/partials/visit-type-list.html',
        controller: 'VisitTypeController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'visit-type-add',
        url: '/visit-types/add',
        templateUrl: '/static/ng-app/partials/visit-type-add.html',
        controller: 'VisitTypeController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'visit-type-list'
        }
    }).state({
        name: 'stimulation-list',
        url: '/stimulations/',
        templateUrl: '/static/ng-app/partials/stimulation-list.html',
        controller: 'StimulationController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'stimulation-add',
        url: '/stimulations/add',
        templateUrl: '/static/ng-app/partials/stimulation-add.html',
        controller: 'StimulationController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'stimulation-list'
        }
    }).state({
        name: 'panel-template-list',
        url: '/panel-templates/',
        templateUrl: '/static/ng-app/partials/panel-template-list.html',
        controller: 'PanelTemplateController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'panel-template-add',
        url: '/panel-templates/add',
        templateUrl: '/static/ng-app/partials/panel-template-add.html',
        controller: 'PanelTemplateController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'panel-template-list'
        }
    }).state({
        name: 'site-panel-list',
        url: '/site-panels/',
        templateUrl: '/static/ng-app/partials/site-panel-list.html',
        controller: 'SitePanelController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'sample-list',
        url: '/samples/',
        templateUrl: '/static/ng-app/partials/sample-list.html',
        controller: 'SampleController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'sample-add',
        url: '/samples/add',
        templateUrl: '/static/ng-app/partials/sample-add.html',
        controller: 'SampleController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'sample-list'
        }
    }).state({
        name: 'bead-sample-list',
        url: '/bead-samples/',
        templateUrl: '/static/ng-app/partials/bead-sample-list.html',
        controller: 'BeadSampleController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'bead-sample-add',
        url: '/bead-samples/add',
        templateUrl: '/static/ng-app/partials/bead-sample-add.html',
        controller: 'BeadSampleController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'bead-sample-list'
        }
    }).state({
        name: 'compensation-list',
        url: '/compensations/',
        templateUrl: '/static/ng-app/partials/compensation-list.html',
        controller: 'CompensationController',
        data: {
            ncyBreadcrumbLabel: 'Subject Groups',
            ncyBreadcrumbParent: 'project-detail'
        }
    }).state({
        name: 'compensation-add',
        url: '/compensations/add',
        templateUrl: '/static/ng-app/partials/compensation-add.html',
        controller: 'CompensationController',
        data: {
            ncyBreadcrumbLabel: 'Add',
            ncyBreadcrumbParent: 'compensation-list'
        }
    });
});

app.run(function ($http, $cookies) {
    $http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});

app.filter('bytes', function() {
	return function(bytes, precision) {
		if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-';
		if (typeof precision === 'undefined') precision = 1;
		var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'],
			number = Math.floor(Math.log(bytes) / Math.log(1024));
		return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) +  ' ' + units[number];
	}
});

app.directive('closeModal', function (){
   return function(scope, elem, attrs) {
     scope.$watch('model.close_modal', function(val) {
        if(val) {
           elem.modal('hide');
        }
     });
   }
});<|endoftext|>


<commit_before>import Node from './Node'
import Scene from './Scene'
import XYZValues from './XYZValues'
import {useDefaultNames} from '../html'

useDefaultNames()

const sleep = ms => new Promise(r => setTimeout(r, ms))

describe('Node', () => {

    let scene = document.createElement('i-scene')
    // let scene = new Scene
	const body = document.body

    afterEach(() => {
		scene.unmount()
		body.innerHTML = ''
		scene = document.createElement('i-scene')
		// scene = new Scene
		scene.mount(body)
	})

    it('default values', async () => {
        // useDefaultNames()

		const n = document.createElement('i-node')
		// const n = new Node // FIXME why doesn't this work?

		expect(n.position.x).toEqual(0)
		expect(n.position.y).toEqual(0)
		expect(n.position.z).toEqual(0)

		expect(n.rotation.x).toEqual(0)
		expect(n.rotation.y).toEqual(0)
		expect(n.rotation.z).toEqual(0)

		expect(n.scale.x).toEqual(1)
		expect(n.scale.y).toEqual(1)
		expect(n.scale.z).toEqual(1)

		expect(n.align.x).toEqual(0)
		expect(n.align.y).toEqual(0)
		expect(n.align.z).toEqual(0)

		expect(n.mountPoint.x).toEqual(0)
		expect(n.mountPoint.y).toEqual(0)
		expect(n.mountPoint.z).toEqual(0)

		expect(n.opacity).toEqual(1)

		expect(n.size.x).toEqual(100)
		expect(n.size.y).toEqual(100)
		expect(n.size.z).toEqual(100)

		expect(n.sizeMode.x).toEqual('literal')
		expect(n.sizeMode.y).toEqual('literal')
		expect(n.sizeMode.z).toEqual('literal')
    })

    it('element is an instance of Node', async () => {
        // useDefaultNames()

		const n = document.createElement('i-node')
        // const n = new Node

		scene.add(n)

		// expect(n instanceof Node).toBe(true) // FIXME why does this fail?
		expect(n.constructor.name).toBe('Node')
        expect(n.threeObject3d).not.toBeUndefined()
        expect(n.scene).not.toBeUndefined()
        expect(n.scene.constructor.name).toBe('Scene')
    })
})
<commit_msg>update the Node tests to use 'new' now that the previous commit fixed native extension<commit_after>import Node from './Node'
import Scene from './Scene'
import XYZValues from './XYZValues'
import {useDefaultNames} from '../html'

useDefaultNames()

const sleep = ms => new Promise(r => setTimeout(r, ms))

describe('Node', () => {

    let scene = new Scene
	const body = document.body

    afterEach(() => {
		scene.unmount()
		body.innerHTML = ''
		scene = new Scene
		scene.mount(body)
	})

    it('default values', async () => {
		const n = new Node

		expect(n.position.x).toEqual(0)
		expect(n.position.y).toEqual(0)
		expect(n.position.z).toEqual(0)

		expect(n.rotation.x).toEqual(0)
		expect(n.rotation.y).toEqual(0)
		expect(n.rotation.z).toEqual(0)

		expect(n.scale.x).toEqual(1)
		expect(n.scale.y).toEqual(1)
		expect(n.scale.z).toEqual(1)

		expect(n.align.x).toEqual(0)
		expect(n.align.y).toEqual(0)
		expect(n.align.z).toEqual(0)

		expect(n.mountPoint.x).toEqual(0)
		expect(n.mountPoint.y).toEqual(0)
		expect(n.mountPoint.z).toEqual(0)

		expect(n.opacity).toEqual(1)

		expect(n.size.x).toEqual(100)
		expect(n.size.y).toEqual(100)
		expect(n.size.z).toEqual(100)

		expect(n.sizeMode.x).toEqual('literal')
		expect(n.sizeMode.y).toEqual('literal')
		expect(n.sizeMode.z).toEqual('literal')
    })

    it('element is an instance of Node, created with `new`', async () => {
        const n = new Node

		scene.add(n)

		expect(n instanceof Node).toBe(true)
		expect(n.constructor.name).toBe('Node')
        expect(n.threeObject3d).not.toBeUndefined()
        expect(n.scene).not.toBeUndefined()
        expect(n.scene.constructor.name).toBe('Scene')
    })

    it('element is an instance of Node, created with `document.createElement`', async () => {
		const n = document.createElement('i-node')

		scene.add(n)

		expect(n instanceof Node).toBe(true)
		expect(n.constructor.name).toBe('Node')
        expect(n.threeObject3d).not.toBeUndefined()
        expect(n.scene).not.toBeUndefined()
        expect(n.scene.constructor.name).toBe('Scene')
    })
})
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://clara.io/
 * @author stephomi / http://stephaneginier.com/
 */

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;

		this.params = {
			Mesh: {},
			Line: {},
			LOD: {},
			Points: { threshold: 1 },
			Sprite: {}
		};

		Object.defineProperties( this.params, {
			PointCloud: {
				get: function () {
					console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
					return this.Points;
				}
			}
		} );

	};

	function ascSort( a, b ) {

		return a.distance - b.distance;

	}

	function intersectObject( object, raycaster, intersects, recursive ) {

		if ( object.visible === false ) return;

		object.raycast( raycaster, intersects );

		if ( recursive === true ) {

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				intersectObject( children[ i ], raycaster, intersects, true );

			}

		}

	}

	//

	THREE.Raycaster.prototype = {

		constructor: THREE.Raycaster,

		linePrecision: 1,

		set: function ( origin, direction ) {

			// direction is assumed to be normalized (for accurate distance calculations)

			this.ray.set( origin, direction );

		},

		setFromCamera: function ( coords, camera ) {

			if ( camera instanceof THREE.PerspectiveCamera ) {

				this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
				this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();

			} else if ( camera instanceof THREE.OrthographicCamera ) {

				this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
				this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );

			} else {

				console.error( 'THREE.Raycaster: Unsupported camera type.' );

			}

		},

		intersectObject: function ( object, recursive ) {

			var intersects = [];

			intersectObject( object, this, intersects, recursive );

			intersects.sort( ascSort );

			return intersects;

		},

		intersectObjects: function ( objects, recursive ) {

			var intersects = [];

			if ( Array.isArray( objects ) === false ) {

				console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
				return intersects;

			}

			for ( var i = 0, l = objects.length; i < l; i ++ ) {

				intersectObject( objects[ i ], this, intersects, recursive );

			}

			intersects.sort( ascSort );

			return intersects;

		}

	};

}( THREE ) );
<commit_msg>Raycaster: correct ray origin in SetFromCamera() (#9098)<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://clara.io/
 * @author stephomi / http://stephaneginier.com/
 */

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;

		this.params = {
			Mesh: {},
			Line: {},
			LOD: {},
			Points: { threshold: 1 },
			Sprite: {}
		};

		Object.defineProperties( this.params, {
			PointCloud: {
				get: function () {
					console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
					return this.Points;
				}
			}
		} );

	};

	function ascSort( a, b ) {

		return a.distance - b.distance;

	}

	function intersectObject( object, raycaster, intersects, recursive ) {

		if ( object.visible === false ) return;

		object.raycast( raycaster, intersects );

		if ( recursive === true ) {

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				intersectObject( children[ i ], raycaster, intersects, true );

			}

		}

	}

	//

	THREE.Raycaster.prototype = {

		constructor: THREE.Raycaster,

		linePrecision: 1,

		set: function ( origin, direction ) {

			// direction is assumed to be normalized (for accurate distance calculations)

			this.ray.set( origin, direction );

		},

		setFromCamera: function ( coords, camera ) {

			if ( camera instanceof THREE.PerspectiveCamera ) {

				this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
				this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();

			} else if ( camera instanceof THREE.OrthographicCamera ) {

				this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
				this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );

			} else {

				console.error( 'THREE.Raycaster: Unsupported camera type.' );

			}

		},

		intersectObject: function ( object, recursive ) {

			var intersects = [];

			intersectObject( object, this, intersects, recursive );

			intersects.sort( ascSort );

			return intersects;

		},

		intersectObjects: function ( objects, recursive ) {

			var intersects = [];

			if ( Array.isArray( objects ) === false ) {

				console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
				return intersects;

			}

			for ( var i = 0, l = objects.length; i < l; i ++ ) {

				intersectObject( objects[ i ], this, intersects, recursive );

			}

			intersects.sort( ascSort );

			return intersects;

		}

	};

}( THREE ) );
<|endoftext|>


<commit_before>import Axios from 'axios';

import experimentalMode from '@waldur/configs/modes/experimental.json';
import stableMode from '@waldur/configs/modes/stable.json';

import attachTracking from './tracking';

const CONFIG_FILE = 'scripts/configs/config.json';
const modes = { stableMode, experimentalMode };

function renderError(details) {
  document
    .querySelector('.loading-screen')
    .setAttribute('style', 'display: none');
  document.querySelector('.erred-screen').setAttribute('style', '');
  document.querySelector('#wrapper').remove();
  document.querySelector('.erred-screen-message').textContent = details;
  document.querySelector('#retry-bootstrap').addEventListener('click', () => {
    location.reload();
  });
}

async function loadConfig() {
  let frontendSettings, backendSettings;
  try {
    const frontendResponse = await Axios.get(CONFIG_FILE);
    frontendSettings = frontendResponse.data;
  } catch (error) {
    if (error.status === 404) {
      // fallback to default configuration
      frontendSettings = {
        apiEndpoint: 'http://localhost:8080/',
      };
    } else if (error instanceof SyntaxError) {
      renderError(
        `Unable to parse client configuration file ${CONFIG_FILE}. Error message: ${error}`,
      );
      return;
    } else {
      renderError(error);
      return;
    }
  }

  try {
    const backendResponse = await Axios.get(
      `${frontendSettings.apiEndpoint}api/configuration/`,
    );
    backendSettings = backendResponse.data;
  } catch (error) {
    if (error.status === -1) {
      renderError(
        `Unfortunately, connection to server has failed. Please check if you can connect to ${frontendSettings.apiEndpoint} from your browser and contact support if the error continues.`,
      );
    } else if (error.status >= 400) {
      renderError(
        `Unable to fetch server configuration. Error message: ${error.statusText}`,
      );
    } else {
      renderError(error);
    }
    return;
  }

  return { ...frontendSettings, plugins: backendSettings };
}

export default async function bootstrap(modulename) {
  const config = await loadConfig();
  if (!config) {
    return;
  }
  window.$$CUSTOMENV = config;
  window.$$MODES = modes;
  attachTracking(window.$$CUSTOMENV);

  angular.element(document).ready(function() {
    angular.bootstrap(document, [modulename], { strictDi: true });
  });
}
<commit_msg>Fix error processing during bootstrap wrt Axios API.<commit_after>import Axios from 'axios';

import experimentalMode from '@waldur/configs/modes/experimental.json';
import stableMode from '@waldur/configs/modes/stable.json';

import attachTracking from './tracking';

const CONFIG_FILE = 'scripts/configs/config.json';
const modes = { stableMode, experimentalMode };

function renderError(details) {
  document
    .querySelector('.loading-screen')
    .setAttribute('style', 'display: none');
  document.querySelector('.erred-screen').setAttribute('style', '');
  document.querySelector('#wrapper').remove();
  document.querySelector('.erred-screen-message').textContent = details;
  document.querySelector('#retry-bootstrap').addEventListener('click', () => {
    location.reload();
  });
}

async function loadConfig() {
  let frontendSettings, backendSettings;
  try {
    const frontendResponse = await Axios.get(CONFIG_FILE);
    frontendSettings = frontendResponse.data;
  } catch (error) {
    if (error.status === 404) {
      // fallback to default configuration
      frontendSettings = {
        apiEndpoint: 'http://localhost:8080/',
      };
    } else if (error instanceof SyntaxError) {
      renderError(
        `Unable to parse client configuration file ${CONFIG_FILE}. Error message: ${error}`,
      );
      return;
    } else {
      renderError(error);
      return;
    }
  }

  try {
    const backendResponse = await Axios.get(
      `${frontendSettings.apiEndpoint}api/configuration/`,
    );
    backendSettings = backendResponse.data;
  } catch (error) {
    if (!error.response) {
      renderError(
        `Unfortunately, connection to server has failed. Please check if you can connect to ${frontendSettings.apiEndpoint} from your browser and contact support if the error continues.`,
      );
      return;
    } else if (error.response.status >= 400) {
      renderError(
        `Unable to fetch server configuration. Error message: ${error.response.statusText}`,
      );
    } else {
      renderError(error);
    }
    return;
  }

  return { ...frontendSettings, plugins: backendSettings };
}

export default async function bootstrap(modulename) {
  const config = await loadConfig();
  if (!config) {
    return;
  }
  window.$$CUSTOMENV = config;
  window.$$MODES = modes;
  attachTracking(window.$$CUSTOMENV);

  angular.element(document).ready(function() {
    angular.bootstrap(document, [modulename], { strictDi: true });
  });
}
<|endoftext|>


<commit_before>/* global inject */
/// <reference path="../typings/angularjs/angular.d.ts"/>
/// <reference path="../typings/jasmine/jasmine.d.ts"/>
describe('directive', function () {
	var $compile;

	beforeEach(module('wt.responsive'));
	beforeEach(inject(function (_$compile_) {
		$compile = _$compile_;
	}));

	it('supports colspan', function () {
		var markup = [
		    '
',
		    '
',
		    '
',
		    '            First title	',
		    '            Second title	',
		    '            Third title	',
		    '            Forth title	',
		    '
',
		    '
',
		    '
',
		    '
',
		    '            This cell spans for 3 columns	',
		    '            Forth column	',
		    '
',
		    '
',
		    '            First column	',
		    '            Second column	',
		    '            Third column	',
		    '            Forth column	',
		    '
',
		    '
',
		    '
'
		].join('');
		var element = angular.element(markup);

		var firstDataRow = element.find('tbody tr:first td');
		expect(firstDataRow.attr('data-title')).toBeUndefined();

		$compile(element);

		expect(firstDataRow.eq(0).attr('data-title')).toBe('First title');
		expect(firstDataRow.eq(1).attr('data-title')).toBe('Forth title');
	});
});<commit_msg>tests(directive): add test covering dynamic rows<commit_after>/* global inject */
/// <reference path="../typings/angularjs/angular.d.ts"/>
/// <reference path="../typings/jasmine/jasmine.d.ts"/>
describe('directive', function () {
	var $compile,
		$rootScope;

	beforeEach(module('wt.responsive'));
	beforeEach(inject(function (_$rootScope_, _$compile_) {
		$compile = _$compile_;
		$rootScope = _$rootScope_;
	}));

	it('supports colspan', function () {
		var markup = [
		    '
',
		    '
',
		    '
',
		    '            First title	',
		    '            Second title	',
		    '            Third title	',
		    '            Forth title	',
		    '
',
		    '
',
		    '
',
		    '
',
		    '            This cell spans for 3 columns	',
		    '            Forth column	',
		    '
',
		    '
',
		    '            First column	',
		    '            Second column	',
		    '            Third column	',
		    '            Forth column	',
		    '
',
		    '
',
		    '
'
		].join('');
		var element = angular.element(markup);

		var firstDataRow = element.find('tbody tr:first td');
		expect(firstDataRow.attr('data-title')).toBeUndefined();

		$compile(element);

		expect(firstDataRow.eq(0).attr('data-title')).toBe('First title');
		expect(firstDataRow.eq(1).attr('data-title')).toBe('Forth title');
	});

	it('supports ng-repeat applied on TR', function () {
		var markup = [
		    '
',
		    '
',
		    '
',
		    '            First title	',
		    '            Second title	',
		    '            Third title	',
		    '            Forth title	',
		    '
',
		    '
',
		    '
',
		    '
',
		    '            First column	',
		    '            Second column	',
		    '            Third column	',
		    '            Forth column	',
		    '
',
		    '
',
		    '
'
		].join('');
		var element = angular.element(markup);
		var scope = $rootScope.$new();
		scope.rows = [0, 1];

		var firstDataRow = element.find('tbody tr:first td');
		expect(firstDataRow.attr('data-title')).toBeUndefined();

		$compile(element)(scope);

		expect(firstDataRow.eq(0).attr('data-title')).toBe('First title');
		expect(firstDataRow.eq(1).attr('data-title')).toBe('Second title');
		expect(firstDataRow.eq(2).attr('data-title')).toBe('Third title');
		expect(firstDataRow.eq(3).attr('data-title')).toBe('Forth title');
	});
});<|endoftext|>


<commit_before>import _ from 'lodash';
const {knex} = require('../util/database').connect();
import {GCS_CONFIG} from '../util/gcs';
import CONST from '../constants';
const logger = require('../util/logger')(__filename);

const FEED_ITEM_TYPES = new Set(['IMAGE', 'TEXT', 'CHECK_IN']);

function getStickySqlString() {
  return `
    (SELECT
      feed_items.id as id,
      feed_items.location as location,
      feed_items.created_at as created_at,
      feed_items.image_path as image_path,
      feed_items.text as text,
      feed_items.type as action_type_code,
      feed_items.city_id as city_id,
      COALESCE(users.name, 'SYSTEM') as user_name,
      users.uuid as user_uuid,
      teams.name as team_name,
      vote_score(feed_items) as votes,
      feed_items.hot_score as hot_score,
      feed_items.is_sticky,
      COALESCE(votes.value, 0) as user_vote
    FROM feed_items
    LEFT JOIN users ON users.id = feed_items.user_id
    LEFT JOIN teams ON teams.id = users.team_id
    LEFT JOIN votes ON votes.user_id = ? AND votes.feed_item_id = feed_items.id
    WHERE feed_items.is_sticky
    GROUP BY
      feed_items.id,
      users.name,
      users.uuid,
      teams.name,
      votes.value
    ORDER BY feed_items.id DESC
    LIMIT 2)`;
}

function getFeed(opts) {
  opts = _.merge({
    limit: 20
  }, opts);

  let sqlString = `
    (SELECT
      feed_items.id as id,
      feed_items.location as location,
      feed_items.created_at as created_at,
      feed_items.image_path as image_path,
      feed_items.text as text,
      feed_items.type as action_type_code,
      feed_items.city_id as city_id,
      COALESCE(users.name, 'SYSTEM') as user_name,
      users.uuid as user_uuid,
      teams.name as team_name,
      vote_score(feed_items) as votes,
      feed_items.hot_score as hot_score,
      feed_items.is_sticky,
      COALESCE(votes.value, 0) as user_vote
    FROM feed_items
    LEFT JOIN users ON users.id = feed_items.user_id
    LEFT JOIN teams ON teams.id = users.team_id
    LEFT JOIN votes ON votes.user_id = ? AND votes.feed_item_id = feed_items.id
    `;

  let params = [opts.client.id];
  let whereClauses = ['NOT feed_items.is_sticky'];

  if (!opts.beforeId) {
    sqlString = getStickySqlString() + " UNION ALL " + sqlString;
    params.push(opts.client.id);
  } else {
    whereClauses.push('feed_items.id < ?');
    params.push(opts.beforeId);
  }

  if (!opts.client.isBanned) {
    whereClauses.push('NOT feed_items.is_banned');
  }

  if (opts.city) {
    whereClauses.push(`feed_items.city_id = ?`);
    params.push(opts.city);
  }

  if (whereClauses.length > 0) {
    sqlString += ` WHERE ${ whereClauses.join(' AND ')}`;
  }
  sqlString += ` GROUP BY feed_items.id, users.name, users.uuid, teams.name, votes.value ) `;
  sqlString += _getSortingSql(opts.sort);
  sqlString += ` LIMIT ?`;
  params.push(opts.limit);

  return knex.raw(sqlString, params)
  .then(result => {
    const rows = result.rows;

    if (_.isEmpty(rows)) {
      return [];
    }

    return _.map(rows, row => _actionToFeedObject(row, opts.client));
  });
}

function createFeedItem(feedItem, trx) {
  if (!FEED_ITEM_TYPES.has(feedItem.type)) {
    throw new Error('Invalid feed item type ' + feedItem.type);
  }
  console.log(feedItem);
  const dbRow = {
    'image_path': feedItem.imagePath,
    'text':       feedItem.text,
    'type':       feedItem.type,
    'city_id':    feedItem.city,
  };

  const location = feedItem.location;
  if (location) {
    // Tuple is in longitude, latitude format in Postgis
    dbRow.location = location.longitude + ',' + location.latitude;
  }
  if (feedItem.isBanned) {
    dbRow.is_banned = feedItem.isBanned;
  }

  if (feedItem.isSticky) {
    dbRow.is_sticky = feedItem.isSticky;
  }

  // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  if (feedItem.user) {
    dbRow.user_id = knex.raw('(SELECT id from users WHERE uuid = ?)', [feedItem.user]);
    dbRow.city_id = dbRow.city_id || knex.raw('(SELECT city_id FROM teams WHERE id = ?)', [feedItem.client.team]);
  }

  console.log(feedItem);

  trx = trx || knex;

  return trx.returning('*').insert(dbRow).into('feed_items')
    .then(rows => {
      if (_.isEmpty(rows)) {
        throw new Error('Feed item row creation failed: ' + dbRow);
      }

      return rows.length;
    });
}

function deleteFeedItem(id, opts) {
  opts = opts || {};

  return knex('feed_items').delete().where({
    'id': id,
    'user_id': knex.raw('(SELECT id from users WHERE uuid = ?)', [opts.client.uuid])
  })
  .then(deletedCount => {
    if (deletedCount > 1) {
      logger.error('Deleted feed item', id, 'client uuid:', opts.client.uuid);
      throw new Error('Unexpected amount of deletes happened: ' + deletedCount)
    }

    return deletedCount;
  });
}

function _actionToFeedObject(row, client) {
  if (!client) {
    throw new Error('Client information not passed as a parameter');
  }

  var feedObj = {
    id: row['id'],
    type: row['action_type_code'],
    votes: row['votes'],
    userVote: row['user_vote'],
    hotScore: row['hot_score'],
    cityId: row['city_id'],
    author: {
      name: row['user_name'],
      team: row['team_name'],
      type: _resolveAuthorType(row, client)
    },
    createdAt: row['created_at']
  };

  if (row.location) {
    feedObj.location = {
      latitude: row.location.y,
      longitude: row.location.x
    };
  }

  if (feedObj.type === 'IMAGE') {
    const imagePath = row['image_path'];

    if (process.env.DISABLE_IMGIX === 'true' || _.endsWith(imagePath, 'gif')) {
      feedObj.url = GCS_CONFIG.baseUrl + '/' + GCS_CONFIG.bucketName + '/' + imagePath;
    } else {
      feedObj.url =
        'https://' + GCS_CONFIG.bucketName + '.imgix.net/' + imagePath +
        process.env.IMGIX_QUERY;
    }
  } else if (feedObj.type === 'TEXT') {
    feedObj.text = row.text;
  }

  return feedObj;
}

function _getSortingSql(sort) {
  const { HOT } = CONST.FEED_SORT_TYPES;

  if (sort === HOT) {
    return 'ORDER BY is_sticky DESC, hot_score DESC, id DESC';
  } else {
    // Defaults to 'NEW'
    return 'ORDER BY is_sticky DESC, id DESC';
  }
}

function _resolveAuthorType(row, client) {
  const rowUserUuid = row['user_uuid'];

  if (rowUserUuid === null) {
    return CONST.AUTHOR_TYPES.SYSTEM;
  } else if (rowUserUuid === client.uuid) {
    return CONST.AUTHOR_TYPES.ME;
  }

  return CONST.AUTHOR_TYPES.OTHER_USER;
}

export {
  getFeed,
  createFeedItem,
  deleteFeedItem,
};
<commit_msg>Removed console.logs<commit_after>import _ from 'lodash';
const {knex} = require('../util/database').connect();
import {GCS_CONFIG} from '../util/gcs';
import CONST from '../constants';
const logger = require('../util/logger')(__filename);

const FEED_ITEM_TYPES = new Set(['IMAGE', 'TEXT', 'CHECK_IN']);

function getStickySqlString() {
  return `
    (SELECT
      feed_items.id as id,
      feed_items.location as location,
      feed_items.created_at as created_at,
      feed_items.image_path as image_path,
      feed_items.text as text,
      feed_items.type as action_type_code,
      feed_items.city_id as city_id,
      COALESCE(users.name, 'SYSTEM') as user_name,
      users.uuid as user_uuid,
      teams.name as team_name,
      vote_score(feed_items) as votes,
      feed_items.hot_score as hot_score,
      feed_items.is_sticky,
      COALESCE(votes.value, 0) as user_vote
    FROM feed_items
    LEFT JOIN users ON users.id = feed_items.user_id
    LEFT JOIN teams ON teams.id = users.team_id
    LEFT JOIN votes ON votes.user_id = ? AND votes.feed_item_id = feed_items.id
    WHERE feed_items.is_sticky
    GROUP BY
      feed_items.id,
      users.name,
      users.uuid,
      teams.name,
      votes.value
    ORDER BY feed_items.id DESC
    LIMIT 2)`;
}

function getFeed(opts) {
  opts = _.merge({
    limit: 20
  }, opts);

  let sqlString = `
    (SELECT
      feed_items.id as id,
      feed_items.location as location,
      feed_items.created_at as created_at,
      feed_items.image_path as image_path,
      feed_items.text as text,
      feed_items.type as action_type_code,
      feed_items.city_id as city_id,
      COALESCE(users.name, 'SYSTEM') as user_name,
      users.uuid as user_uuid,
      teams.name as team_name,
      vote_score(feed_items) as votes,
      feed_items.hot_score as hot_score,
      feed_items.is_sticky,
      COALESCE(votes.value, 0) as user_vote
    FROM feed_items
    LEFT JOIN users ON users.id = feed_items.user_id
    LEFT JOIN teams ON teams.id = users.team_id
    LEFT JOIN votes ON votes.user_id = ? AND votes.feed_item_id = feed_items.id
    `;

  let params = [opts.client.id];
  let whereClauses = ['NOT feed_items.is_sticky'];

  if (!opts.beforeId) {
    sqlString = getStickySqlString() + " UNION ALL " + sqlString;
    params.push(opts.client.id);
  } else {
    whereClauses.push('feed_items.id < ?');
    params.push(opts.beforeId);
  }

  if (!opts.client.isBanned) {
    whereClauses.push('NOT feed_items.is_banned');
  }

  if (opts.city) {
    whereClauses.push(`feed_items.city_id = ?`);
    params.push(opts.city);
  }

  if (whereClauses.length > 0) {
    sqlString += ` WHERE ${ whereClauses.join(' AND ')}`;
  }
  sqlString += ` GROUP BY feed_items.id, users.name, users.uuid, teams.name, votes.value ) `;
  sqlString += _getSortingSql(opts.sort);
  sqlString += ` LIMIT ?`;
  params.push(opts.limit);

  return knex.raw(sqlString, params)
  .then(result => {
    const rows = result.rows;

    if (_.isEmpty(rows)) {
      return [];
    }

    return _.map(rows, row => _actionToFeedObject(row, opts.client));
  });
}

function createFeedItem(feedItem, trx) {
  if (!FEED_ITEM_TYPES.has(feedItem.type)) {
    throw new Error('Invalid feed item type ' + feedItem.type);
  }

  const dbRow = {
    'image_path': feedItem.imagePath,
    'text':       feedItem.text,
    'type':       feedItem.type,
    'city_id':    feedItem.city,
  };

  const location = feedItem.location;
  if (location) {
    // Tuple is in longitude, latitude format in Postgis
    dbRow.location = location.longitude + ',' + location.latitude;
  }
  if (feedItem.isBanned) {
    dbRow.is_banned = feedItem.isBanned;
  }

  if (feedItem.isSticky) {
    dbRow.is_sticky = feedItem.isSticky;
  }

  // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  if (feedItem.user) {
    dbRow.user_id = knex.raw('(SELECT id from users WHERE uuid = ?)', [feedItem.user]);
    dbRow.city_id = dbRow.city_id || knex.raw('(SELECT city_id FROM teams WHERE id = ?)', [feedItem.client.team]);
  }

  trx = trx || knex;

  return trx.returning('*').insert(dbRow).into('feed_items')
    .then(rows => {
      if (_.isEmpty(rows)) {
        throw new Error('Feed item row creation failed: ' + dbRow);
      }

      return rows.length;
    });
}

function deleteFeedItem(id, opts) {
  opts = opts || {};

  return knex('feed_items').delete().where({
    'id': id,
    'user_id': knex.raw('(SELECT id from users WHERE uuid = ?)', [opts.client.uuid])
  })
  .then(deletedCount => {
    if (deletedCount > 1) {
      logger.error('Deleted feed item', id, 'client uuid:', opts.client.uuid);
      throw new Error('Unexpected amount of deletes happened: ' + deletedCount)
    }

    return deletedCount;
  });
}

function _actionToFeedObject(row, client) {
  if (!client) {
    throw new Error('Client information not passed as a parameter');
  }

  var feedObj = {
    id: row['id'],
    type: row['action_type_code'],
    votes: row['votes'],
    userVote: row['user_vote'],
    hotScore: row['hot_score'],
    cityId: row['city_id'],
    author: {
      name: row['user_name'],
      team: row['team_name'],
      type: _resolveAuthorType(row, client)
    },
    createdAt: row['created_at']
  };

  if (row.location) {
    feedObj.location = {
      latitude: row.location.y,
      longitude: row.location.x
    };
  }

  if (feedObj.type === 'IMAGE') {
    const imagePath = row['image_path'];

    if (process.env.DISABLE_IMGIX === 'true' || _.endsWith(imagePath, 'gif')) {
      feedObj.url = GCS_CONFIG.baseUrl + '/' + GCS_CONFIG.bucketName + '/' + imagePath;
    } else {
      feedObj.url =
        'https://' + GCS_CONFIG.bucketName + '.imgix.net/' + imagePath +
        process.env.IMGIX_QUERY;
    }
  } else if (feedObj.type === 'TEXT') {
    feedObj.text = row.text;
  }

  return feedObj;
}

function _getSortingSql(sort) {
  const { HOT } = CONST.FEED_SORT_TYPES;

  if (sort === HOT) {
    return 'ORDER BY is_sticky DESC, hot_score DESC, id DESC';
  } else {
    // Defaults to 'NEW'
    return 'ORDER BY is_sticky DESC, id DESC';
  }
}

function _resolveAuthorType(row, client) {
  const rowUserUuid = row['user_uuid'];

  if (rowUserUuid === null) {
    return CONST.AUTHOR_TYPES.SYSTEM;
  } else if (rowUserUuid === client.uuid) {
    return CONST.AUTHOR_TYPES.ME;
  }

  return CONST.AUTHOR_TYPES.OTHER_USER;
}

export {
  getFeed,
  createFeedItem,
  deleteFeedItem,
};
<|endoftext|>


<commit_before>"use strict";

var Brig = require('../../');

var brig = new Brig();

var engine = new brig.QmlEngine();
var rootContext = engine.rootContext();
var context = new brig.QmlContext(rootContext);

var component = new brig.QmlComponent(engine);
component.setData('import QtQuick 2.0\nimport QtQuick.Controls 1.2\nimport QtQuick.Window 2.1\nApplicationWindow {\nvisibility: Window.FullScreen; color: \"red\"\n }');
var qObject = component.create(context);

var window = qObject.toQuickWindow();
window.show();
<commit_msg>using new API on fullscreen testcase<commit_after>"use strict";

var Brig = require('../../');

var brig = new Brig();

brig.on('ready', function(brig) {

	var component = brig.createComponent();
	component.setData('import QtQuick 2.0\nimport QtQuick.Controls 1.2\nimport QtQuick.Window 2.1\nApplicationWindow {\nvisibility: Window.FullScreen; color: \"red\"\n }');

	var window = component.create();
});
<|endoftext|>


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

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateOutput',

  properties: [
    {
      name: 'buf',
      factory: function() { return []; }
    }
  ],

  methods: [
    function output() {
      for ( var i = 0 ; i < arguments.length ; i++ ) {
        var o = arguments[i];

        if ( typeof o === 'object' ) {
          this.buf.push(o.toString());
        } else {
          this.buf.push(o);
        }
      }
    },

    function toString() {
      return this.buf.length == 0 ? '' :
        this.buf.length == 1 ? this.buf[0] :
        this.buf.join('');
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateUtil',

  axioms: [foam.pattern.Singleton.create()],

  requires: [
    'foam.parse.StringPS',
    'foam.parse.ImperativeGrammar as Grammar'
  ],

  constants: {
    HEADER: 'var self = this, ctx = this.__context__, Y = this.__subContext__;\n' +
      'var output = opt_outputter ? opt_outputter : TOC(this);\n' +
      'var out = output.output.bind(output);\n' +
      "out('",
    FOOTER: "');\nreturn opt_outputter ? output : output.toString();\n"
  },

  properties: [
    {
      name: 'grammar',
      factory: function() {
        var g = this.Grammar.create({
          symbols: function(repeat0, simpleAlt, sym, seq1, seq, repeat, notChars, anyChar, not, optional, literal) {
            return {
              START: sym('markup'),

              markup: repeat0(simpleAlt(
                sym('comment'),
                sym('simple value'),
                sym('raw values tag'),
                sym('code tag'),
                sym('ignored newline'),
                sym('newline'),
                sym('single quote'),
                sym('text')
              )),

              'comment': seq1(1, '<!--', repeat0(not('-->', anyChar())), '-->'),

              'simple value': seq('%%', repeat(notChars(' ()-"\r\n><:;,')), optional('()')),

              'raw values tag': simpleAlt(
                seq('<%=', repeat(not('%>', anyChar())), '%>')
              ),

              'code tag': seq('<%', repeat(not('%>', anyChar())), '%>'),
              'ignored newline': simpleAlt(
                literal('\\\r\\\n'),
                literal('\\\n')
              ),
              newline: simpleAlt(
                literal('\r\n'),
                literal('\n')
              ),
              'single quote': literal("'"),
              text: anyChar()
            }
          }
        });
        var self = this;
        g.addActions({
          markup: function(v) {
            var wasSimple = self.simple;
            var ret = wasSimple ? null : self.out.join('');
            self.out = [];
            self.simple = true;
            return [wasSimple, ret];
          },
          'simple value': function(v) {
            self.push("',\n self.",
                      v[1].join(''),
                      v[2],
                      ",\n'");
          },
          'raw values tag': function (v) {
            self.push("',\n",
                      v[1].join(''),
                      ",\n'");
          },
          'code tag': function (v) {
            self.push("');\n",
                      v[1].join(''),
                      ";out('");
          },
          'single quote': function() {
            self.pushSimple("\\'");
          },
          newline: function() {
            self.pushSimple('\\n');
          },
          text: function(v) {
            self.pushSimple(v);
          }
        });
        return g;
      }
    },
    {
      name: 'out',
      factory: function() { return []; }
    },
    {
      name: 'simple',
      value: true
    },
    {
      name: 'ps',
      factory: function() {
        return this.StringPS.create();
      }
    }
  ],

  methods: [
    function push() {
      this.simple = false;
      this.pushSimple.apply(this, arguments);
    },

    function pushSimple() {
      this.out.push.apply(this.out, arguments);
    },

    function compile(t, name, args) {
      var result = this.grammar.parseString(t);
      if ( ! result ) throw "Error parsing template " + name;

      var code = this.HEADER +
          ( result[0] ? t : result[1] )
          + this.FOOTER;

      var args = ['opt_outputter'].concat(args);
      var f = eval(
        '(function() { ' +
          'var TOC = function(o) { return foam.templates.TemplateOutput.create(); };' +
          'var f = function(' + args.join(',') + '){' + code + '};' +
          'return function() { '+
          'if ( arguments.length && arguments[0] && ! arguments[0].output ) return f.apply(this, [undefined].concat(Array.from(arguments)));' +
          'return f.apply(this, arguments);};})()');

      return f;
    },

    function lazyCompile(t, name, args) {
      return (function(util) {
        var delegate;
        return function() {
          if ( ! delegate ) delegate = util.compile(t, name, args)
          return delegate.apply(this, arguments);
        };
      })(this);
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateAxiom',
  extends: 'Method',

  properties: [
    'name',
    {
      name: 'template',
      class: 'String'
    },
    'args'
  ],

  methods: [
    function installInProto(proto) {
      proto[this.name] =
        foam.templates.TemplateUtil.create().lazyCompile(this.template, this.name, this.args || []);
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateExtension',
  refines: 'foam.core.Model',

  properties: [
    {
      name: 'templates',
      class: 'AxiomArray',
      of: 'foam.templates.TemplateAxiom',
      adaptArrayElement: function(o, prop) {
        return foam.lookup(prop.of).create(o);
      }
    }
  ]
});
<commit_msg>Made template 'code' not be required.<commit_after>/*
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateOutput',

  properties: [
    {
      name: 'buf',
      factory: function() { return []; }
    }
  ],

  methods: [
    function output() {
      for ( var i = 0 ; i < arguments.length ; i++ ) {
        var o = arguments[i];

        if ( typeof o === 'object' ) {
          this.buf.push(o.toString());
        } else {
          this.buf.push(o);
        }
      }
    },

    function toString() {
      return this.buf.length == 0 ? '' :
        this.buf.length == 1 ? this.buf[0] :
        this.buf.join('');
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateUtil',

  axioms: [foam.pattern.Singleton.create()],

  requires: [
    'foam.parse.StringPS',
    'foam.parse.ImperativeGrammar as Grammar'
  ],

  constants: {
    HEADER: 'var self = this, ctx = this.__context__, Y = this.__subContext__;\n' +
      'var output = opt_outputter ? opt_outputter : TOC(this);\n' +
      'var out = output.output.bind(output);\n' +
      "out('",
    FOOTER: "');\nreturn opt_outputter ? output : output.toString();\n"
  },

  properties: [
    {
      name: 'grammar',
      factory: function() {
        var g = this.Grammar.create({
          symbols: function(repeat0, simpleAlt, sym, seq1, seq, repeat, notChars, anyChar, not, optional, literal) {
            return {
              START: sym('markup'),

              markup: repeat0(simpleAlt(
                sym('comment'),
                sym('simple value'),
                sym('raw values tag'),
                sym('code tag'),
                sym('ignored newline'),
                sym('newline'),
                sym('single quote'),
                sym('text')
              )),

              'comment': seq1(1, '<!--', repeat0(not('-->', anyChar())), '-->'),

              'simple value': seq('%%', repeat(notChars(' ()-"\r\n><:;,')), optional('()')),

              'raw values tag': simpleAlt(
                seq('<%=', repeat(not('%>', anyChar())), '%>')
              ),

              'code tag': seq('<%', repeat(not('%>', anyChar())), '%>'),
              'ignored newline': simpleAlt(
                literal('\\\r\\\n'),
                literal('\\\n')
              ),
              newline: simpleAlt(
                literal('\r\n'),
                literal('\n')
              ),
              'single quote': literal("'"),
              text: anyChar()
            }
          }
        });
        var self = this;
        g.addActions({
          markup: function(v) {
            var wasSimple = self.simple;
            var ret = wasSimple ? null : self.out.join('');
            self.out = [];
            self.simple = true;
            return [wasSimple, ret];
          },
          'simple value': function(v) {
            self.push("',\n self.",
                      v[1].join(''),
                      v[2],
                      ",\n'");
          },
          'raw values tag': function (v) {
            self.push("',\n",
                      v[1].join(''),
                      ",\n'");
          },
          'code tag': function (v) {
            self.push("');\n",
                      v[1].join(''),
                      ";out('");
          },
          'single quote': function() {
            self.pushSimple("\\'");
          },
          newline: function() {
            self.pushSimple('\\n');
          },
          text: function(v) {
            self.pushSimple(v);
          }
        });
        return g;
      }
    },
    {
      name: 'out',
      factory: function() { return []; }
    },
    {
      name: 'simple',
      value: true
    },
    {
      name: 'ps',
      factory: function() {
        return this.StringPS.create();
      }
    }
  ],

  methods: [
    function push() {
      this.simple = false;
      this.pushSimple.apply(this, arguments);
    },

    function pushSimple() {
      this.out.push.apply(this.out, arguments);
    },

    function compile(t, name, args) {
      var result = this.grammar.parseString(t);
      if ( ! result ) throw "Error parsing template " + name;

      var code = this.HEADER +
          ( result[0] ? t : result[1] )
          + this.FOOTER;

      var args = ['opt_outputter'].concat(args);
      var f = eval(
        '(function() { ' +
          'var TOC = function(o) { return foam.templates.TemplateOutput.create(); };' +
          'var f = function(' + args.join(',') + '){' + code + '};' +
          'return function() { '+
          'if ( arguments.length && arguments[0] && ! arguments[0].output ) return f.apply(this, [undefined].concat(Array.from(arguments)));' +
          'return f.apply(this, arguments);};})()');

      return f;
    },

    function lazyCompile(t, name, args) {
      return (function(util) {
        var delegate;
        return function() {
          if ( ! delegate ) delegate = util.compile(t, name, args)
          return delegate.apply(this, arguments);
        };
      })(this);
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateAxiom',
  extends: 'Method',

  properties: [
    {
      name: 'template',
      class: 'String'
    },
    { name: 'code', required: false },
    'args'
  ],

  methods: [
    function installInProto(proto) {
      proto[this.name] =
        foam.templates.TemplateUtil.create().lazyCompile(this.template, this.name, this.args || []);
    }
  ]
});

foam.CLASS({
  package: 'foam.templates',
  name: 'TemplateExtension',
  refines: 'foam.core.Model',

  properties: [
    {
      name: 'templates',
      class: 'AxiomArray',
      of: 'foam.templates.TemplateAxiom',
      adaptArrayElement: function(o, prop) {
        return foam.lookup(prop.of).create(o);
      }
    }
  ]
});
<|endoftext|>