<commit_before>var matchFBO     = require('../../lib/match-fbo')
var conway       = require('conway-hart')
var throttle     = require('frame-debounce')
var fit          = require('canvas-fit')
var getContext   = require('gl-context')
var compare      = require('gl-compare')
var createBuffer = require('gl-buffer')
var createVAO    = require('gl-vao')
var createShader = require('glslify')
var fs           = require('fs')
var now          = require('right-now')
var glm          = require('gl-matrix')
var mat4         = glm.mat4

var container  = document.getElementById('container')
var canvas     = container.appendChild(document.createElement('canvas'))
var readme     = fs.readFileSync(__dirname + '/README.md', 'utf8')
var gl         = getContext(canvas, render)
var comparison = compare(gl, actual, expected)

comparison.mode = 'slide'
comparison.amount = 0.5

require('../common')({
    description: readme
  , compare: comparison
  , canvas: canvas
  , test: matchFBO(comparison, 0.99)
})

window.addEventListener('resize', fit(canvas), false)

//Construct a test polytope
var polytope = conway('I')

var vertexData = []
for(var i=0; i<polytope.cells.length; ++i) {
  var loop = polytope.cells[i]
  for(var j=0; j<loop.length; ++j) {
    vertexData.push.apply(vertexData, polytope.positions[loop[j]])
    vertexData.push.apply(vertexData, polytope.positions[loop[(j+1)%loop.length]])
  }
}

var vertexBuffer = createBuffer(gl, vertexData)
var vertexArray = createVAO(gl, [
  {
    "buffer": vertexBuffer,
    "size": 3
  }])

var actualShader = createShader({
    frag: './shaders/fragment.glsl'
  , vert: process.env.file_transforms_glsl
})(gl)

var expectedShader = createShader({
    frag: './shaders/fragment.glsl'
  , vert: './shaders/vertex.glsl'
})(gl)

function getCamera() {
  var projection = mat4.perspective(
    mat4.create(),
    Math.PI/4.0,
    canvas.width/canvas.height,
    0.0001,
    1000.0)

  var t = now() * 0.0001
  var view = mat4.lookAt(
    mat4.create(),
    [4*Math.cos(t), 4.5, 4*Math.sin(t)],
    [0,0,0],
    [0,1,0])

  var model = mat4.create()
  mat4.rotateX(model, model, t * 2.9 + 0.1)

  console.log(model, view, projection)

  return {
    view: view,
    projection: projection,
    model: model
  }
}

var camera
function render() {
  camera = getCamera()
  comparison.run()
  comparison.render()
}

function actual(fbo) {
  fbo.shape = [canvas.height, canvas.width]
  fbo.bind()
  gl.clear(gl.COLOR_BUFFER_BIT)

  actualShader.bind()
  actualShader.uniforms = camera

  vertexArray.bind()
  vertexArray.draw(gl.LINES, vertexData.length / 3)
}

function expected(fbo) {
  fbo.shape = [canvas.height, canvas.width]
  fbo.bind()
  gl.clear(gl.COLOR_BUFFER_BIT)

  expectedShader.bind()
  expectedShader.uniforms = camera

  vertexArray.bind()
  vertexArray.draw(gl.LINES, vertexData.length / 3)
}<commit_msg>remove console.log<commit_after>var matchFBO     = require('../../lib/match-fbo')
var conway       = require('conway-hart')
var throttle     = require('frame-debounce')
var fit          = require('canvas-fit')
var getContext   = require('gl-context')
var compare      = require('gl-compare')
var createBuffer = require('gl-buffer')
var createVAO    = require('gl-vao')
var createShader = require('glslify')
var fs           = require('fs')
var now          = require('right-now')
var glm          = require('gl-matrix')
var mat4         = glm.mat4

var container  = document.getElementById('container')
var canvas     = container.appendChild(document.createElement('canvas'))
var readme     = fs.readFileSync(__dirname + '/README.md', 'utf8')
var gl         = getContext(canvas, render)
var comparison = compare(gl, actual, expected)

comparison.mode = 'slide'
comparison.amount = 0.5

require('../common')({
    description: readme
  , compare: comparison
  , canvas: canvas
  , test: matchFBO(comparison, 0.99)
})

window.addEventListener('resize', fit(canvas), false)

//Construct a test polytope
var polytope = conway('I')

var vertexData = []
for(var i=0; i<polytope.cells.length; ++i) {
  var loop = polytope.cells[i]
  for(var j=0; j<loop.length; ++j) {
    vertexData.push.apply(vertexData, polytope.positions[loop[j]])
    vertexData.push.apply(vertexData, polytope.positions[loop[(j+1)%loop.length]])
  }
}

var vertexBuffer = createBuffer(gl, vertexData)
var vertexArray = createVAO(gl, [
  {
    "buffer": vertexBuffer,
    "size": 3
  }])

var actualShader = createShader({
    frag: './shaders/fragment.glsl'
  , vert: process.env.file_transforms_glsl
})(gl)

var expectedShader = createShader({
    frag: './shaders/fragment.glsl'
  , vert: './shaders/vertex.glsl'
})(gl)

function getCamera() {
  var projection = mat4.perspective(
    mat4.create(),
    Math.PI/4.0,
    canvas.width/canvas.height,
    0.0001,
    1000.0)

  var t = now() * 0.0001
  var view = mat4.lookAt(
    mat4.create(),
    [4*Math.cos(t), 4.5, 4*Math.sin(t)],
    [0,0,0],
    [0,1,0])

  var model = mat4.create()
  mat4.rotateX(model, model, t * 2.9 + 0.1)

  return {
    view: view,
    projection: projection,
    model: model
  }
}

var camera
function render() {
  camera = getCamera()
  comparison.run()
  comparison.render()
}

function actual(fbo) {
  fbo.shape = [canvas.height, canvas.width]
  fbo.bind()
  gl.clear(gl.COLOR_BUFFER_BIT)

  actualShader.bind()
  actualShader.uniforms = camera

  vertexArray.bind()
  vertexArray.draw(gl.LINES, vertexData.length / 3)
}

function expected(fbo) {
  fbo.shape = [canvas.height, canvas.width]
  fbo.bind()
  gl.clear(gl.COLOR_BUFFER_BIT)

  expectedShader.bind()
  expectedShader.uniforms = camera

  vertexArray.bind()
  vertexArray.draw(gl.LINES, vertexData.length / 3)
}<|endoftext|>


<commit_before>/**
 * @file 创建 text 节点
 * @author errorrik(errorrik@gmail.com)
 */

var each = require('../util/each');
var removeEl = require('../browser/remove-el');
var insertHTMLBefore = require('../browser/insert-html-before');
var createANode = require('../parser/create-a-node');
var ExprType = require('../parser/expr-type');
var pushStrBuffer = require('../runtime/push-str-buffer');
var changeExprCompare = require('../runtime/change-expr-compare');
var nodeInit = require('./node-init');
var NodeType = require('./node-type');
var nodeEvalExpr = require('./node-eval-expr');
var warnSetHTML = require('./warn-set-html');
var isEndStump = require('./is-end-stump');
var isSimpleText = require('./is-simple-text');

/**
 * 创建 text 节点
 *
 * @param {Object} options 初始化参数
 * @param {ANode} options.aNode 抽象信息节点对象
 * @param {Component=} options.owner 所属的组件对象
 * @return {Object}
 */
function createText(options) {
    var node = nodeInit(options);
    node.nodeType = NodeType.TEXT;

    node.attach = textOwnAttach;
    node.dispose = textOwnDispose;
    node._attachHTML = textOwnAttachHTML;
    node._update = textOwnUpdate;

    node._static = node.aNode.textExpr.value;
    node._simple = isSimpleText(node.aNode);

    // #[begin] reverse
    // from el
    if (options.walker) {
        var currentNode = options.walker.current;
        if (node._simple) {
            if (currentNode && currentNode.nodeType === 3) {
                node.el = currentNode;
                options.walker.goNext();
            }
        }
        else {
            /* eslint-disable no-constant-condition */
            while (1) {
                /* eslint-enable no-constant-condition */
                var next = options.elWalker.next;
                if (isEndStump(next, 'text')) {
                    options.elWalker.goNext();
                    removeEl(next);
                    break;
                }

                options.elWalker.goNext();
            }

            removeEl(currentNode);
        }
    }
    // #[end]

    return node;
}

/**
 * 销毁 text 节点
 */
function textOwnDispose() {
    this._prev = null;
    this.el = null;
    this.content = null;
}

/**
 * attach text 节点的 html
 *
 * @param {Object} buf html串存储对象
 */
function textOwnAttachHTML(buf) {
    this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);
    pushStrBuffer(buf, this.content);
}

/**
 * 定位text节点在父元素中的位置
 *
 * @param {Object} node text节点元素
 */
function textLocatePrevNode(node) {
    function getPrev(node) {
        var parentChildren = node.parent.children;
        var len = parentChildren.length;

        while (len--) {
            if (node === parentChildren[len]) {
                return parentChildren[len - 1];
            }
        }
    }

    if (!node._located) {
        var parentBase = node.parent;
        node._prev = getPrev(node);
        while (!node._prev && parentBase
            && (parentBase.nodeType === NodeType.TPL
                || parentBase.nodeType === NodeType.SLOT)
        ) {
            node._prev = getPrev(parentBase);
            parentBase = parentBase.parent;
        }

        node._located = 1;
    }
}

/**
 * 将text attach到页面
 *
 * @param {HTMLElement} parentEl 要添加到的父元素
 * @param {HTMLElement＝} beforeEl 要添加到哪个元素之前
 */
function textOwnAttach(parentEl, beforeEl) {
    this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);

    insertHTMLBefore(this.content, parentEl, beforeEl);
}

/* eslint-disable max-depth */

/**
 * 更新 text 节点的视图
 *
 * @param {Array} changes 数据变化信息
 */
function textOwnUpdate(changes) {
    var me = this;

    var len = changes ? changes.length : 0;
    while (len--) {
        if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
            var text = nodeEvalExpr(this, this.aNode.textExpr, 1);

            if (text !== this.content) {
                this.content = text;
                var rawText = nodeEvalExpr(this, this.aNode.textExpr);

                // 无 stump 元素，所以需要根据组件结构定位
                textLocatePrevNode(me);

                var parentEl = this.parent._getEl();
                if (me._simple) {
                    if (me.el) {
                        me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = rawText;
                    }
                    else {
                        var el = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
                        if (el) {
                            switch (el.nodeType) {
                                case 3:
                                    me.el = el;
                                    me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = rawText;
                                    break;
                                case 1:
                                    el.insertAdjacentHTML('beforebegin', text);
                                    break;
                                default:
                                    me.el = document.createTextNode(text);
                                    parentEl.insertBefore(me.el, el);
                            }
                        }
                        else {
                            parentEl.insertAdjacentHTML('beforeend', text);
                        }
                    }
                }
                else {
                    var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
                    var startRemoveEl = insertBeforeEl;

                    while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
                        insertBeforeEl = startRemoveEl.nextSibling;
                        removeEl(startRemoveEl);
                        startRemoveEl = insertBeforeEl;
                    }

                    // #[begin] error
                    warnSetHTML(parentEl);
                    // #[end]

                    insertHTMLBefore(text, parentEl, insertBeforeEl);
                }
            }

            return;
        }
    }
}

/* eslint-enable max-depth */

exports = module.exports = createText;
<commit_msg>fix complex text reverse bug<commit_after>/**
 * @file 创建 text 节点
 * @author errorrik(errorrik@gmail.com)
 */

var each = require('../util/each');
var removeEl = require('../browser/remove-el');
var insertHTMLBefore = require('../browser/insert-html-before');
var createANode = require('../parser/create-a-node');
var ExprType = require('../parser/expr-type');
var pushStrBuffer = require('../runtime/push-str-buffer');
var changeExprCompare = require('../runtime/change-expr-compare');
var nodeInit = require('./node-init');
var NodeType = require('./node-type');
var nodeEvalExpr = require('./node-eval-expr');
var warnSetHTML = require('./warn-set-html');
var isEndStump = require('./is-end-stump');
var isSimpleText = require('./is-simple-text');

/**
 * 创建 text 节点
 *
 * @param {Object} options 初始化参数
 * @param {ANode} options.aNode 抽象信息节点对象
 * @param {Component=} options.owner 所属的组件对象
 * @return {Object}
 */
function createText(options) {
    var node = nodeInit(options);
    node.nodeType = NodeType.TEXT;

    node.attach = textOwnAttach;
    node.dispose = textOwnDispose;
    node._attachHTML = textOwnAttachHTML;
    node._update = textOwnUpdate;

    node._static = node.aNode.textExpr.value;
    node._simple = isSimpleText(node.aNode);

    // #[begin] reverse
    // from el
    if (options.walker) {
        var currentNode = options.walker.current;
        if (node._simple) {
            if (currentNode && currentNode.nodeType === 3) {
                node.el = currentNode;
                options.walker.goNext();
            }
        }
        else {
            removeEl(currentNode);
            options.walker.goNext();

            while (1) { /* eslint-disable-line */
                currentNode = options.walker.current;
                if (isEndStump(currentNode, 'text')) {
                    options.walker.goNext();
                    removeEl(currentNode);
                    break;
                }

                options.walker.goNext();
            }
        }
    }
    // #[end]

    return node;
}

/**
 * 销毁 text 节点
 */
function textOwnDispose() {
    this._prev = null;
    this.el = null;
    this.content = null;
}

/**
 * attach text 节点的 html
 *
 * @param {Object} buf html串存储对象
 */
function textOwnAttachHTML(buf) {
    this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);
    pushStrBuffer(buf, this.content);
}

/**
 * 定位text节点在父元素中的位置
 *
 * @param {Object} node text节点元素
 */
function textLocatePrevNode(node) {
    function getPrev(node) {
        var parentChildren = node.parent.children;
        var len = parentChildren.length;

        while (len--) {
            if (node === parentChildren[len]) {
                return parentChildren[len - 1];
            }
        }
    }

    if (!node._located) {
        var parentBase = node.parent;
        node._prev = getPrev(node);
        while (!node._prev && parentBase
            && (parentBase.nodeType === NodeType.TPL
                || parentBase.nodeType === NodeType.SLOT)
        ) {
            node._prev = getPrev(parentBase);
            parentBase = parentBase.parent;
        }

        node._located = 1;
    }
}

/**
 * 将text attach到页面
 *
 * @param {HTMLElement} parentEl 要添加到的父元素
 * @param {HTMLElement＝} beforeEl 要添加到哪个元素之前
 */
function textOwnAttach(parentEl, beforeEl) {
    this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);

    insertHTMLBefore(this.content, parentEl, beforeEl);
}

/* eslint-disable max-depth */

/**
 * 更新 text 节点的视图
 *
 * @param {Array} changes 数据变化信息
 */
function textOwnUpdate(changes) {
    var me = this;

    var len = changes ? changes.length : 0;
    while (len--) {
        if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
            var text = nodeEvalExpr(this, this.aNode.textExpr, 1);

            if (text !== this.content) {
                this.content = text;
                var rawText = nodeEvalExpr(this, this.aNode.textExpr);

                // 无 stump 元素，所以需要根据组件结构定位
                textLocatePrevNode(me);

                var parentEl = this.parent._getEl();
                if (me._simple) {
                    if (me.el) {
                        me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = rawText;
                    }
                    else {
                        var el = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
                        if (el) {
                            switch (el.nodeType) {
                                case 3:
                                    me.el = el;
                                    me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = rawText;
                                    break;
                                case 1:
                                    el.insertAdjacentHTML('beforebegin', text);
                                    break;
                                default:
                                    me.el = document.createTextNode(text);
                                    parentEl.insertBefore(me.el, el);
                            }
                        }
                        else {
                            parentEl.insertAdjacentHTML('beforeend', text);
                        }
                    }
                }
                else {
                    var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
                    var startRemoveEl = insertBeforeEl;

                    while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
                        insertBeforeEl = startRemoveEl.nextSibling;
                        removeEl(startRemoveEl);
                        startRemoveEl = insertBeforeEl;
                    }

                    // #[begin] error
                    warnSetHTML(parentEl);
                    // #[end]

                    insertHTMLBefore(text, parentEl, insertBeforeEl);
                }
            }

            return;
        }
    }
}

/* eslint-enable max-depth */

exports = module.exports = createText;
<|endoftext|>


<commit_before>(function(red, $) {
var cjs = red.cjs, _ = red._;
var origin = window.location.protocol + "//" + window.location.host;

$.widget("red.editor", {

	options: {
		debug_ready: false,
		debug_env: false,
		command_box: false
	}

	, _create: function() {
		if(this.options.command_box) {
			this.command_box = $("<input />")	.prependTo(this.element.parent())
												.focus()
												.on("keydown", _.bind(function(event) {
													if(event.keyCode === 13) {
														var val = this.command_box.val();
														this.command_box.val("");
														this.on_input_command(val);
													}
												}, this));
		}

		this.env = red.create("environment");
		if(this.option("debug_env")) {
			window.env = this.env;
		}
		var root_pointer = this.env.get_root_pointer();
		this.root = root_pointer.root();
		this.element.dom_output({
			root: root_pointer
		});

		this.client_socket = new red.ProgramStateClient({
			ready_func: this.option("debug_ready")
		}).on("message", function(data) {
			if(data.type === "color") {
				var color = data.value;
				$("html").css({
					"border-bottom": "10px solid " + color,
					height: "100%",
					"box-sizing": "border-box"
				});
			}
		}, this).on("root_loaded", function(root) {
			this.root.set("external_root", root, {literal: true});
			this.root.set("external_root_pointer", red.create("pointer", {stack: [root]}), {literal: true});
			this.load_viewer();
			window.eenv = this.client_socket.get_external_env();
		}, this);
	}

	, load_viewer: function() {
		this.env

// ===== BEGIN EDITOR =====

.top()
.set("stringify_value", "function(v) {\n" +
"if(red._.isUndefined(v)) { return '(undefined)'; }\n" +
"else if(red._.isNull(v)) { return '(null)'; }\n" +
"else if(red._.isNumber(v) || red._.isBoolean(v)) { return v+''; }\n" +
"else if(red._.isString(v)) { return '\"' + v + '\"'; }\n" +
"else if(red._.isFunction(v)) { return '(func)'; }\n" +
"return v;\n" +
"\n" +
"}")
.set("ambiguous_view", "<stateful>")
.cd("ambiguous_view")
	.set("(protos)", "INIT", "(obj instanceof red.Dict ? [dict_view] : (obj instanceof red.Cell ? [cell_view] : []))")
	.set("obj", "INIT", "pointer ? pointer.points_at() : false")
	.up()
.set("cell_view", "<stateful>")
.cd("cell_view")
	.set("(protos)", "INIT", "[dom]")
	.set("text")
	.set("text", "INIT", "'cell'")
	.up()
.set("stateful_prop_view", "<stateful>")
.cd("stateful_prop_view")
	.set("(protos)", "INIT", "[dom]")
	.set("text")
	.set("text", "INIT", "'stateful prop'")
	.up()
.set("dict_view", "<stateful>")
.cd("dict_view")
	.set("(protos)", "INIT", "[dom]")
	.set("dict", "INIT", "pointer.points_at()")
	.set("children", "<dict>")
	.cd("children")
		.set("child_view", "<stateful>")
		.cd("child_view")
			.set("(manifestations)", "dict.get_prop_names(pointer)")
			.set("(protos)", "INIT", "[dom]")
			.set("name", "INIT", "basis")
			.set("value", "INIT", "dict.prop_val(name, pointer)")
			.set("prop_pointer", "INIT", "dict.get_prop_pointer(name, pointer)")
			.set("children", "<dict>")
			.cd("children")
				.set("prop_name_view", "<stateful>")
				.cd("prop_name_view")
					.set("(protos)", "INIT", "[dom]")
					.set("tag", "<stateful_prop>")
					.set("tag", "INIT", "'span'")
					.set("text", "<stateful_prop>")
					.set("text", "INIT", "name")
					.set("attr", "<dict>")
					.cd("attr")
						.set("class", "INIT", "'prop_name'")
						.up()
					.up()
				.set("prop_value_view", "<stateful>")
				.cd("prop_value_view")
					.set("(protos)", "INIT", "[dom]")
					.set("tag", "<stateful_prop>")
					.set("tag", "INIT", "'span'")
					.set("text", "<stateful_prop>")
					.set("text", "INIT", "stringify_value(value)")
					.set("attr", "<dict>")
					.cd("attr")
						.set("class", "INIT", "'prop_value'")
						.up()
					.up()
				.set("prop_src_view", "<stateful>")
				.cd("prop_src_view")
					.set("pointer", "<stateful_prop>")
					.set("pointer", "INIT", "prop_pointer")
					.set("(protos)", "INIT", "[ambiguous_view]")
					.up()
				.up()
			.up()
		.up()
	.up()
.cd("children")
	.set("obj", "<stateful>")
	.cd("obj")
		.set("pointer", "<stateful_prop>")
		.set("pointer", "INIT", "external_root_pointer")
		.set("(protos)", "INIT", "ambiguous_view")
		.up()
	.up()
;

// ===== END EDITOR =====
		if(this.option("debug_env")) {
			this.env.print_on_return = true;
		}
	}

	, _destroy: function() {
		this.remove_message_listener();
		this.client_socket.destroy();
		if(this.command_box) {
			this.command_box.remove();
		}
	}

	, on_input_command: function(value) {
		var tokens = aware_split(value).map(function(token) {
			return token.trim();
		});
		var command;
		if((["undo", "redo", "reset"]).indexOf(tokens[0]) >= 0) {
			command = tokens[0];
			this.client_socket.post_command(command);
		} else {
			var external_env = this.client_socket.get_external_env();
			command = external_env[tokens[0]].apply(external_env, _.rest(tokens));
			if(command instanceof red.Command) {
				this.client_socket.post_command(command);
			}
		}
	}
});

}(red, jQuery));
<commit_msg>Tweaking the editor<commit_after>(function(red, $) {
var cjs = red.cjs, _ = red._;
var origin = window.location.protocol + "//" + window.location.host;

$.widget("red.editor", {

	options: {
		debug_ready: false,
		debug_env: false,
		command_box: false
	}

	, _create: function() {
		if(this.options.command_box) {
			this.command_box = $("<input />")	.prependTo(this.element.parent())
												.focus()
												.on("keydown", _.bind(function(event) {
													if(event.keyCode === 13) {
														var val = this.command_box.val();
														this.command_box.val("");
														this.on_input_command(val);
													}
												}, this));
		}

		this.env = red.create("environment");
		if(this.option("debug_env")) {
			window.env = this.env;
		}
		var root_pointer = this.env.get_root_pointer();
		this.root = root_pointer.root();
		this.element.dom_output({
			root: root_pointer
		});

		this.client_socket = new red.ProgramStateClient({
			ready_func: this.option("debug_ready")
		}).on("message", function(data) {
			if(data.type === "color") {
				var color = data.value;
				$("html").css({
					"border-bottom": "10px solid " + color,
					height: "100%",
					"box-sizing": "border-box"
				});
			}
		}, this).on("root_loaded", function(root) {
			this.root.set("external_root", root, {literal: true});
			this.root.set("external_root_pointer", red.create("pointer", {stack: [root]}), {literal: true});
			this.load_viewer();
			window.eenv = this.client_socket.get_external_env();
		}, this);
	}

	, load_viewer: function() {
		this.env

// ===== BEGIN EDITOR =====

.top()
.set("stringify_value", "function(v) {\n" +
"if(red._.isUndefined(v)) { return '(undefined)'; }\n" +
"else if(red._.isNull(v)) { return '(null)'; }\n" +
"else if(red._.isNumber(v) || red._.isBoolean(v)) { return v+''; }\n" +
"else if(red._.isString(v)) { return '\"' + v + '\"'; }\n" +
"else if(red._.isFunction(v)) { return '(func)'; }\n" +
"return v;\n" +
"\n" +
"}")
.set("ambiguous_view", "<stateful>")
.cd("ambiguous_view")
	.set("(protos)", "INIT", "(obj instanceof red.Dict ? [dict_view] : (obj instanceof red.Cell ? [cell_view] : []))")
	.set("obj", "INIT", "pointer ? pointer.points_at() : false")
	.up()
.set("cell_view", "<stateful>")
.cd("cell_view")
	.set("(protos)", "INIT", "[dom]")
	.set("text")
	.set("text", "INIT", "'cell'")
	.up()
.set("stateful_prop_view", "<stateful>")
.cd("stateful_prop_view")
	.set("(protos)", "INIT", "[dom]")
	.set("text")
	.set("text", "INIT", "'stateful prop'")
	.up()
.set("dict_view", "<stateful>")
.cd("dict_view")
	.set("(protos)", "INIT", "[dom]")
	.set("dict", "INIT", "pointer.points_at()")
	.set("children", "<dict>")
	.cd("children")
		.set("child_view", "<stateful>")
		.cd("child_view")
			.set("(manifestations)", "dict.get_prop_names(pointer)")
			.set("(protos)", "INIT", "[dom]")
			.set("name", "INIT", "basis")
			.set("value", "INIT", "dict.prop_val(name, pointer)")
			.set("prop_pointer", "INIT", "dict.get_prop_pointer(name, pointer)")
			.set("children", "<dict>")
			.cd("children")
				.set("prop_name_view", "<stateful>")
				.cd("prop_name_view")
					.set("(protos)", "INIT", "[dom]")
					.set("tag", "<stateful_prop>")
					.set("tag", "INIT", "'span'")
					.set("text", "<stateful_prop>")
					.set("text", "INIT", "name")
					.set("attr", "<dict>")
					.cd("attr")
						.set("class", "INIT", "'prop_name'")
						.up()
					.up()
				.set("prop_value_view", "<stateful>")
				.cd("prop_value_view")
					.set("(protos)", "INIT", "[dom]")
					.set("tag", "<stateful_prop>")
					.set("tag", "INIT", "'span'")
					.set("text", "<stateful_prop>")
					.set("text", "INIT", "stringify_value(value)")
					.set("attr", "<dict>")
					.cd("attr")
						.set("class", "INIT", "'prop_value'")
						.up()
					.up()
				.set("prop_src_view", "<stateful>")
				.cd("prop_src_view")
					.set("pointer", "<stateful_prop>")
					.set("pointer", "INIT", "parent.parent.prop_pointer")
					.set("(protos)", "INIT", "[ambiguous_view]")
					.set("text")
					.set("text", "INIT", "pointer")
					.up()
				.up()
			.up()
		.up()
	.up()
.cd("children")
	.set("obj", "<stateful>")
	.cd("obj")
		.set("pointer", "<stateful_prop>")
		.set("pointer", "INIT", "external_root_pointer")
		.set("(protos)", "INIT", "ambiguous_view")
		.up()
	.up()
;

// ===== END EDITOR =====
		if(this.option("debug_env")) {
			this.env.print_on_return = true;
		}
	}

	, _destroy: function() {
		this.remove_message_listener();
		this.client_socket.destroy();
		if(this.command_box) {
			this.command_box.remove();
		}
	}

	, on_input_command: function(value) {
		var tokens = aware_split(value).map(function(token) {
			return token.trim();
		});
		var command;
		if((["undo", "redo", "reset"]).indexOf(tokens[0]) >= 0) {
			command = tokens[0];
			this.client_socket.post_command(command);
		} else {
			var external_env = this.client_socket.get_external_env();
			command = external_env[tokens[0]].apply(external_env, _.rest(tokens));
			if(command instanceof red.Command) {
				this.client_socket.post_command(command);
			}
		}
	}
});

}(red, jQuery));
<|endoftext|>


<commit_before>import React                    from 'react';
import { bindActionCreators }   from 'redux';
import { connect }              from 'react-redux';
import OrderCreate              from '../components/OrderCreate';
import DrinkList                from '../components/DrinkList';
import DrinkListExport          from '../components/DrinkListExport';
import DrinkForm                from '../components/DrinkForm';
import actionCreators           from '../actions';

const mapStateToProps = (state) => ({
  drinks        : state.drinks
});
const mapDispatchToProps = (dispatch) => ({
  actions : bindActionCreators(actionCreators, dispatch)
});

export class DrinksView extends React.Component {
  static propTypes = {
    drinks  : React.PropTypes.array,
    actions : React.PropTypes.object
  }

  render () {
    const { drinks, actions, ...other } = this.props;
    return (

getra:nce soll bestand

              <DrinkList drinks={drinks} actions={actions} />

<OrderCreate drinks={drinks} onCreateClick={actions.createOrder} />

<DrinkListExport drinks={drinks} />

<DrinkForm onAddClick={actions.addDrink} />

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(DrinksView);
<commit_msg>order: open button added<commit_after>import React                    from 'react';
import { bindActionCreators }   from 'redux';
import { connect }              from 'react-redux';
import OrderOpen                from '../components/OrderOpen';
import DrinkList                from '../components/DrinkList';
import DrinkListExport          from '../components/DrinkListExport';
import DrinkForm                from '../components/DrinkForm';
import actionCreators           from '../actions';

const mapStateToProps = (state) => ({
  drinks        : state.drinks
});
const mapDispatchToProps = (dispatch) => ({
  actions : bindActionCreators(actionCreators, dispatch)
});

export class DrinksView extends React.Component {
  static propTypes = {
    drinks  : React.PropTypes.array,
    actions : React.PropTypes.object
  }

  render () {
    const { drinks, actions, ...other } = this.props;
    return (

getra:nce soll bestand

              <DrinkList drinks={drinks} actions={actions} />

<OrderOpen drinks={drinks} onOpenClick={actions.openOrder} />

<DrinkListExport drinks={drinks} />

<DrinkForm onAddClick={actions.addDrink} />

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(DrinksView);
<|endoftext|>


<commit_before>import React from 'react';

const RecipePage = ({
  name,
  ingredients
}) => (

Nom : {name}

ings : {ingredients}

);

export default RecipePage;
<commit_msg>WIP: RecipePage.js, build is failing, fix tomorrow<commit_after>import React from 'react';

const RecipePage = ({
  name,
  ingredients,
  steps,
  desc,
  note,
  editable
}) => (

      {name}

      {desc ?

          {desc}

 :
        ''
      }
      <RecipeItemList

      />

      <RecipeItemList

      />
      {note ?

          {note}

 :
        ''
      }

);

export default RecipePage;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

// ********************************************************************************************* //
// GCLI

var scope = {};

try
{
    Cu.import("resource:///modules/devtools/gcli.jsm", scope);
}
catch (err)
{
    if (FBTrace.DBG_ERROR)
        FBTrace.sysout("GCLI not available");
}

if (scope.gcli) {

// ********************************************************************************************* //
// Services

var Locale = Cu.import("resource://firebug/locale.js").Locale;

// ********************************************************************************************* //
// Command Implementation

var FirebugController =
{
    openFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.toggleBar(true);
        });
    },

    hideFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.minimizeBar();
        });
    },

    closeFirebug: function(args, context)
    {
        var Firebug = context.environment.chromeDocument.defaultView.Firebug;
        if (!Firebug)
            return;

        if (!Firebug.isLoaded)
            return;

        this.startFirebug(context, function(Firebug) {
            Firebug.closeFirebug();
        });
    },

    detachFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.toggleDetachBar(true);
        });
    },

    attachFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            if (Firebug.isDetached())
                Firebug.toggleDetachBar();
            Firebug.toggleBar(true);
        });
    },

    startFirebug: function(context, callback)
    {
        var Firebug = context.environment.chromeDocument.defaultView.Firebug;
        if (!Firebug)
            return;

        Firebug.GlobalUI.startFirebug(function(Firebug) {
            callback(Firebug);
        });
    },
}

// ********************************************************************************************* //
// Registration

scope.gcli.addCommand({
    name: "firebug",
    description: "Web Development Evolved"
});

scope.gcli.addCommand({
    name: "firebug open",
    description: Locale.$STR("firebug.menu.tip.Open_Firebug"),
    exec: FirebugController.openFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug hide",
    description: Locale.$STR("firebug.menu.tip.Minimize_Firebug"),
    exec: FirebugController.hideFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug close",
    description: Locale.$STR("firebug.shortcut.tip.closeFirebug"),
    exec: FirebugController.closeFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug detach",
    description: Locale.$STR("firebug.DetachFirebug"),
    exec: FirebugController.detachFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug attach",
    description: Locale.$STR("firebug.AttachFirebug"),
    exec: FirebugController.attachFirebug.bind(FirebugController)
});

// ********************************************************************************************* //
}
<commit_msg>Just a comment<commit_after>/* See license.txt for terms of usage */

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

// ********************************************************************************************* //
// GCLI

var scope = {};

try
{
    Cu.import("resource:///modules/devtools/gcli.jsm", scope);
}
catch (err)
{
    if (FBTrace.DBG_ERROR)
        FBTrace.sysout("GCLI not available");
}

if (scope.gcli) {

// ********************************************************************************************* //
// Services

var Locale = Cu.import("resource://firebug/locale.js").Locale;

// ********************************************************************************************* //
// Command Implementation

/**
 * Read https://developer.mozilla.org/en/Tools/GCLI/Writing_GCLI_Commands
 * about how to implement GCLI comands.
 */
var FirebugController =
{
    openFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.toggleBar(true);
        });
    },

    hideFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.minimizeBar();
        });
    },

    closeFirebug: function(args, context)
    {
        var Firebug = context.environment.chromeDocument.defaultView.Firebug;
        if (!Firebug)
            return;

        if (!Firebug.isLoaded)
            return;

        this.startFirebug(context, function(Firebug) {
            Firebug.closeFirebug();
        });
    },

    detachFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            Firebug.toggleDetachBar(true);
        });
    },

    attachFirebug: function(args, context)
    {
        this.startFirebug(context, function(Firebug) {
            if (Firebug.isDetached())
                Firebug.toggleDetachBar();
            Firebug.toggleBar(true);
        });
    },

    startFirebug: function(context, callback)
    {
        var Firebug = context.environment.chromeDocument.defaultView.Firebug;
        if (!Firebug)
            return;

        Firebug.GlobalUI.startFirebug(function(Firebug) {
            callback(Firebug);
        });
    },
}

// ********************************************************************************************* //
// Registration

scope.gcli.addCommand({
    name: "firebug",
    description: "Web Development Evolved"
});

scope.gcli.addCommand({
    name: "firebug open",
    description: Locale.$STR("firebug.menu.tip.Open_Firebug"),
    exec: FirebugController.openFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug hide",
    description: Locale.$STR("firebug.menu.tip.Minimize_Firebug"),
    exec: FirebugController.hideFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug close",
    description: Locale.$STR("firebug.shortcut.tip.closeFirebug"),
    exec: FirebugController.closeFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug detach",
    description: Locale.$STR("firebug.DetachFirebug"),
    exec: FirebugController.detachFirebug.bind(FirebugController)
});

scope.gcli.addCommand({
    name: "firebug attach",
    description: Locale.$STR("firebug.AttachFirebug"),
    exec: FirebugController.attachFirebug.bind(FirebugController)
});

// ********************************************************************************************* //
}
<|endoftext|>


<commit_before>import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import { Button, Popover, PopoverHeader, PopoverBody } from "reactstrap";
import { Container, Row, Col } from "reactstrap";
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
  UncontrolledDropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem
} from "reactstrap";

class App extends Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      popoverOpen: false
    };
  }

  toggle() {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    });
  }

  render() {
    return (
      <Container>
        <Row>
          <Col>
            <Navbar color="faded" light expand="md">
              <NavbarBrand href="/">EzMaster</NavbarBrand>
              <NavbarToggler onClick={this.toggle} />
              <Collapse isOpen={this.state.isOpen} navbar>

                  <NavItem>
                    <NavLink href="/components/">Components</NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink href="https://github.com/reactstrap/reactstrap">
                      Github
                    </NavLink>
                  </NavItem>
                  <UncontrolledDropdown nav inNavbar>
                    <DropdownToggle nav caret>
                      Options
                    </DropdownToggle>
                    <DropdownMenu>
                      <DropdownItem>Option 1</DropdownItem>
                      <DropdownItem>Option 2</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Reset</DropdownItem>
                    </DropdownMenu>
                  </UncontrolledDropdown>

              </Collapse>
            </Navbar>
          </Col>
        </Row>

        <Row>
          <Col>

              <Button id="Popover1" onClick={this.toggle}>
                Launch Popover
              </Button>
              <Popover
                placement="bottom"
                isOpen={this.state.popoverOpen}
                target="Popover1"
                toggle={this.toggle}
              >
                <PopoverHeader>Popover Title</PopoverHeader>
                <PopoverBody>
                  Sed posuere consectetur est at lobortis. Aenean eu leo quam.
                  Pellentesque ornare sem lacinia quam venenatis vestibulum.
                </PopoverBody>
              </Popover>

              {/* to test font-awesome with reactjs */}

          </Col>
        </Row>
        <Row>
          <Col>.col</Col>
          <Col>.col</Col>
          <Col>.col</Col>
          <Col>.col</Col>
        </Row>
        <Row>
          <Col xs="3">.col-3</Col>
          <Col xs="auto">.col-auto - variable width content</Col>
          <Col xs="3">.col-3</Col>
        </Row>
        <Row>
          <Col xs="6">.col-6</Col>
          <Col xs="6">.col-6</Col>
        </Row>
        <Row>
          <Col xs="6" sm="4">
            .col-6 .col-sm-4
          </Col>
          <Col xs="6" sm="4">
            .col-6 .col-sm-4
          </Col>
          <Col sm="4">.col-sm-4</Col>
        </Row>
        <Row>
          <Col sm={{ size: 6, order: 2, offset: 1 }}>
            .col-sm-6 .col-sm-order-2 .col-sm-offset-2
          </Col>
        </Row>
        <Row>
          <Col sm="12" md={{ size: 8, offset: 2 }}>
            .col-sm-12 .col-md-6 .col-md-offset-3
          </Col>
        </Row>
        <Row>
          <Col sm={{ size: "auto", offset: 1 }}>.col-sm .col-sm-offset-1</Col>
          <Col sm={{ size: "auto", offset: 1 }}>.col-sm .col-sm-offset-1</Col>
        </Row>
      </Container>
    );
  }
}

export default App;
<commit_msg>prettier<commit_after>import React, { Component } from "react";
import logo from        "./logo.svg";
import "./App.css";
import { Button, Popover, PopoverHeader, PopoverBody } from "reactstrap";
import { Container, Row, Col } from "reactstrap";
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
  UncontrolledDropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem
} from "reactstrap";

class App extends Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      popoverOpen: false
    };
  }

  toggle() {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    });
  }

  render() {
    return (
      <Container>
        <Row>
          <Col>
            <Navbar color="faded" light expand="md">
              <NavbarBrand href="/">EzMaster</NavbarBrand>
              <NavbarToggler onClick={this.toggle} />
              <Collapse isOpen={this.state.isOpen} navbar>

                  <NavItem>
                    <NavLink href="/components/">Components</NavLink>
                  </NavItem>
                  <NavItem>
                    <NavLink href="https://github.com/reactstrap/reactstrap">
                      Github
                    </NavLink>
                  </NavItem>
                  <UncontrolledDropdown nav inNavbar>
                    <DropdownToggle nav caret>
                      Options
                    </DropdownToggle>
                    <DropdownMenu>
                      <DropdownItem>Option 1</DropdownItem>
                      <DropdownItem>Option 2</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Reset</DropdownItem>
                    </DropdownMenu>
                  </UncontrolledDropdown>

              </Collapse>
            </Navbar>
          </Col>
        </Row>

        <Row>
          <Col>

              <Button id="Popover1" onClick={this.toggle}>
                Launch Popover
              </Button>
              <Popover
                placement="bottom"
                isOpen={this.state.popoverOpen}
                target="Popover1"
                toggle={this.toggle}
              >
                <PopoverHeader>Popover Title</PopoverHeader>
                <PopoverBody>
                  Sed posuere consectetur est at lobortis. Aenean eu leo quam.
                  Pellentesque ornare sem lacinia quam venenatis vestibulum.
                </PopoverBody>
              </Popover>

              {/* to test font-awesome with reactjs */}

          </Col>
        </Row>
        <Row>
          <Col>.col</Col>
          <Col>.col</Col>
          <Col>.col</Col>
          <Col>.col</Col>
        </Row>
        <Row>
          <Col xs="3">.col-3</Col>
          <Col xs="auto">.col-auto - variable width content</Col>
          <Col xs="3">.col-3</Col>
        </Row>
        <Row>
          <Col xs="6">.col-6</Col>
          <Col xs="6">.col-6</Col>
        </Row>
        <Row>
          <Col xs="6" sm="4">
            .col-6 .col-sm-4
          </Col>
          <Col xs="6" sm="4">
            .col-6 .col-sm-4
          </Col>
          <Col sm="4">.col-sm-4</Col>
        </Row>
        <Row>
          <Col sm={{ size: 6, order: 2, offset: 1 }}>
            .col-sm-6 .col-sm-order-2 .col-sm-offset-2
          </Col>
        </Row>
        <Row>
          <Col sm="12" md={{ size: 8, offset: 2 }}>
            .col-sm-12 .col-md-6 .col-md-offset-3
          </Col>
        </Row>
        <Row>
          <Col sm={{ size: "auto", offset: 1 }}>.col-sm .col-sm-offset-1</Col>
          <Col sm={{ size: "auto", offset: 1 }}>.col-sm .col-sm-offset-1</Col>
        </Row>
      </Container>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>// ==UserScript==
// @name       fast-forward badge
// @namespace  https://github.com/sinsoku/fastforward_badge
// @version    0.1
// @include    https://github.com/*/pull/*
// ==/UserScript==

function addBadge(enable) {
  var text;
  var tagName = "span";
  var style = "border-radius: 5px;" +
    "display: inline-block;" +
    "margin-top: 3px;" +
    "padding: 1px 3px;";
  var enableStyle = "color: #fff;" +
    "background-color: forestgreen;";
  var disabledStyle = "color: #fff;" +
    "background-color: dimgray;";
  if (enable) {
    text = "fast-forward";
    style += enableStyle;
  } else {
    text = "non-fast forward";
    style += disabledStyle;
  }
  var badge = '<' + tagName + ' style="' + style + '">' + text + '</' + tagName + '>';
  $(".discussion-topic-header").append(badge);
}
var pullreq, baseBranch;
var s = document.location.pathname.split('/');
var owner = s[1];
var repo = s[2];
var number = s[4];
var apiURL = "https://api.github.com/";
$.ajaxSetup({ async: false });

function getPullReq() {
  var url = apiURL + "repos/" + owner + "/" + repo + "/pulls/" + number;
  $.getJSON(url, function(json) { pullreq = json; });
}
function getBaseBranch() {
  var url = apiURL + "repos/" + owner + "/" + repo + "/branches/" + pullreq.base.ref;
  $.getJSON(url, function(json) { baseBranch = json; });
}

function isFastForward() {
  return pullreq.base.sha == baseBranch.commit.sha;
}
function isOpen() {
  return pullreq.state == "open";
}

getPullReq();
getBaseBranch();
if (isOpen()) { addBadge(isFastForward()); }
<commit_msg>fix bug: fast-forward badge was shown always.<commit_after>// ==UserScript==
// @name       fast-forward badge
// @namespace  https://github.com/sinsoku/fastforward_badge
// @version    0.1
// @include    https://github.com/*/pull/*
// ==/UserScript==

function addBadge(enable) {
  var text;
  var tagName = "span";
  var style = "border-radius: 5px;" +
    "display: inline-block;" +
    "margin-top: 3px;" +
    "padding: 1px 3px;";
  var enableStyle = "color: #fff;" +
    "background-color: forestgreen;";
  var disabledStyle = "color: #fff;" +
    "background-color: dimgray;";
  if (enable) {
    text = "fast-forward";
    style += enableStyle;
  } else {
    text = "non-fast forward";
    style += disabledStyle;
  }
  var badge = '<' + tagName + ' style="' + style + '">' + text + '</' + tagName + '>';
  $(".discussion-topic-header").append(badge);
}
var pullreq, commits, baseBranch;
var s = document.location.pathname.split('/');
var owner = s[1];
var repo = s[2];
var number = s[4];
var apiURL = "https://api.github.com/";
$.ajaxSetup({ async: false });

function getPullReq() {
  var url = apiURL + "repos/" + owner + "/" + repo + "/pulls/" + number;
  $.getJSON(url, function(json) { pullreq = json; });
}
function getCommits() {
  var url = apiURL + "repos/" + owner + "/" + repo + "/pulls/" + number + "/commits";
  $.getJSON(url, function(json) { commits = json; });
}
function getBaseBranch() {
  var url = apiURL + "repos/" + owner + "/" + repo + "/branches/" + pullreq.base.ref;
  $.getJSON(url, function(json) { baseBranch = json; });
}

function isFastForward() {
  return commits[0].parents[0].sha == baseBranch.commit.sha;
}
function isOpen() {
  return pullreq.state == "open";
}

getPullReq();
getCommits();
getBaseBranch();
if (isOpen()) { addBadge(isFastForward()); }
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import Dimensions from 'Dimensions';

import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  NavigatorIOS,
  TouchableWithoutFeedback,
  ListView,
  View,
  Image
} from 'react-native';

var screenHeight = Dimensions.get('window').height;
var screenWidth  = Dimensions.get('window').width;
var result = [];
var addressImage = "http://api.map.baidu.com/images/weather/night/duoyun.png";
var dataSource
var DetailPage = React.createClass({

getInitialState: function() {
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });
    return {
      dataSource: ds.cloneWithRows(result),
    };
  },

componentWillMount(){
  // this._onFetchAddressImage(this.props.text);
	this._onFetch(this.props.text);
},

componentDidMount(){
},

_reloadLiveViewData: function(datas) {
  var newDataSource = this.state.dataSource.cloneWithRows(datas);
  this.setState({
    dataSource: newDataSource,
  });
},

render() {
    return (
     <View style={styles.container}>
     <Image source = {{uri:"http://img.secretchina.com/dat/media/25/2015/05/27/20150527092249819.jpg"}} style={{width:screenWidth,height:screenHeight}}>
     <View
     automaticallyAdjustContentInsets={true}
     style={styles.header}>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:22,paddingBottom:10}}>{this.props.text}</Text>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:14,paddingBottom:10}}>时区:"Asia/Shanghai"</Text>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:14}}>Time_offset:"+08:00"</Text>
     </View>
     <ListView
            automaticallyAdjustContentInsets={false}
            dataSource  ={this.state.dataSource}
            renderRow   ={this._renderRow}
            />
      </Image>
    </View>
    );
  },

_onFetch(address) {
  // var url = "http://api.map.baidu.com/telematics/v3/weather?location="+address+"&output=json&ak=sZvXrnY0LsGnucNksCdH73dUAre5FKMD";
  var url = "https://api.thinkpage.cn/v3/weather/daily.json?key=o97r0fxvop12o8cx&location="+address+"&language=zh-Hans&unit=c&start=0&days=5"
	fetch(url)
			.then((response) => response.text())
			.then((responseText) => {
  				var arr_from_json = JSON.parse(responseText);
  				result = arr_from_json.results[0].daily;
          this._reloadLiveViewData(result);

			})
			.catch((error) => {
        alert("onFecth"+error);
  			console.warn(url);
			});
},

_onFetchAddressImage(address){
var addressImageURL = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word="+address+"&cg=star&pn=0&rn=5&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=3c"
fetch(addressImageURL)
    .then((response) => response.text())
    .then((responseText) => {
        addressData = JSON.parse(responseText);
        this._reloadLiveViewData(result);
    })
    .catch((error) => {
      alert("onFetchAddressImage"+error);
      console.warn(url);
    });
},

 _renderRow: function(rowData: string, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) {
	return(
			<TouchableHighlight>
      <View style={styles.row}>
					<View style={styles.cellBox}><Text style={styles.contentTxt}>{result[rowID].date}</Text></View>
          <View style={[styles.cellBox,{flexDirection:'row'}]} >
          <Image source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} style={{width:20,height:20,justifyContent:'center',paddingTop:10}}/>
          <Text style={styles.contentTxt}>{result[rowID].text_day}</Text>
          </View>

          <View style={styles.cellBox}><Text style={styles.contentTxt}>{result[rowID].low}~{result[rowID].high}</Text></View>
      </View>
			</TouchableHighlight>
		);
},

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  header: {
   width:screenWidth,
   height:150,
   paddingTop:65,
   backgroundColor: 'rgba(0,0,0,0)'
  },

  headerContent:{

  },
  bodyContent: {
	 flex:1
  },

  row: {
    flexDirection: 'row',
    padding: 0,
  },

  cellBox: {
    flex :1,
    justifyContent:'center'
  },

  contentTxt:{
  	padding:10,
  	fontSize:16,
  	textAlign: 'center',
    color:"#ffffff",
  }

});
module.exports = DetailPage;
<commit_msg>图片，文字，居中现实<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import Dimensions from 'Dimensions';

import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  NavigatorIOS,
  TouchableWithoutFeedback,
  ListView,
  View,
  Image
} from 'react-native';

var screenHeight = Dimensions.get('window').height;
var screenWidth  = Dimensions.get('window').width;
var result = [];
var addressImage = "http://api.map.baidu.com/images/weather/night/duoyun.png";
var dataSource
var DetailPage = React.createClass({

getInitialState: function() {
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });
    return {
      dataSource: ds.cloneWithRows(result),
    };
  },

componentWillMount(){
  // this._onFetchAddressImage(this.props.text);
	this._onFetch(this.props.text);
},

componentDidMount(){
},

_reloadLiveViewData: function(datas) {
  var newDataSource = this.state.dataSource.cloneWithRows(datas);
  this.setState({
    dataSource: newDataSource,
  });
},

render() {
    return (
     <View style={styles.container}>
     <Image source = {{uri:"http://img.secretchina.com/dat/media/25/2015/05/27/20150527092249819.jpg"}} style={{width:screenWidth,height:screenHeight}}>
     <View
     automaticallyAdjustContentInsets={true}
     style={styles.header}>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:22,paddingBottom:10}}>{this.props.text}</Text>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:14,paddingBottom:10}}>时区:"Asia/Shanghai"</Text>
        <Text style={{backgroundColor: 'rgba(0,0,0,0)',color:"white",textAlign:"center",fontSize:14}}>Time_offset:"+08:00"</Text>
     </View>
     <View style={styles.listView}>
     <ListView
            automaticallyAdjustContentInsets={false}
            dataSource  ={this.state.dataSource}
            renderRow   ={this._renderRow}
            />
    </View>
      </Image>
    </View>
    );
  },

_onFetch(address) {
  var url = "https://api.thinkpage.cn/v3/weather/daily.json?key=o97r0fxvop12o8cx&location="+address+"&language=zh-Hans&unit=c&start=0&days=5"
	fetch(url)
			.then((response) => response.text())
			.then((responseText) => {
  				var arr_from_json = JSON.parse(responseText);
  				result = arr_from_json.results[0].daily;
          this._reloadLiveViewData(result);
			})
			.catch((error) => {
        alert("onFecth"+error);
  			console.warn(url);
			});
},

_onFetchAddressImage(address){
var addressImageURL = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word="+address+"&cg=star&pn=0&rn=5&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=3c"
fetch(addressImageURL)
    .then((response) => response.text())
    .then((responseText) => {
        addressData = JSON.parse(responseText);
        this._reloadLiveViewData(result);
    })
    .catch((error) => {
      alert("onFetchAddressImage"+error);
      console.warn(url);
    });
},

 _renderRow: function(rowData: string, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) {
	return(
			<TouchableHighlight>
      <View style={styles.row}>
					<View style={styles.cellBox}><Text style={styles.contentTxt}>{result[rowID].date}</Text></View>
          <View style={[styles.cellBox]} >
            <Image source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} style={{width:20,height:20,marginRight:10,justifyContent:'flex-start'}}/>
            <Text style={styles.contentTxt}>{result[rowID].text_day}</Text>
          </View>

          <View style={styles.cellBox}><Text style={styles.contentTxt}>{result[rowID].low}~{result[rowID].high}</Text></View>
      </View>
			</TouchableHighlight>
		);
},

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  header: {
   width:screenWidth,
   height:150,
   paddingTop:65,
   backgroundColor: 'rgba(0,0,0,0)'
  },

  headerContent:{

  },
  bodyContent: {
	 flex:1
  },

  row: {
    flexDirection: 'row',
    padding: 0,
  },

  cellBox: {
    flex :1,
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'center',
    height:40,
  },

  listView:{
    width:(screenWidth*0.95),
    marginLeft:screenWidth*0.025,
    backgroundColor:"#333",
    opacity:0.9,
    borderRadius:10,
  },

  contentTxt:{
  	fontSize:16,
  	textAlign: 'center',
    color:"#ffffff",
  }

});
module.exports = DetailPage;
<|endoftext|>


<commit_before>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

var itemsView;
var collectionsView;
var io;
var connectionSelectedDeferred;

/*
 * window takes two arguments:
 * io - used for input/output (dataOut is list of item IDs)
 * sourcesOnly - whether only sources should be shown in the window
 */
var doLoad = Zotero.Promise.coroutine(function* () {
	// Set font size from pref
	var sbc = document.getElementById('zotero-select-items-container');
	Zotero.setFontSize(sbc);

	io = window.arguments[0];
	if(io.wrappedJSObject) io = io.wrappedJSObject;
	if(io.addBorder) document.getElementsByTagName("dialog")[0].style.border = "1px solid black";
	if(io.singleSelection) document.getElementById("zotero-items-tree").setAttribute("seltype", "single");

	setItemsPaneMessage(Zotero.getString('pane.items.loading'));

	collectionsView = new Zotero.CollectionTreeView();
	collectionsView.hideSources = ['duplicates', 'trash', 'feeds'];
	document.getElementById('zotero-collections-tree').view = collectionsView;

	yield collectionsView.waitForLoad();

	connectionSelectedDeferred = Zotero.Promise.defer();
	yield connectionSelectedDeferred.promise;

	if (io.select) {
		yield collectionsView.selectItem(io.select);
	}

	Zotero.updateQuickSearchBox(document);
});

function doUnload()
{
	collectionsView.unregister();
	if(itemsView)
		itemsView.unregister();
}

var onCollectionSelected = Zotero.Promise.coroutine(function* ()
{
	if(itemsView)
		itemsView.unregister();

	if(collectionsView.selection.count == 1 && collectionsView.selection.currentIndex != -1)
	{
		var collectionTreeRow = collectionsView.getRow(collectionsView.selection.currentIndex);
		collectionTreeRow.setSearch('');
		Zotero.Prefs.set('lastViewedFolder', collectionTreeRow.id);

		setItemsPaneMessage(Zotero.getString('pane.items.loading'));

		// Load library data if necessary
		var library = Zotero.Libraries.get(collectionTreeRow.ref.libraryID);
		if (!library.getDataLoaded('item')) {
			Zotero.debug("Waiting for items to load for library " + library.libraryID);
			yield library.waitForDataLoad('item');
		}

		// Create items list and wait for it to load
		itemsView = new Zotero.ItemTreeView(collectionTreeRow, (window.arguments[1] ? true : false));
		document.getElementById('zotero-items-tree').view = itemsView;
		yield itemsView.waitForLoad();

		clearItemsPaneMessage();

		connectionSelectedDeferred.resolve();
		collectionsView.onSelect();
	}
});

function onSearch()
{
	if(itemsView)
	{
		var searchVal = document.getElementById('zotero-tb-search').value;
		itemsView.setFilter('search', searchVal);
	}
}

function onItemSelected()
{
	itemsView.onSelect();
}

function setItemsPaneMessage(content) {
	var elem = document.getElementById('zotero-items-pane-message-box');
	elem.textContent = '';
	if (typeof content == 'string') {
		let contentParts = content.split("\n\n");
		for (let part of contentParts) {
			var desc = document.createElement('description');
			desc.appendChild(document.createTextNode(part));
			elem.appendChild(desc);
		}
	}
	else {
		elem.appendChild(content);
	}
	document.getElementById('zotero-items-pane-content').selectedIndex = 1;
}

function clearItemsPaneMessage() {
	var box = document.getElementById('zotero-items-pane-message-box');
	document.getElementById('zotero-items-pane-content').selectedIndex = 0;
}

function doAccept()
{
	io.dataOut = itemsView.getSelectedItems(true);
}<commit_msg>Fix classic Add Citation dialog after 820755e15<commit_after>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

var itemsView;
var collectionsView;
var io;
var connectionSelectedDeferred;

/*
 * window takes two arguments:
 * io - used for input/output (dataOut is list of item IDs)
 * sourcesOnly - whether only sources should be shown in the window
 */
var doLoad = Zotero.Promise.coroutine(function* () {
	// Set font size from pref
	var sbc = document.getElementById('zotero-select-items-container');
	Zotero.setFontSize(sbc);

	io = window.arguments[0];
	if(io.wrappedJSObject) io = io.wrappedJSObject;
	if(io.addBorder) document.getElementsByTagName("dialog")[0].style.border = "1px solid black";
	if(io.singleSelection) document.getElementById("zotero-items-tree").setAttribute("seltype", "single");

	setItemsPaneMessage(Zotero.getString('pane.items.loading'));

	collectionsView = new Zotero.CollectionTreeView();
	collectionsView.hideSources = ['duplicates', 'trash', 'feeds'];
	document.getElementById('zotero-collections-tree').view = collectionsView;

	yield collectionsView.waitForLoad();

	connectionSelectedDeferred = Zotero.Promise.defer();
	yield connectionSelectedDeferred.promise;

	if (io.select) {
		yield collectionsView.selectItem(io.select);
	}

	Zotero.updateQuickSearchBox(document);
});

function doUnload()
{
	collectionsView.unregister();
	if(itemsView)
		itemsView.unregister();
}

var onCollectionSelected = Zotero.Promise.coroutine(function* ()
{
	if(itemsView)
		itemsView.unregister();

	if(collectionsView.selection.count == 1 && collectionsView.selection.currentIndex != -1)
	{
		var collectionTreeRow = collectionsView.getRow(collectionsView.selection.currentIndex);
		collectionTreeRow.setSearch('');
		Zotero.Prefs.set('lastViewedFolder', collectionTreeRow.id);

		setItemsPaneMessage(Zotero.getString('pane.items.loading'));

		// Load library data if necessary
		var library = Zotero.Libraries.get(collectionTreeRow.ref.libraryID);
		if (!library.getDataLoaded('item')) {
			Zotero.debug("Waiting for items to load for library " + library.libraryID);
			yield library.waitForDataLoad('item');
		}

		// Create items list and wait for it to load
		itemsView = new Zotero.ItemTreeView(collectionTreeRow, (window.arguments[1] ? true : false));
		document.getElementById('zotero-items-tree').view = itemsView;
		yield itemsView.waitForLoad();

		clearItemsPaneMessage();

		connectionSelectedDeferred.resolve();
		collectionsView.runListeners('select');
	}
});

function onSearch()
{
	if(itemsView)
	{
		var searchVal = document.getElementById('zotero-tb-search').value;
		itemsView.setFilter('search', searchVal);
	}
}

function onItemSelected()
{
	itemsView.runListeners('select');
}

function setItemsPaneMessage(content) {
	var elem = document.getElementById('zotero-items-pane-message-box');
	elem.textContent = '';
	if (typeof content == 'string') {
		let contentParts = content.split("\n\n");
		for (let part of contentParts) {
			var desc = document.createElement('description');
			desc.appendChild(document.createTextNode(part));
			elem.appendChild(desc);
		}
	}
	else {
		elem.appendChild(content);
	}
	document.getElementById('zotero-items-pane-content').selectedIndex = 1;
}

function clearItemsPaneMessage() {
	var box = document.getElementById('zotero-items-pane-message-box');
	document.getElementById('zotero-items-pane-content').selectedIndex = 0;
}

function doAccept()
{
	io.dataOut = itemsView.getSelectedItems(true);
}<|endoftext|>


<commit_before>import {h} from 'preact';

import Button from '../../components/Button';
import SideNav from '../../components/SideNav';
import InfoMain from '../../components/InfoMain';
import InfoFooter from '../../components/InfoFooter';
import MainContent from '../../components/MainContent';

const App = () => (

	<SideNav>
		<InfoMain/>
		<InfoFooter/>
	</SideNav>
	<MainContent/>

);

export default App;
<commit_msg>Pass data.json to home page 📟<commit_after>import {h} from 'preact';

import data from '../../data.json';
import SideNav from '../../components/SideNav';
import InfoMain from '../../components/InfoMain';
import InfoFooter from '../../components/InfoFooter';
import MainContent from '../../components/MainContent';

const App = () => (

		<SideNav>
			<InfoMain name={data.name} role={data.role} mail={data.mail}/>
			<InfoFooter/>
		</SideNav>
		<MainContent {...data}/>

);

export default App;
<|endoftext|>


<commit_before>/**
 * VoximaplantClient constructor
 * */
function VoximaplantClient(aLogin_str, aPassword_str, aOptOptions_obj) {
    var lLogin_str = aLogin_str;
    var lPassword_str = aPassword_str;
    var lOptions_obj = {
        micRequired: true,
        progressTone: true,
        progressToneCountry: "RU",
        showDebugInfo: false
    };
    if (aOptOptions_obj && aOptOptions_obj instanceof Object) {
        for (var i in aOptOptions_obj) {
            lOptions_obj[i] = aOptOptions_obj[i];
        }
    }

    /*
     * VoximplantClient aviable statuses
     */
    this.NOT_INTIALIZED = 0;
    this.INTIALIZED = 1;
    this.MIC_VERIFIED = 2;
    this.CONNECTED = 3;
    this.LOGGED_IN = 4;
    this.CONNECTION_CLOSED = 5;

    /*
     * Event fires when calling started
     */
    this.onCallingStartedEvent = null;

    /*
     * Event fires when calling completed
     */
    this.onCallingCompletedEvent = null;

    var lStatus_int = this.NOT_INTIALIZED;
    var lInstance_vx_obj = null;
    var lCall_vx_obj = null;

    if (lStatus_int < this.INTIALIZED) {
        lInstance_vx_obj = VoxImplant.getInstance();
        var self = this;
        lInstance_vx_obj.addEventListener(VoxImplant.Events.SDKReady, function() {
            lStatus_int = self.INTIALIZED;
            lInstance_vx_obj.addEventListener(VoxImplant.Events.MicAccessResult, function(e) {
                if (e.result) {
                    lStatus_int = self.MIC_VERIFIED;
                }
            });
            if (!lInstance_vx_obj.connected()) {
                lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionEstablished, function() {
                    lStatus_int = self.CONNECTED;
                    lInstance_vx_obj.addEventListener(VoxImplant.Events.AuthResult, function(e) {
                        if (e.result) {
                            lStatus_int = self.LOGGED_IN;
                        }
                    });
                    lInstance_vx_obj.login(lLogin_str, lPassword_str);
                });
                lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionClosed, function() {
                    lStatus_int = self.CONNECTION_CLOSED;
                });
                lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionFailed, function() {
                    lStatus_int = self.CONNECTION_CLOSED;
                });
                lInstance_vx_obj.connect();
            }
            lInstance_vx_obj.init(lOptions_obj);
        });
    }

    /*
     * get current status of VoximplantClient
     */
    this.getStatus = function() {
        return lStatus_int;
    };

    /*
     * checks is calling allowed
     */
    this.isCallingAllowed = function() {
        return lStatus_int === self.LOGGED_IN;
    };

    /*
     * call to number
     */
    this.callToNumber = function(aNumber) {
        if (!this.isCallingAllowed() || lCall_vx_obj !== null) {
            return;
        }
        aNumber = aNumber.replace(/[^0-9]/g, '');
        lCall_vx_obj = lInstance_vx_obj.call(aNumber);
        var self = this;
        var closeCallFunc = function() {
            lCall_vx_obj.removeEventListener(VoxImplant.CallEvents.Failed, closeCallFunc);
            lCall_vx_obj.removeEventListener(VoxImplant.CallEvents.Disconnected, closeCallFunc);
            if (lCall_vx_obj.state() !== 'ENDED') {
                llCall_vx_obj.hangup();
            }
            llCall_vx_obj = null;

            if (self.onCallingCompletedEvent && typeof self.onCallingCompletedEvent === 'function') {
                self.onCallingCompletedEvent();
            }
        };
        lCall_vx_obj.addEventListener(VoxImplant.CallEvents.Failed, closeCallFunc);
        lCall_vx_obj.addEventListener(VoxImplant.CallEvents.Disconnected, closeCallFunc);

        if (this.onCallingStartedEvent && typeof this.onCallingStartedEvent === 'function') {
            this.onCallingStartedEvent();
        }
    };

    /*
     * hang up
     */
    this.hangUp = function() {
        if (!this.isCallingAllowed() || lCall_vx_obj === null) {
            return;
        }
        lCall_vx_obj.hangup();
    };
}<commit_msg>VoximplantClient init() method added. Also added onInitializationCompletedEvent event<commit_after>/**
 * VoximaplantClient constructor
 * */
function VoximaplantClient(aLogin_str, aPassword_str, aOptOptions_obj) {
    var lLogin_str = aLogin_str;
    var lPassword_str = aPassword_str;
    var lOptions_obj = {
        micRequired: true,
        progressTone: true,
        progressToneCountry: "RU",
        showDebugInfo: false
    };
    if (aOptOptions_obj && aOptOptions_obj instanceof Object) {
        for (var i in aOptOptions_obj) {
            lOptions_obj[i] = aOptOptions_obj[i];
        }
    }

    /*
     * VoximplantClient aviable statuses
     */
    this.NOT_INTIALIZED = 0;
    this.INTIALIZED = 1;
    this.MIC_VERIFIED = 2;
    this.CONNECTED = 3;
    this.LOGGED_IN = 4;
    this.CONNECTION_CLOSED = 5;

    /*
     * Event fires when calling started
     */
    this.onCallingStartedEvent = null;

    /*
     * Event fires when calling completed
     */
    this.onCallingCompletedEvent = null;

    /*
     * Event fires when VoximplantClient::init() method will be completed
     */
    this.onInitializationCompletedEvent = null;
    var self = this;
    var tryToExecuteInitializationCompletedEventHandler = function() {
        if (self.onInitializationCompletedEvent && typeof self.onInitializationCompletedEvent === 'function') {
            self.onInitializationCompletedEvent();
        }
    };

    var lStatus_int = this.NOT_INTIALIZED;
    var lInstance_vx_obj = null;
    var lCall_vx_obj = null;

    this.init = function () {
        if (lStatus_int < this.INTIALIZED) {
            lInstance_vx_obj = VoxImplant.getInstance();
            var self = this;
            lInstance_vx_obj.addEventListener(VoxImplant.Events.SDKReady, function() {
                lStatus_int = self.INTIALIZED;
                lInstance_vx_obj.addEventListener(VoxImplant.Events.MicAccessResult, function(e) {
                    if (e.result) {
                        lStatus_int = self.MIC_VERIFIED;
                    } else {
                        tryToExecuteInitializationCompletedEventHandler();
                    }
                });
                if (!lInstance_vx_obj.connected()) {
                    lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionEstablished, function() {
                        lStatus_int = self.CONNECTED;
                        lInstance_vx_obj.addEventListener(VoxImplant.Events.AuthResult, function(e) {
                            if (e.result) {
                                lStatus_int = self.LOGGED_IN;
                            }
                            tryToExecuteInitializationCompletedEventHandler();
                        });
                        lInstance_vx_obj.login(lLogin_str, lPassword_str);
                    });
                    lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionClosed, function() {
                        lStatus_int = self.CONNECTION_CLOSED;
                    });
                    lInstance_vx_obj.addEventListener(VoxImplant.Events.ConnectionFailed, function() {
                        lStatus_int = self.CONNECTION_CLOSED;
                        tryToExecuteInitializationCompletedEventHandler();
                    });
                    lInstance_vx_obj.connect();
                }
            });
            lInstance_vx_obj.init(lOptions_obj);
        }
    };

    /*
     * get current status of VoximplantClient
     */
    this.getStatus = function() {
        return lStatus_int;
    };

    /*
     * checks is calling allowed
     */
    this.isCallingAllowed = function() {
        return lStatus_int === self.LOGGED_IN;
    };

    /*
     * call to number
     */
    this.callToNumber = function(aNumber) {
        if (!this.isCallingAllowed() || lCall_vx_obj !== null) {
            return;
        }
        aNumber = aNumber.replace(/[^0-9]/g, '');
        lCall_vx_obj = lInstance_vx_obj.call(aNumber);
        var self = this;
        var closeCallFunc = function() {
            lCall_vx_obj.removeEventListener(VoxImplant.CallEvents.Failed, closeCallFunc);
            lCall_vx_obj.removeEventListener(VoxImplant.CallEvents.Disconnected, closeCallFunc);
            if (lCall_vx_obj.state() !== 'ENDED') {
                llCall_vx_obj.hangup();
            }
            llCall_vx_obj = null;

            if (self.onCallingCompletedEvent && typeof self.onCallingCompletedEvent === 'function') {
                self.onCallingCompletedEvent();
            }
        };
        lCall_vx_obj.addEventListener(VoxImplant.CallEvents.Failed, closeCallFunc);
        lCall_vx_obj.addEventListener(VoxImplant.CallEvents.Disconnected, closeCallFunc);

        if (this.onCallingStartedEvent && typeof this.onCallingStartedEvent === 'function') {
            this.onCallingStartedEvent();
        }
    };

    /*
     * hang up
     */
    this.hangUp = function() {
        if (!this.isCallingAllowed() || lCall_vx_obj === null) {
            return;
        }
        lCall_vx_obj.hangup();
    };
}<|endoftext|>


<commit_before><commit_msg>added pclamp and almostIdentity math utility functions<commit_after><|endoftext|>


<commit_before><commit_msg>Adding blog and twitter link to left navigation for docs<commit_after><|endoftext|>


<commit_before>steal({
	src: "http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js.uncompressed.js",
	_skip: true
}, '../event.js').then(
	'./trigger',
	function(){

	// dojo.js
	// ---------
	// _dojo node list._
	//
	// These are pre-loaded by `steal` -> no callback.
	require(["dojo", "dojo/query", "plugd/trigger", "dojo/NodeList-dom"]);

	// Map string helpers.
	can.trim = function(s){
		return s && dojo.trim(s);
	}

	// Map array helpers.
	can.makeArray = function(arr){
		array = [];
		dojo.forEach(arr, function(item){ array.push(item)});
		return array;
	};
	can.isArray = dojo.isArray;
	can.inArray = function(item,arr){
		return dojo.indexOf(arr, item);
	};
	can.map = function(arr, fn){
		return dojo.map(can.makeArray(arr||[]), fn);
	};
	can.each = function(elements, callback) {
    	var i, key;
	    if (typeof  elements.length == 'number' && elements.pop)
	      for(i = 0; i < elements.length; i++) {
	        if(callback(i, elements[i]) === false) return elements;
	      }
	    else
	      for(key in elements) {
	        if(callback(key, elements[key]) === false) return elements;
	      }
	    return elements;
  	}
	// Map object helpers.
	can.extend = function(first){
		if(first === true){
			var args = can.makeArray(arguments);
			args.shift();
			return dojo.mixin.apply(dojo, args)
		}
		return dojo.mixin.apply(dojo, arguments)
	}
	can.param = function(object){
		return dojo.objectToQuery(object)
	}
	can.isEmptyObject = function(object){
		var prop;
		for(prop in object){
			break;
		}
		return prop === undefined;;
	}
	// Map function helpers.
	can.proxy = function(func, context){
		return dojo.hitch(context, func)
	}
	can.isFunction = function(f){
		return dojo.isFunction(f);
	}
	/**
	 * EVENTS
	 *
	 * Dojo does not use the callback handler when unbinding.  Instead
	 * when binding (dojo.connect or dojo.on) an object with a remove
	 * method is returned.
	 *
	 * Because of this, we have to map each callback to the "remove"
	 * object to it can be passed to dojo.disconnect.
	 */

	// The id of the `function` to be bound, used as an expando on the `function`
	// so we can lookup it's `remove` object.
	var id = 0,
		// Takes a node list, goes through each node
		// and adds events data that has a map of events to
		// callbackId to `remove` object.  It looks like
		// `{click: {5: {remove: fn}}}`.
		addBinding = function( nodelist, ev, cb ) {
			nodelist.forEach(function(node){
				var node = new dojo.NodeList(node)
				var events = can.data(node,"events");
				if(!events){
					can.data(node,"events", events = {})
				}
				if(!events[ev]){
					events[ev] = {};
				}
				if(cb.__bindingsIds === undefined) {
					cb.__bindingsIds=id++;
				}
				events[ev][cb.__bindingsIds] = node.on(ev, cb)[0]
			});
		},
		// Removes a binding on a `nodelist` by finding
		// the remove object within the object's data.
		removeBinding = function(nodelist,ev,cb){
			nodelist.forEach(function(node){
				var node = new dojo.NodeList(node),
					events = can.data(node,"events"),
					handlers = events[ev],
					handler = handlers[cb.__bindingsIds];

				dojo.disconnect(handler);
				delete handlers[cb.__bindingsIds];

				if(can.isEmptyObject(handlers)){
					delete events[ev]
				}
			});
		}

	can.bind = function( ev, cb){
		// If we can bind to it...
		if(this.bind && this.bind !== can.bind){
			this.bind(ev, cb)

		// Otherwise it's an element or `nodeList`.
		} else if(this.on || this.nodeType){
			addBinding( new dojo.NodeList(this), ev, cb)
		} else if(this.addEvent) {
			this.addEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.addEvent.call(this, ev, cb)
		}
		return this;
	}
	can.unbind = function(ev, cb){
		// If we can bind to it...
		if(this.unbind && this.unbind !== can.unbind){
			this.unbind(ev, cb)
		}

		else if(this.on || this.nodeType) {
			removeBinding(new dojo.NodeList(this), ev, cb);
		} else {
			// Make it bind-able...
			can.removeEvent.call(this, ev, cb)
		}
		return this;
	}

	can.trigger = function(item, event, args, bubble){
		if(item.trigger){
			if(bubble === false){
				if(!item[0] || item[0].nodeType === 3){
					return;
				}
				// Force stop propagation by
				// listening to `on` and then immediately disconnecting.
				var connect = item.on(event, function(ev){

					ev.stopPropagation && ev.stopPropagation();
					ev.cancelBubble = true;
					ev._stopper && ev._stopper();

					dojo.disconnect(connect);
				})
				item.trigger(event,args)
			} else {
				item.trigger(event,args)
			}

		} else {
			if(typeof event === 'string'){
				event = {type: event}
			}
			event.data = args
			can.dispatch.call(item, event)
		}
	}

	can.delegate = function(selector, ev , cb){
		if(this.on || this.nodeType){
			addBinding( new dojo.NodeList(this), selector+":"+ev, cb)
		} else if(this.delegate) {
			this.delegate(selector, ev , cb)
		}
		return this;
	}
	can.undelegate = function(selector, ev , cb){
		if(this.on || this.nodeType){
			removeBinding(new dojo.NodeList(this), selector+":"+ev, cb);
		} else if(this.undelegate) {
			this.undelegate(selector, ev , cb)
		}

		return this;
	}

	/**
	 * Ajax
	 */
	var optionsMap = {
		type:"method",
		success : undefined,
		error: undefined
	}
	var updateDeferred = function(xhr, d){
		for(var prop in xhr){
			if(typeof d[prop] == 'function'){
				d[prop] = function(){
					xhr[prop].apply(xhr, arguments)
				}
			} else {
				d[prop] = prop[xhr]
			}
		}
	}

	can.ajax = function(options){
		var type = can.capitalize( (options.type || "get").toLowerCase() ),
			method = dojo["xhr"+type];
		var success = options.success,
			error = options.error,
			d = new can.Deferred();

		var def = method({
			url : options.url,
			handleAs : options.dataType,
			sync : !options.async,
			headers : options.headers,
			content: options.data
		})
		def.then(function(data, ioargs){
			updateDeferred(xhr, d);
			d.resolve(data,"success",xhr);
			success && success(data,"success",xhr);
		},function(data,ioargs){
			updateDeferred(xhr, d);
			d.reject(xhr,"error");
			error(xhr,"error");
		})

		var xhr = def.ioArgs.xhr;

		updateDeferred(xhr, d);
		return d;

	}
	// Element - get the wrapped helper.
	can.$ = function(selector){
		if(selector === window){
			return window;
		}
		if(typeof selector === "string"){
			return dojo.query(selector)
		} else {
			return new dojo.NodeList(selector);
		}

	}
	can.buildFragment = function(frags, nodes){
		var owner = nodes.length && nodes[0].ownerDocument,
			frag = dojo.toDom(frags[0], owner );
		if(frag.nodeType !== 11){
			var tmp = document.createDocumentFragment();
			tmp.appendChild(frag)
			frag = tmp;
		}
		return {fragment: frag}
	}

	can.append = function(wrapped, html){
		return wrapped.forEach(function(node){
			dojo.place( html, node)
		});
	}

	/**
	 * can.data
	 *
	 * can.data is used to store arbitrary data on an element.
	 * Dojo does not support this, so we implement it itself.
	 *
	 * The important part is to call cleanData on any elements
	 * that are removed from the DOM.  For this to happen, we
	 * overwrite
	 *
	 *   -dojo.empty
	 *   -dojo.destroy
	 *   -dojo.place when "replace" is used TODO!!!!
	 *
	 * For can.Control, we also need to trigger a non bubbling event
	 * when an element is removed.  We do this also in cleanData.
	 */
	var data = {},
	    uuid = can.uuid = +new Date(),
	    exp  = can.expando = 'can' + uuid;

	function getData(node, name) {
	    var id = node[exp], store = id && data[id];
	    return name === undefined ? store || setData(node) :
	      (store && store[name]);
	}

	function setData(node, name, value) {
	    var id = node[exp] || (node[exp] = ++uuid),
	      store = data[id] || (data[id] = {});
	    if (name !== undefined) store[name] = value;
	    return store;
	};

	var cleanData = function(elems){
	  	can.trigger(new dojo.NodeList(elems),"destroyed",[],false)
	  	for ( var i = 0, elem;
			(elem = elems[i]) !== undefined; i++ ) {
				var id = elem[exp]
				delete data[id];
			}
	};

	can.data = function(wrapped, name, value){
		return value === undefined ?
			wrapped.length == 0 ? undefined : getData(wrapped[0], name) :
			wrapped.forEach(function(node){
				setData(node, name, value);
			});
	};

	// Overwrite `dojo.destroy`, `dojo.empty` and `dojo.place`.
	var empty = dojo.empty;
	dojo.empty = function(){
		for(var c; c = node.lastChild;){ // Intentional assignment.
			dojo.destroy(c);
		}
	}

	var destroy = dojo.destroy;
	dojo.destroy = function(node){
		node = dojo.byId(node);
		cleanData([node]);
		node.getElementsByTagName && cleanData(node.getElementsByTagName('*'))

		return destroy.apply(dojo, arguments);
	};

	can.addClass = function(wrapped, className){
		return wrapped.addClass(className);
	}

	can.remove = function(wrapped){
		// We need to remove text nodes ourselves.
		wrapped.forEach(dojo.destroy);
	}

	can.get = function(wrapped, index){
		return wrapped[index];
	}

	// Add pipe to `dojo.Deferred`.
	can.extend(dojo.Deferred.prototype, {
		pipe : function(done, fail){
			var d = new dojo.Deferred();
			this.addCallback(function(){
				d.resolve( done.apply(this, arguments) );
			});

			this.addErrback(function(){
				if(fail){
					d.reject( fail.apply(this, arguments) );
				} else {
					d.reject.apply(d, arguments);
				}
			});
			return d;
		}
	});

}).then('../deferred.js')
<commit_msg>Fixing missing target in can.trigger for Dojo<commit_after>steal({
	src: "http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js.uncompressed.js",
	_skip: true
}, '../event.js').then(
	'./trigger',
	function(){

	// dojo.js
	// ---------
	// _dojo node list._
	//
	// These are pre-loaded by `steal` -> no callback.
	require(["dojo", "dojo/query", "plugd/trigger", "dojo/NodeList-dom"]);

	// Map string helpers.
	can.trim = function(s){
		return s && dojo.trim(s);
	}

	// Map array helpers.
	can.makeArray = function(arr){
		array = [];
		dojo.forEach(arr, function(item){ array.push(item)});
		return array;
	};
	can.isArray = dojo.isArray;
	can.inArray = function(item,arr){
		return dojo.indexOf(arr, item);
	};
	can.map = function(arr, fn){
		return dojo.map(can.makeArray(arr||[]), fn);
	};
	can.each = function(elements, callback) {
    	var i, key;
	    if (typeof  elements.length == 'number' && elements.pop)
	      for(i = 0; i < elements.length; i++) {
	        if(callback(i, elements[i]) === false) return elements;
	      }
	    else
	      for(key in elements) {
	        if(callback(key, elements[key]) === false) return elements;
	      }
	    return elements;
  	}
	// Map object helpers.
	can.extend = function(first){
		if(first === true){
			var args = can.makeArray(arguments);
			args.shift();
			return dojo.mixin.apply(dojo, args)
		}
		return dojo.mixin.apply(dojo, arguments)
	}
	can.param = function(object){
		return dojo.objectToQuery(object)
	}
	can.isEmptyObject = function(object){
		var prop;
		for(prop in object){
			break;
		}
		return prop === undefined;;
	}
	// Map function helpers.
	can.proxy = function(func, context){
		return dojo.hitch(context, func)
	}
	can.isFunction = function(f){
		return dojo.isFunction(f);
	}
	/**
	 * EVENTS
	 *
	 * Dojo does not use the callback handler when unbinding.  Instead
	 * when binding (dojo.connect or dojo.on) an object with a remove
	 * method is returned.
	 *
	 * Because of this, we have to map each callback to the "remove"
	 * object to it can be passed to dojo.disconnect.
	 */

	// The id of the `function` to be bound, used as an expando on the `function`
	// so we can lookup it's `remove` object.
	var id = 0,
		// Takes a node list, goes through each node
		// and adds events data that has a map of events to
		// callbackId to `remove` object.  It looks like
		// `{click: {5: {remove: fn}}}`.
		addBinding = function( nodelist, ev, cb ) {
			nodelist.forEach(function(node){
				var node = new dojo.NodeList(node)
				var events = can.data(node,"events");
				if(!events){
					can.data(node,"events", events = {})
				}
				if(!events[ev]){
					events[ev] = {};
				}
				if(cb.__bindingsIds === undefined) {
					cb.__bindingsIds=id++;
				}
				events[ev][cb.__bindingsIds] = node.on(ev, cb)[0]
			});
		},
		// Removes a binding on a `nodelist` by finding
		// the remove object within the object's data.
		removeBinding = function(nodelist,ev,cb){
			nodelist.forEach(function(node){
				var node = new dojo.NodeList(node),
					events = can.data(node,"events"),
					handlers = events[ev],
					handler = handlers[cb.__bindingsIds];

				dojo.disconnect(handler);
				delete handlers[cb.__bindingsIds];

				if(can.isEmptyObject(handlers)){
					delete events[ev]
				}
			});
		}

	can.bind = function( ev, cb){
		// If we can bind to it...
		if(this.bind && this.bind !== can.bind){
			this.bind(ev, cb)

		// Otherwise it's an element or `nodeList`.
		} else if(this.on || this.nodeType){
			addBinding( new dojo.NodeList(this), ev, cb)
		} else if(this.addEvent) {
			this.addEvent(ev, cb)
		} else {
			// Make it bind-able...
			can.addEvent.call(this, ev, cb)
		}
		return this;
	}
	can.unbind = function(ev, cb){
		// If we can bind to it...
		if(this.unbind && this.unbind !== can.unbind){
			this.unbind(ev, cb)
		}

		else if(this.on || this.nodeType) {
			removeBinding(new dojo.NodeList(this), ev, cb);
		} else {
			// Make it bind-able...
			can.removeEvent.call(this, ev, cb)
		}
		return this;
	}

	can.trigger = function(item, event, args, bubble){
		if(item.trigger){
			if(bubble === false){
				if(!item[0] || item[0].nodeType === 3){
					return;
				}
				// Force stop propagation by
				// listening to `on` and then immediately disconnecting.
				var connect = item.on(event, function(ev){

					ev.stopPropagation && ev.stopPropagation();
					ev.cancelBubble = true;
					ev._stopper && ev._stopper();

					dojo.disconnect(connect);
				})
				item.trigger(event,args)
			} else {
				item.trigger(event,args)
			}

		} else {
			if(typeof event === 'string'){
				event = {type: event}
			}
			event.data = args
			event.target = event.target || item;
			can.dispatch.call(item, event)
		}
	}

	can.delegate = function(selector, ev , cb){
		if(this.on || this.nodeType){
			addBinding( new dojo.NodeList(this), selector+":"+ev, cb)
		} else if(this.delegate) {
			this.delegate(selector, ev , cb)
		}
		return this;
	}
	can.undelegate = function(selector, ev , cb){
		if(this.on || this.nodeType){
			removeBinding(new dojo.NodeList(this), selector+":"+ev, cb);
		} else if(this.undelegate) {
			this.undelegate(selector, ev , cb)
		}

		return this;
	}

	/**
	 * Ajax
	 */
	var optionsMap = {
		type:"method",
		success : undefined,
		error: undefined
	}
	var updateDeferred = function(xhr, d){
		for(var prop in xhr){
			if(typeof d[prop] == 'function'){
				d[prop] = function(){
					xhr[prop].apply(xhr, arguments)
				}
			} else {
				d[prop] = prop[xhr]
			}
		}
	}

	can.ajax = function(options){
		var type = can.capitalize( (options.type || "get").toLowerCase() ),
			method = dojo["xhr"+type];
		var success = options.success,
			error = options.error,
			d = new can.Deferred();

		var def = method({
			url : options.url,
			handleAs : options.dataType,
			sync : !options.async,
			headers : options.headers,
			content: options.data
		})
		def.then(function(data, ioargs){
			updateDeferred(xhr, d);
			d.resolve(data,"success",xhr);
			success && success(data,"success",xhr);
		},function(data,ioargs){
			updateDeferred(xhr, d);
			d.reject(xhr,"error");
			error(xhr,"error");
		})

		var xhr = def.ioArgs.xhr;

		updateDeferred(xhr, d);
		return d;

	}
	// Element - get the wrapped helper.
	can.$ = function(selector){
		if(selector === window){
			return window;
		}
		if(typeof selector === "string"){
			return dojo.query(selector)
		} else {
			return new dojo.NodeList(selector);
		}

	}
	can.buildFragment = function(frags, nodes){
		var owner = nodes.length && nodes[0].ownerDocument,
			frag = dojo.toDom(frags[0], owner );
		if(frag.nodeType !== 11){
			var tmp = document.createDocumentFragment();
			tmp.appendChild(frag)
			frag = tmp;
		}
		return {fragment: frag}
	}

	can.append = function(wrapped, html){
		return wrapped.forEach(function(node){
			dojo.place( html, node)
		});
	}

	/**
	 * can.data
	 *
	 * can.data is used to store arbitrary data on an element.
	 * Dojo does not support this, so we implement it itself.
	 *
	 * The important part is to call cleanData on any elements
	 * that are removed from the DOM.  For this to happen, we
	 * overwrite
	 *
	 *   -dojo.empty
	 *   -dojo.destroy
	 *   -dojo.place when "replace" is used TODO!!!!
	 *
	 * For can.Control, we also need to trigger a non bubbling event
	 * when an element is removed.  We do this also in cleanData.
	 */
	var data = {},
	    uuid = can.uuid = +new Date(),
	    exp  = can.expando = 'can' + uuid;

	function getData(node, name) {
	    var id = node[exp], store = id && data[id];
	    return name === undefined ? store || setData(node) :
	      (store && store[name]);
	}

	function setData(node, name, value) {
	    var id = node[exp] || (node[exp] = ++uuid),
	      store = data[id] || (data[id] = {});
	    if (name !== undefined) store[name] = value;
	    return store;
	};

	var cleanData = function(elems){
	  	can.trigger(new dojo.NodeList(elems),"destroyed",[],false)
	  	for ( var i = 0, elem;
			(elem = elems[i]) !== undefined; i++ ) {
				var id = elem[exp]
				delete data[id];
			}
	};

	can.data = function(wrapped, name, value){
		return value === undefined ?
			wrapped.length == 0 ? undefined : getData(wrapped[0], name) :
			wrapped.forEach(function(node){
				setData(node, name, value);
			});
	};

	// Overwrite `dojo.destroy`, `dojo.empty` and `dojo.place`.
	var empty = dojo.empty;
	dojo.empty = function(){
		for(var c; c = node.lastChild;){ // Intentional assignment.
			dojo.destroy(c);
		}
	}

	var destroy = dojo.destroy;
	dojo.destroy = function(node){
		node = dojo.byId(node);
		cleanData([node]);
		node.getElementsByTagName && cleanData(node.getElementsByTagName('*'))

		return destroy.apply(dojo, arguments);
	};

	can.addClass = function(wrapped, className){
		return wrapped.addClass(className);
	}

	can.remove = function(wrapped){
		// We need to remove text nodes ourselves.
		wrapped.forEach(dojo.destroy);
	}

	can.get = function(wrapped, index){
		return wrapped[index];
	}

	// Add pipe to `dojo.Deferred`.
	can.extend(dojo.Deferred.prototype, {
		pipe : function(done, fail){
			var d = new dojo.Deferred();
			this.addCallback(function(){
				d.resolve( done.apply(this, arguments) );
			});

			this.addErrback(function(){
				if(fail){
					d.reject( fail.apply(this, arguments) );
				} else {
					d.reject.apply(d, arguments);
				}
			});
			return d;
		}
	});

}).then('../deferred.js')
<|endoftext|>