<commit_before>var parse = require("pug-parser");
var lex = require("pug-lexer");
var Block = require("./block.js");
var tags = "a abbr address area article aside audio b base bdi bdo big blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd keygen label legend li link main map mark menu menuitem meta meter nav noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track u ul var video wbr circle defs ellipse g line linearGradient mask path pattern polygon polyline radialGradient rect stop svg text tspan".split(" ");

function Compilation(doc,path){
	doc = doc.replace(/\r\n/g,"\n");
    this.path = path;
    this.tree = parse(lex(doc)).nodes;
    this.main = new Block();
    this.mixins = new Block();
    this.script = new Block();
	this.imports = new Block();
	this.members = new Block();
    this.extendblock = new Block();
    this.blocks = new Block();
    this.block = this.main;
    this.blocklist = {};
}

Compilation.prototype = Object.create(Block.prototype);

Compilation.prototype.compile = function(){
    this.deblock(this.tree);
    this.tree.forEach(function(node){
        if(node.type == "Tag" && node.name == "script") node.name = "main";
    })
	this.block.writeLine('"use strict";');
    this.block.writeLine("var React = require(\"react\");");
    this.block.writeLine("var jade2react = require(\"jade2react\");");
	this.block.writeBlock(this.imports);
    this.block.writeLine("");
    this.block.writeBlock(this.extendblock); //start of class
    this.block.indent(1);
    this.block.writeLine("_render(__add){",1);
    this.renderNodes(this.tree,true);
    if(this.extendblock.out.length){
        this.block.writeLine("super._render.call(this,__add);");
    }
    this.block.indent(-1);
    this.block.writeLine("}");
    this.block.writeLine("render(){",1);
    this.block.writeLine("return jade2react.render(this,this._render)[0];",-1);
    this.block.writeLine("}");
    for(var block in this.blocklist){
        var b = this.blocklist[block];
        this.block.writeLine(block+"(__add){",1);
        if(b.prepend){
            this.renderNodes(b.prepend.nodes);
        }
        if(b.replace){
            this.renderNodes(b.replace.nodes);
        }else{
            this.block.writeLine("super."+block+".call(this,__add);");
        }
        if(b.append){
            this.renderNodes(b.append.nodes);
        }
        this.block.indent(-1);
        this.block.writeLine("}");
    }
    if(this.mixins.out.length){
        this.block.writeBlock(this.mixins);
    }
	if(this.members.out.length){
		this.block.writeBlock(this.members);
	}
    this.block.indent(-1);
    this.block.writeLine("}"); //end of class
	this.block.writeLine("module.exports = Component;");
    this.block.writeLine("");
    this.block.writeBlock(this.script);

    if(!this.extendblock.out.length){
        this.renderExtends()
    }

    var code = this.block.build();
    return code;
}

Compilation.prototype.deblock = function(nodes){
    for(var i = 0; i < nodes.length; i++){
        var node = nodes[i];
        if(node.block) node.nodes = node.block.nodes;
        if(node.nodes) this.deblock(node.nodes);
    }
}

Compilation.prototype.renderNode = function(node){
    switch(node.type){
        case "Text":
        case "Code":
        case "Tag":
        case "Block":
        case "Each":
        case "Comment":
        case "BlockComment":
        case "Case":
        case "When":
        case "Mixin":
        case "MixinBlock":
        case "Extends":
        case "NamedBlock":
            this["render"+node.type](node);
            break;
    }
}

Compilation.prototype.renderNodes = function(nodes){
    for(var i = 0; i < nodes.length; i++){
        this.renderNode(nodes[i]);
    }
}

Compilation.prototype.renderText = function(node){
    if(!node.val) return;
    this.block.writeLine("__add(\""+node.val+"\");");
}

Compilation.prototype.renderCode = function(node){
    if(!node.val) return;
    if(node.block){
        this.block.writeLine(node.val+"{",1);
        this.renderNodes(node.block.nodes);
        this.block.indent(-1);
        this.block.writeLine("}");
    }else if(node.buffer){
        this.block.writeLine("__add("+node.val+");");
    }else{
        this.block.writeLine(node.val);
    }
}

Compilation.prototype.renderTag = function(node){
    if(node.name=="main"){
		var target = this.script;
		for(var i = 0; i < node.attrs.length; i++){
			if(node.attrs[i].name == "section"){
				switch(node.attrs[i].val){
					case "start":
					case "'start'":
					case '"start"':
						var target = this.imports;
						break;
					case "body":
					case "'body'":
					case '"body"':
						var target = this.members;
						break;
					case "end":
					case "'end'":
					case '"end"':
					default:
						var target = this.script;
						break;
				}
				break;
			}
		}
		var content = [];
        for(var i = 0; i < node.nodes.length; i++){
            switch(node.nodes[i].type){
                case "Text":
                    content.push(node.nodes[i].val);
                    break;
            }
        }
		content.join("").split("\n").forEach(function(line){
			target.writeLine(line);
		});
    }else if(node.name == "children"){
        this.block.writeLine("for(var i = 0; i < this.props.children.length; i++){",1);
        this.block.writeLine("__add(this.props.children[i]);",-1);
        this.block.writeLine("}");
    }else{
        var isDOM = tags.indexOf(node.name)>=0;
        this.block.write("__add(React.createFactory("+(isDOM?"'":"")+node.name+(isDOM?"'":"")+"),");

        if(node.code && node.code.val){
            node.nodes.unshift(node.code)
        }
        if(node.name == "script" || node.name == "style"){
            var script = [];
            for(var i = 0; i < node.nodes.length; i++){
                switch(node.nodes[i].type){
                    case "Code":
                        script.push(node.nodes[i].val);
                        break;
                    case "Text":
                        script.push("\""+node.nodes[i].val.replace(/"/g,"\\\"")+"\"");
                        break;
                }
            }
            script = script.join(" + ");
            if(script){
                node.attrs.push({
                    name:"dangerouslySetInnerHTML",
                    val:"{__html:"+script+"}"
                })
            }
            node.nodes = [];
        }
        this.renderAttributes(node);

        if(node.nodes.length){
            this.block.writeLine(",function(__add){",1);
            this.renderNodes(node.nodes);
            this.block.indent(-1);
            this.block.writeLine("});");
        }else{
            this.block.writeLine(");");
        }
    }
}

Compilation.prototype.renderBlock = function(node){
    this.renderNodes(node.nodes);
}

Compilation.prototype.renderAttributes = function(node){
    if(node.attrs){
        var attributes = {};
        for(var i = 0; i < node.attrs.length; i++){
            var att = node.attrs[i];
            if(attributes[att.name] && att.name == "class"){
                attributes[att.name] += " + \" \" + "+att.val;
            }else{
                attributes[att.name] = att.val;
            }
        }

        if(attributes.class){
            attributes.className = attributes.class;
            delete attributes.class;
        }
        if(node.attributeBlocks.length) this.block.write("jade2react.mixinAttributes(");
        var first = true;
        this.block.write("{");
        for(var att in attributes){
            this.block.write((first?"":",")+'"'+att+'":'+(att=="style"?"jade2react.mapStyle(":"")+attributes[att]+(att=="style"?")":""));
            first = false;
        }
        this.block.write("}");
        if(node.attributeBlocks.length) this.block.write(",["+node.attributeBlocks.join(",")+"])");
    }else{
        this.block.write("{}");
    }
}

Compilation.prototype.renderEach = function(node){
    this.block.writeLine("for(var "+(node.key||"__key")+" in "+node.obj+"){",1);
    if(node.val){
        this.block.writeLine("var "+node.val+" = "+node.obj+"["+(node.key||"__key")+"];");
    }
    this.renderNodes(node.nodes);
    this.block.indent(-1);
    this.block.writeLine("}");
}

Compilation.prototype.renderComment = function(node){
    this.block.writeLine("//"+node.val)
}

Compilation.prototype.renderBlockComment = function(node){
    this.block.writeLine("/*",1);
    for(var i = 0; i < node.nodes.length; i++){
        this.block.writeLine(node.nodes[i].val);
    }
    this.block.indent(-1);
    this.block.writeLine("*/");
}

Compilation.prototype.renderCase = function(node){
    this.block.writeLine("switch("+node.expr+"){",1);
    this.renderNodes(node.nodes);
    this.block.indent(-1);
    this.block.writeLine("}");
}

Compilation.prototype.renderWhen = function(node){
    this.block.writeLine("case "+node.expr+":",1);
    if(node.nodes){
        this.renderNodes(node.nodes);
        this.block.writeLine("break;");
    }
    this.block.indent(-1);
}

Compilation.prototype.renderMixin = function(node){
    if(node.call){
        this.block.write("this."+node.name+"(");
        if(node.nodes){
            this.block.writeLine("jade2react.render(this,function(__add){",1);
            this.renderNodes(node.nodes);
            this.block.indent(-1);
            this.block.write("}),");
        }else{
            this.block.write("[],");
        }
        this.renderAttributes(node);
        this.block.writeLine(","+node.args+").forEach(__add);");
    }else{
        var prev = this.block;
        this.block = new Block();
        this.mixins.writeBlock(this.block);

        if(node.args){
            var argparts = node.args.split("...");
            argparts[0] = argparts[0].trim();
            if(argparts[0][argparts[0].length-1] == ","){
                argparts[0] = argparts[0].slice(0,-1);
            }
            argparts[0] = ","+argparts[0];
        }else{
            argparts = [""];
        }

        this.block.writeLine("Component.prototype."+node.name+" = function(block,attributes"+argparts[0]+"){",1);
        if(argparts.length > 1){
            this.block.writeLine("var "+argparts[1].trim()+" = Array.prototype.slice.call(arguments,"+argparts[0].split(",").length+");");
        }
        this.block.writeLine("return jade2react.render(this,function(__add){",1);
        this.renderNodes(node.nodes)
        this.block.indent(-1);
        this.block.writeLine("});");
        this.block.indent(-1);
        this.block.writeLine("}");
        this.block = prev;
    }
}

Compilation.prototype.renderMixinBlock = function(node){
    this.block.writeLine("block.forEach(__add)")
}

Compilation.prototype.renderExtends = function(node){
    var baseComponent = (node?("require(\""+node.file.path+"\")"):"React.Component");
    this.extendblock.writeLine("class Component extends "+baseComponent+"{");
}

Compilation.prototype.renderNamedBlock = function(node){
    if(!this.blocklist[node.name]) this.blocklist[node.name] = {};
    this.blocklist[node.name][node.mode||"replace"] = node;
    if(node.mode == "replace" || node.mode === undefined){
        this.block.writeLine("this."+node.name+"(__add);")
    }
}

module.exports = Compilation;
<commit_msg>escape newlines & tabs<commit_after>var parse = require("pug-parser");
var lex = require("pug-lexer");
var Block = require("./block.js");
var tags = "a abbr address area article aside audio b base bdi bdo big blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd keygen label legend li link main map mark menu menuitem meta meter nav noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track u ul var video wbr circle defs ellipse g line linearGradient mask path pattern polygon polyline radialGradient rect stop svg text tspan".split(" ");

function Compilation(doc,path){
	doc = doc.replace(/\r\n/g,"\n");
    this.path = path;
    this.tree = parse(lex(doc)).nodes;
    this.main = new Block();
    this.mixins = new Block();
    this.script = new Block();
	this.imports = new Block();
	this.members = new Block();
    this.extendblock = new Block();
    this.blocks = new Block();
    this.block = this.main;
    this.blocklist = {};
}

Compilation.prototype = Object.create(Block.prototype);

Compilation.prototype.compile = function(){
    this.deblock(this.tree);
    this.tree.forEach(function(node){
        if(node.type == "Tag" && node.name == "script") node.name = "main";
    })
	this.block.writeLine('"use strict";');
    this.block.writeLine("var React = require(\"react\");");
    this.block.writeLine("var jade2react = require(\"jade2react\");");
	this.block.writeBlock(this.imports);
    this.block.writeLine("");
    this.block.writeBlock(this.extendblock); //start of class
    this.block.indent(1);
    this.block.writeLine("_render(__add){",1);
    this.renderNodes(this.tree,true);
    if(this.extendblock.out.length){
        this.block.writeLine("super._render.call(this,__add);");
    }
    this.block.indent(-1);
    this.block.writeLine("}");
    this.block.writeLine("render(){",1);
    this.block.writeLine("return jade2react.render(this,this._render)[0];",-1);
    this.block.writeLine("}");
    for(var block in this.blocklist){
        var b = this.blocklist[block];
        this.block.writeLine(block+"(__add){",1);
        if(b.prepend){
            this.renderNodes(b.prepend.nodes);
        }
        if(b.replace){
            this.renderNodes(b.replace.nodes);
        }else{
            this.block.writeLine("super."+block+".call(this,__add);");
        }
        if(b.append){
            this.renderNodes(b.append.nodes);
        }
        this.block.indent(-1);
        this.block.writeLine("}");
    }
    if(this.mixins.out.length){
        this.block.writeBlock(this.mixins);
    }
	if(this.members.out.length){
		this.block.writeBlock(this.members);
	}
    this.block.indent(-1);
    this.block.writeLine("}"); //end of class
	this.block.writeLine("module.exports = Component;");
    this.block.writeLine("");
    this.block.writeBlock(this.script);

    if(!this.extendblock.out.length){
        this.renderExtends()
    }

    var code = this.block.build();
    return code;
}

Compilation.prototype.deblock = function(nodes){
    for(var i = 0; i < nodes.length; i++){
        var node = nodes[i];
        if(node.block) node.nodes = node.block.nodes;
        if(node.nodes) this.deblock(node.nodes);
    }
}

Compilation.prototype.renderNode = function(node){
    switch(node.type){
        case "Text":
        case "Code":
        case "Tag":
        case "Block":
        case "Each":
        case "Comment":
        case "BlockComment":
        case "Case":
        case "When":
        case "Mixin":
        case "MixinBlock":
        case "Extends":
        case "NamedBlock":
            this["render"+node.type](node);
            break;
    }
}

Compilation.prototype.renderNodes = function(nodes){
    for(var i = 0; i < nodes.length; i++){
        this.renderNode(nodes[i]);
    }
}

Compilation.prototype.renderText = function(node){
    if(!node.val) return;
    this.block.writeLine("__add(\""+node.val+"\");");
}

Compilation.prototype.renderCode = function(node){
    if(!node.val) return;
    if(node.block){
        this.block.writeLine(node.val+"{",1);
        this.renderNodes(node.block.nodes);
        this.block.indent(-1);
        this.block.writeLine("}");
    }else if(node.buffer){
        this.block.writeLine("__add("+node.val+");");
    }else{
        this.block.writeLine(node.val);
    }
}

Compilation.prototype.renderTag = function(node){
    if(node.name=="main"){
		var target = this.script;
		for(var i = 0; i < node.attrs.length; i++){
			if(node.attrs[i].name == "section"){
				switch(node.attrs[i].val){
					case "start":
					case "'start'":
					case '"start"':
						var target = this.imports;
						break;
					case "body":
					case "'body'":
					case '"body"':
						var target = this.members;
						break;
					case "end":
					case "'end'":
					case '"end"':
					default:
						var target = this.script;
						break;
				}
				break;
			}
		}
		var content = [];
        for(var i = 0; i < node.nodes.length; i++){
            switch(node.nodes[i].type){
                case "Text":
                    content.push(node.nodes[i].val);
                    break;
            }
        }
		content.join("").split("\n").forEach(function(line){
			target.writeLine(line);
		});
    }else if(node.name == "children"){
        this.block.writeLine("for(var i = 0; i < this.props.children.length; i++){",1);
        this.block.writeLine("__add(this.props.children[i]);",-1);
        this.block.writeLine("}");
    }else{
        var isDOM = tags.indexOf(node.name)>=0;
        this.block.write("__add(React.createFactory("+(isDOM?"'":"")+node.name+(isDOM?"'":"")+"),");

        if(node.code && node.code.val){
            node.nodes.unshift(node.code)
        }
        if(node.name == "script" || node.name == "style"){
            var script = [];
            for(var i = 0; i < node.nodes.length; i++){
                switch(node.nodes[i].type){
                    case "Code":
                        script.push(node.nodes[i].val);
                        break;
                    case "Text":
                        script.push("\""+node.nodes[i].val.replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"\"");
                        break;
                }
            }
            script = script.join(" + ");
            if(script){
                node.attrs.push({
                    name:"dangerouslySetInnerHTML",
                    val:"{__html:"+script+"}"
                })
            }
            node.nodes = [];
        }
        this.renderAttributes(node);

        if(node.nodes.length){
            this.block.writeLine(",function(__add){",1);
            this.renderNodes(node.nodes);
            this.block.indent(-1);
            this.block.writeLine("});");
        }else{
            this.block.writeLine(");");
        }
    }
}

Compilation.prototype.renderBlock = function(node){
    this.renderNodes(node.nodes);
}

Compilation.prototype.renderAttributes = function(node){
    if(node.attrs){
        var attributes = {};
        for(var i = 0; i < node.attrs.length; i++){
            var att = node.attrs[i];
            if(attributes[att.name] && att.name == "class"){
                attributes[att.name] += " + \" \" + "+att.val;
            }else{
                attributes[att.name] = att.val;
            }
        }

        if(attributes.class){
            attributes.className = attributes.class;
            delete attributes.class;
        }
        if(node.attributeBlocks.length) this.block.write("jade2react.mixinAttributes(");
        var first = true;
        this.block.write("{");
        for(var att in attributes){
            this.block.write((first?"":",")+'"'+att+'":'+(att=="style"?"jade2react.mapStyle(":"")+attributes[att]+(att=="style"?")":""));
            first = false;
        }
        this.block.write("}");
        if(node.attributeBlocks.length) this.block.write(",["+node.attributeBlocks.join(",")+"])");
    }else{
        this.block.write("{}");
    }
}

Compilation.prototype.renderEach = function(node){
    this.block.writeLine("for(var "+(node.key||"__key")+" in "+node.obj+"){",1);
    if(node.val){
        this.block.writeLine("var "+node.val+" = "+node.obj+"["+(node.key||"__key")+"];");
    }
    this.renderNodes(node.nodes);
    this.block.indent(-1);
    this.block.writeLine("}");
}

Compilation.prototype.renderComment = function(node){
    this.block.writeLine("//"+node.val)
}

Compilation.prototype.renderBlockComment = function(node){
    this.block.writeLine("/*",1);
    for(var i = 0; i < node.nodes.length; i++){
        this.block.writeLine(node.nodes[i].val);
    }
    this.block.indent(-1);
    this.block.writeLine("*/");
}

Compilation.prototype.renderCase = function(node){
    this.block.writeLine("switch("+node.expr+"){",1);
    this.renderNodes(node.nodes);
    this.block.indent(-1);
    this.block.writeLine("}");
}

Compilation.prototype.renderWhen = function(node){
    this.block.writeLine("case "+node.expr+":",1);
    if(node.nodes){
        this.renderNodes(node.nodes);
        this.block.writeLine("break;");
    }
    this.block.indent(-1);
}

Compilation.prototype.renderMixin = function(node){
    if(node.call){
        this.block.write("this."+node.name+"(");
        if(node.nodes){
            this.block.writeLine("jade2react.render(this,function(__add){",1);
            this.renderNodes(node.nodes);
            this.block.indent(-1);
            this.block.write("}),");
        }else{
            this.block.write("[],");
        }
        this.renderAttributes(node);
        this.block.writeLine(","+node.args+").forEach(__add);");
    }else{
        var prev = this.block;
        this.block = new Block();
        this.mixins.writeBlock(this.block);

        if(node.args){
            var argparts = node.args.split("...");
            argparts[0] = argparts[0].trim();
            if(argparts[0][argparts[0].length-1] == ","){
                argparts[0] = argparts[0].slice(0,-1);
            }
            argparts[0] = ","+argparts[0];
        }else{
            argparts = [""];
        }

        this.block.writeLine("Component.prototype."+node.name+" = function(block,attributes"+argparts[0]+"){",1);
        if(argparts.length > 1){
            this.block.writeLine("var "+argparts[1].trim()+" = Array.prototype.slice.call(arguments,"+argparts[0].split(",").length+");");
        }
        this.block.writeLine("return jade2react.render(this,function(__add){",1);
        this.renderNodes(node.nodes)
        this.block.indent(-1);
        this.block.writeLine("});");
        this.block.indent(-1);
        this.block.writeLine("}");
        this.block = prev;
    }
}

Compilation.prototype.renderMixinBlock = function(node){
    this.block.writeLine("block.forEach(__add)")
}

Compilation.prototype.renderExtends = function(node){
    var baseComponent = (node?("require(\""+node.file.path+"\")"):"React.Component");
    this.extendblock.writeLine("class Component extends "+baseComponent+"{");
}

Compilation.prototype.renderNamedBlock = function(node){
    if(!this.blocklist[node.name]) this.blocklist[node.name] = {};
    this.blocklist[node.name][node.mode||"replace"] = node;
    if(node.mode == "replace" || node.mode === undefined){
        this.block.writeLine("this."+node.name+"(__add);")
    }
}

module.exports = Compilation;
<|endoftext|>


<commit_before>'use strict';
var https         = require('https');
var activityUtils = require('./activityUtils');
var config        = require('config');
var SfmcClient    = require('../lib/sfmc/sfmcClient');

var Activity = function () {
var sfmcClient = new SfmcClient(config);

  return {
    execute: function( req, res ) {
        console.log("================");
        console.log('ROUTE = EXECUTE');
        console.log("================");
        //activityUtils.logData( req );

        var aArgs = req.body.inArguments;
        var oArgs = {};

        for (var i=0; i<aArgs.length; i++) {
        for (var key in aArgs[i]) {
            oArgs[key] = aArgs[i][key];
          }
        }

        // TODO: Implement request to Voucher API
        var voucherCode = "TEST_CODE_" + oArgs.voucher.amount;

        var primaryKeyValue = oArgs.emailAddress;
        var dataExtensionKey = oArgs.dataExtensionKey;
        var primaryKeyField = oArgs.dataExtensionPrimaryKey;
        var voucherCodeField = oArgs.dataExtensionVoucherField;

        var keys = {}, values = {};
        keys[primaryKeyField] = primaryKeyValue;
        values[voucherCodeField] = voucherCode;

        var options = {
          dataExtensionKey: dataExtensionKey,
          keys: keys,
          values: values
        };

        var row = sfmcClient.dataExtensionRow(options);
        row.post(function (error, request, body) {
           if (error) {
               console.log("ERROR...");
               console.log(error);

             res.send( 500, error );
           } else if (body.errorcode) {
               console.log("ERROR CODE...");
               console.log(body);
                res.send( 500, body );
           } else {
             res.send( 200, body );
           }
        });
    },
    save: function( req, res ) {
        console.log("================");
        console.log('ROUTE = SAVE');
        console.log("================");
        //activityUtils.logData( req );
        res.send( 200, 'Save' );
    },
    publish: function( req, res ) {
        console.log("================");
        console.log('ROUTE = PUBLISH');
        console.log("================");
        //activityUtils.logData( req );

        res.send( 200 );
    },
    validate: function( req, res ) {
        console.log("================");
        console.log('ROUTE = VALIDATE');
        console.log("================");
        //activityUtils.logData( req );
        res.send( 200 );
    }
  };
};

module.exports = Activity;<commit_msg>Added DE post test to publish<commit_after>'use strict';
var https         = require('https');
var activityUtils = require('./activityUtils');
var config        = require('config');
var SfmcClient    = require('../lib/sfmc/sfmcClient');

var Activity = function () {
  var sfmcClient = new SfmcClient(config);

  return {
    execute: function( req, res ) {
        console.log("================");
        console.log('ROUTE = EXECUTE');
        console.log("================");
        activityUtils.logData( req );

        var aArgs = req.body.inArguments;
        var oArgs = {};

        for (var i=0; i<aArgs.length; i++) {
        for (var key in aArgs[i]) {
            oArgs[key] = aArgs[i][key];
          }
        }

        // TODO: Implement request to Voucher API
        var voucherCode = "TEST_CODE_" + oArgs.voucher.amount;

        var primaryKeyValue = oArgs.emailAddress;
        var dataExtensionKey = oArgs.dataExtensionKey;
        var primaryKeyField = oArgs.dataExtensionPrimaryKey;
        var voucherCodeField = oArgs.dataExtensionVoucherField;

        var keys = {}, values = {};
        keys[primaryKeyField] = primaryKeyValue;
        values[voucherCodeField] = voucherCode;

        var options = {
          dataExtensionKey: dataExtensionKey,
          keys: keys,
          values: values
        };

        var row = sfmcClient.dataExtensionRow(options);
        row.post(function (error, request, body) {
           if (error) {
             console.log("ERROR 500");
             console.log(error);
             res.send( 500, error );
           } else if (body.errorcode) {
             console.log("ERROR " + body.errorcode);
             console.log(body);
             res.send( 500, body );
           } else {
             res.send( 200, body );
           }
        });
    },
    save: function( req, res ) {
        console.log("================");
        console.log('ROUTE = SAVE');
        console.log("================");
        activityUtils.logData( req );
        res.send( 200, 'Save' );
    },
    publish: function( req, res ) {
        console.log("================");
        console.log('ROUTE = PUBLISH');
        console.log("================");
        activityUtils.logData( req );
        res.send( 200 );
    },
    validate: function( req, res ) {
        console.log("================");
        console.log('ROUTE = VALIDATE');
        console.log("================");
        activityUtils.logData( req );
        res.send( 200 );
    }
  };
};

module.exports = Activity;<|endoftext|>


<commit_before>const r = require('express').Router()
const k = require('../knex')

r.route('/:post_id/comments')
 .get((req, res, next) => {
  k('comments')
    .where({ post_id: req.params.post_id })
    .then(comments => res.json(comments))
    .catch(err => next(err))
 })
//
.post('/:post_id/comments', validate, (req, res, next) => {
  k('comments')
    .insert({ content: req.body.content, post_id: req.params.post_id })
    .where({ post_id: req.params.post_id })
    .returning('*')
    .then(comments => res.json(comments[0]))
    .catch(err => next(err))
})

.patch('/:post_id/comments', validate, (req, res, next) => {
  k('comments')
    .update({ content: req.body.content })
    .where({ post_id: req.params.post_id, id: req.params.id })
    .returning('*')
    .then(comments => res.json(comments[0]))
    .catch(err => next(err))
})

.delete('/:post_id/comments', (req, res, next) => {
  k('comments')
    .del()
    .where({ post_id: req.params.post_id, id: req.params.id })
    .then(() => res.end())
    .catch(err => next(err))
})

function validate(req, res, next) {
  const errors = [];
  ['content'].forEach(field => {
    if (!req.body[field] || req.body[field].trim() === '') {
      errors.push({ field, messages: ["cannot be blank"] })
    }
  })
  if (errors.length) return res.status(422).json({ errors })
  next()
}

module.exports = r
<commit_msg>comments serverside route syntax fixed<commit_after>const r = require('express').Router()
const k = require('../knex')

r.route('/:post_id/comments')
 .get((req, res, next) => {
  k('comments')
    .where({ post_id: req.params.post_id })
    .then(comments => res.json(comments))
    .catch(err => next(err))
 })
//
.post((req, res, next) => {
  k('comments')
    .insert({ content: req.body.content, post_id: req.params.post_id })
    .where({ post_id: req.params.post_id })
    .returning('*')
    .then(comments => res.json(comments[0]))
    .catch(err => next(err))
})

.patch((req, res, next) => {
  k('comments')
    .update({ content: req.body.content })
    .where({ post_id: req.params.post_id, id: req.params.id })
    .returning('*')
    .then(comments => res.json(comments[0]))
    .catch(err => next(err))
})

.delete((req, res, next) => {
  k('comments')
    .del()
    .where({ post_id: req.params.post_id, id: req.params.id })
    .then(() => res.end())
    .catch(err => next(err))
})

function validate(req, res, next) {
  const errors = [];
  ['content'].forEach(field => {
    if (!req.body[field] || req.body[field].trim() === '') {
      errors.push({ field, messages: ["cannot be blank"] })
    }
  })
  if (errors.length) return res.status(422).json({ errors })
  next()
}

module.exports = r
<|endoftext|>


<commit_before>/** This module defines the routes for comments using the store.js as db memory
 *
 * @author Johannes Konert
 * @licence CC BY-SA 4.0
 *
 * @module routes/comments
 * @type {Router}
 */

// remember: in modules you have 3 variables given by CommonJS
// 1.) require() function
// 2.) module.exports
// 3.) exports (which is module.exports)

// modules
var express = require('express');
var logger = require('debug')('me2u4:videos');
var store = require('../blackbox/store');
var utils = require('../utils/utils');

var comments = express.Router();

// if you like, you can use this for task 1.b:
var requiredKeys = {videoid: 'number', text: 'string'};
var optionalKeys = {likes: 'number', dislikes: 'number'};
var internalKeys = {id: 'number', timestamp: 'number'};

// helper functions
var validateCommentRequest = function (req, res, callback) {
    var likes = parseInt(req.body.likes);
    var dislikes = parseInt(req.body.dislikes);

    if (req.body.text === undefined || req.body.text === "") {
        utils.checkErrorMessageLength("text");
    }

    if (req.body.videoid === undefined || req.body.videoid === "") {
        utils.checkErrorMessageLength("videoid");
    }

    if (utils.noError()) {
        if (!(likes instanceof Number) || likes < 0) {
            req.body.likes = 0;
        }
        if (!(dislikes instanceof Number) || dislikes < 0) {
            req.body.dislikes = 0;
        }
        callback();
    } else {

        utils.sendErrorMessage(400, res, "missing parameters: ");

    }
};

// routes **********************
comments.route('/')
    .get(function (req, res, next) {
        res.json(store.select('comments'));
        next();
    })
    .post(function (req, res, next) {

        validateCommentRequest(req, res, function () {
            req.body.timestamp = utils.getTimeStamp();
            var id = store.insert('comments', req.body);
            // set code 201 "created" and send the item back
            res.status(201).json(store.select('comments', id));
        });
    })
    .put(function (req, res, next) {
        validateCommentRequest(req, res, function () {
            req.body.timestamp = utils.getTimeStamp();
            store.replace('comments', req.body.id, req.body);
            res.status(201).json(store.select('comments', req.body.id));
        });
    })
    .delete(function (req, res, next) {
        store.remove('comments', req.body.id);
        res.status(204).end();
    });

// this middleware function can be used, if you like or remove it
comments.use(function (req, res, next) {
    // if anything to send has been added to res.locals.items
    if (res.locals.items) {
        // then we send it as json and remove it
        res.json(res.locals.items);
        delete res.locals.items;
    } else {
        // otherwise we set status to no-content
        res.set('Content-Type', 'application/json');
        res.status(201).end(); // no content;
    }
});

module.exports = comments;<commit_msg>no message<commit_after>/** This module defines the routes for comments using the store.js as db memory
 *
 * @author Johannes Konert
 * @licence CC BY-SA 4.0
 *
 * @module routes/comments
 * @type {Router}
 */

// remember: in modules you have 3 variables given by CommonJS
// 1.) require() function
// 2.) module.exports
// 3.) exports (which is module.exports)

// modules
var express = require('express');
var logger = require('debug')('me2u4:comments');
var store = require('../blackbox/store');
var utils = require('../utils/utils');

var comments = express.Router();

// if you like, you can use this for task 1.b:
var requiredKeys = {videoid: 'number', text: 'string'};
var optionalKeys = {likes: 'number', dislikes: 'number'};
var internalKeys = {id: 'number', timestamp: 'number'};

// helper functions
var validateCommentRequest = function (req, res, callback) {
    var likes = parseInt(req.body.likes);
    var dislikes = parseInt(req.body.dislikes);

    if (req.body.text === undefined || req.body.text === "") {
        utils.checkErrorMessageLength("text");
    }

    if (req.body.videoid === undefined || req.body.videoid === "") {
        utils.checkErrorMessageLength("videoid");
    }

    if (utils.noError()) {
        if (!(likes instanceof Number) || likes < 0) {
            req.body.likes = 0;
        }
        if (!(dislikes instanceof Number) || dislikes < 0) {
            req.body.dislikes = 0;
        }
        callback();
    } else {

        utils.sendErrorMessage(400, res, "missing parameters: ");

    }
};

// routes **********************
comments.route('/')
    .get(function (req, res, next) {
        res.json(store.select('comments'));
        next();
    })
    .post(function (req, res, next) {

        validateCommentRequest(req, res, function () {
            req.body.timestamp = utils.getTimeStamp();
            var id = store.insert('comments', req.body);
            // set code 201 "created" and send the item back
            res.status(201).json(store.select('comments', id));
        });
    })
    .put(function (req, res, next) {
        validateCommentRequest(req, res, function () {
            req.body.timestamp = utils.getTimeStamp();
            store.replace('comments', req.body.id, req.body);
            res.status(201).json(store.select('comments', req.body.id));
        });
    })
    .delete(function (req, res, next) {
        store.remove('comments', req.body.id);
        res.status(204).end();
    });

// this middleware function can be used, if you like or remove it
comments.use(function (req, res, next) {
    // if anything to send has been added to res.locals.items
    if (res.locals.items) {
        // then we send it as json and remove it
        res.json(res.locals.items);
        delete res.locals.items;
    } else {
        // otherwise we set status to no-content
        res.set('Content-Type', 'application/json');
        res.status(201).end(); // no content;
    }
});

module.exports = comments;<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var dbClient = require('mariasql');
var Q = require('q');

var client = new dbClient({
  host: 'localhost',
  user: 'root',
  password: ''
});

/**
 *
 * @param {string} id String to confirm is a valid integer
 * @returns {Q.promise} containing value of the ID number as integer
 */
function verifyIdIsInteger(id) {
  let deferred = Q.defer()

  let parsed_id = parseInt(id)
  if (!parsed_id) {
    deferred.reject(new Error("Supplied ID is not an integer"))
  }
  else {
    console.log("ID is valid: " + parsed_id)
    deferred.resolve(parsed_id)
  }

  return deferred.promise
}

/**
 * Removes a contact with ID `id` from the database
 * @param {integer} id ID of contact to remove
 * @returns {Q.promise}
 */

function deleteContactFromDB(id) {
  let deferred = Q.defer()
  client.query("DELETE FROM voluble.contacts WHERE id = ?", [id], true, function (err, rows) {
    if (err) { deferred.reject(err) }
    else {
      console.log("Successfully deleted contact " + id)
      deferred.resolve()
    }
  })

  return deferred.promise
}

/**
 * Queries the database to make sure confirm that the contact with id `id` exists
 * @param {integer} id Contact ID number
 * @returns {Q.promise} with value `id` if contact exists
 */
function checkContactWithIDExists(id) {
  let deferred = Q.defer()
  client.query("SELECT id FROM voluble.contacts WHERE id = ?", [id], { useArray: true }, function (err, rows) {
    if (err) { deferred.reject(err) }
    else if (!rows.length) {
      deferred.reject(new Error("Contact with this ID does not exist."))
    }
    else deferred.resolve(id)
  })
  return deferred.promise
}

/**
 * Queries the database to retrieve the info for contact with ID `id`
 * @param {integer} id Contact ID number
 * @returns {Q.promise} with JSON data containing user info
 */
function getContactWithId(id) {
  let deferred = Q.defer()
  client.query("SELECT * FROM voluble.contacts WHERE id = ?", [id], { useArray: true }, function (err, rows) {
    if (err) { deferred.reject(err) }
    else {
      deferred.resolve(rows[0])
    }
  })

  return deferred.promise
}

function updateSingleContactDetailWithId(id, field_name, new_value) {
  let deferred = Q.defer()

  client.query("UPDATE voluble.contacts SET " + field_name + " = ? WHERE id = ?", [new_value, id], function (err, rows) {
    if (err) {
      deferred.reject(err)
    } else {
      deferred.resolve()
    }

  })

  return deferred.promise
}

function updateContactDetailsWithId(id, updatedDetails) {
  /* Expect `updatedDetail` could be like:
  {
    first_name: "Derek",
    email_address: "steve@apple.com"
  }
  */
  promises = []

  for (detail in updatedDetails){
    promises.push(updateSingleContactDetailWithId(id, detail, updatedDetails[detail]))
  }
  return Q.all(promises)
}

router.get('/', function (req, res, next) {

  let prep = client.prepare("SELECT * FROM `voluble`.`contacts` ORDER BY id ASC")
  let q = client.query(prep())
  let contacts = []

  q.on('result', function (result) {
    result.on('data', function (row) {
      row.url = req.protocol + '://' + req.get('host') + "/contacts/" + row.id
      contacts.push(row)
    })
  }).on('end', function () {
    res.json(contacts).status(200)
  })
})

router.get('/:contact_id', function (req, res, next) {

  verifyIdIsInteger(req.params.contact_id)
    .then(function (id) {
      return checkContactWithIDExists(id)
    })
    .then(function (id) {
      return getContactWithId(id)
    }).then(function (user) {
      res.status(200).json(user)
    })
    .catch(function (error) {
      res.status(500).send(error.message)
    })
    .done()

})

function addContactToDB(first_name, surname, email) {
  let deferred = Q.defer()

  let prep = client.prepare("INSERT INTO `voluble`.`contacts` (`first_name`, `surname`, `email_address`, `default_servicechain`) VALUES (?, ?, ?, '1')")
  client.query(prep([first_name, surname, email]), function (err, rows) {
    if (err) {
      deferred.reject(err)
    }

    deferred.resolve(client.lastInsertId())
  })

  return deferred.promise
}

/* Note: this is boilerplate and has NOT been implemented yet */
router.post('/', function (req, res, next) {
  addContactToDB(req.body.first_name, req.body.surname, req.body.email_address)
    .then(function (newContactID) {
      res.status(200).send("New contact: ID " + newContactID)
    })
    .catch(function (error) {
      console.log(error)
      res.status(500).end()
    })
    .done()

})

/* Note: this is boilerplate and has NOT been implemented yet */
router.put('/:contact_id', function (req, res, next) {

  verifyIdIsInteger(req.params.contact_id)
    .then(function (id) {
      return checkContactWithIDExists(id)
    })
    .then(function (id) {
      return updateContactDetailsWithId(id, req.body)
    })
    .then(function(){
      res.status(200).end()
    })
    .catch(function (err) {
      console.log(err)
      res.status(500).send(err)
    })
    .done()

})

router.delete('/:contact_id', function (req, res, next) {
  verifyIdIsInteger(req.params.contact_id)
    .then(function (contact_id) {
      return deleteContactFromDB(contact_id)
    })
    .then(function () {
      res.send("Successfully deleted contact " + req.params.contact_id)
    })
    .catch(function (error) {
      console.log(error.message)
      res.status(500).end()
    })
    .done()
})

module.exports = router;<commit_msg>Docs make the world go around<commit_after>var express = require('express');
var router = express.Router();
var dbClient = require('mariasql');
var Q = require('q');

var client = new dbClient({
  host: 'localhost',
  user: 'root',
  password: ''
});

/**
 *
 * @param {string} id String to confirm is a valid integer
 * @returns {Q.promise} containing value of the ID number as integer
 */
function verifyIdIsInteger(id) {
  let deferred = Q.defer()

  let parsed_id = parseInt(id)
  if (!parsed_id) {
    deferred.reject(new Error("Supplied ID is not an integer"))
  }
  else {
    console.log("ID is valid: " + parsed_id)
    deferred.resolve(parsed_id)
  }

  return deferred.promise
}

/**
 * Removes a contact with ID `id` from the database
 * @param {integer} id ID of contact to remove
 * @returns {Q.promise}
 */

function deleteContactFromDB(id) {
  let deferred = Q.defer()
  client.query("DELETE FROM voluble.contacts WHERE id = ?", [id], true, function (err, rows) {
    if (err) { deferred.reject(err) }
    else {
      console.log("Successfully deleted contact " + id)
      deferred.resolve()
    }
  })

  return deferred.promise
}

/**
 * Queries the database to make sure confirm that the contact with id `id` exists
 * @param {integer} id Contact ID number
 * @returns {Q.promise} with value `id` if contact exists
 */
function checkContactWithIDExists(id) {
  let deferred = Q.defer()
  client.query("SELECT id FROM voluble.contacts WHERE id = ?", [id], { useArray: true }, function (err, rows) {
    if (err) { deferred.reject(err) }
    else if (!rows.length) {
      deferred.reject(new Error("Contact with this ID does not exist."))
    }
    else deferred.resolve(id)
  })
  return deferred.promise
}

/**
 * Queries the database to retrieve the info for contact with ID `id`
 * @param {integer} id Contact ID number
 * @returns {Q.promise} with JSON data containing user info
 */
function getContactWithId(id) {
  let deferred = Q.defer()
  client.query("SELECT * FROM voluble.contacts WHERE id = ?", [id], { useArray: true }, function (err, rows) {
    if (err) { deferred.reject(err) }
    else {
      deferred.resolve(rows[0])
    }
  })

  return deferred.promise
}

/**
 * Does UPDATE DB operation to update a Contact's detail. Usually called by `updateContactDetailsWithId`.
 * @param {integer} id ID of contact to update
 * @param {string} field_name Name of the parameter to update, e.g. first_name
 * @param {string} new_value Value to insert at `field_name`
 */
function updateSingleContactDetailWithId(id, field_name, new_value) {
  let deferred = Q.defer()

  client.query("UPDATE voluble.contacts SET " + field_name + " = ? WHERE id = ?", [new_value, id], function (err, rows) {
    if (err) {
      deferred.reject(err)
    } else {
      deferred.resolve()
    }

  })

  return deferred.promise
}

/**
 * Updates the details of a single Contact. Internally calls updateSingleContactDetailWithId for each detail change.
 * @param {integer} id ID of the Contact whose details will be updated
 * @param {object} updatedDetails Object containing a mapping of parameter names to new values, e.g {first_name: 'Adam', surname: 'Smith'}
 */
function updateContactDetailsWithId(id, updatedDetails) {
  /* Expect `updatedDetail` could be like:
  {
    first_name: "Derek",
    email_address: "steve@apple.com"
  }
  */
  promises = []

  for (detail in updatedDetails){
    promises.push(updateSingleContactDetailWithId(id, detail, updatedDetails[detail]))
  }
  return Q.all(promises)
}

router.get('/', function (req, res, next) {

  let prep = client.prepare("SELECT * FROM `voluble`.`contacts` ORDER BY id ASC")
  let q = client.query(prep())
  let contacts = []

  q.on('result', function (result) {
    result.on('data', function (row) {
      row.url = req.protocol + '://' + req.get('host') + "/contacts/" + row.id
      contacts.push(row)
    })
  }).on('end', function () {
    res.json(contacts).status(200)
  })
})

router.get('/:contact_id', function (req, res, next) {

  verifyIdIsInteger(req.params.contact_id)
    .then(function (id) {
      return checkContactWithIDExists(id)
    })
    .then(function (id) {
      return getContactWithId(id)
    }).then(function (user) {
      res.status(200).json(user)
    })
    .catch(function (error) {
      res.status(500).send(error.message)
    })
    .done()

})

function addContactToDB(first_name, surname, email) {
  let deferred = Q.defer()

  let prep = client.prepare("INSERT INTO `voluble`.`contacts` (`first_name`, `surname`, `email_address`, `default_servicechain`) VALUES (?, ?, ?, '1')")
  client.query(prep([first_name, surname, email]), function (err, rows) {
    if (err) {
      deferred.reject(err)
    }

    deferred.resolve(client.lastInsertId())
  })

  return deferred.promise
}

/* Note: this is boilerplate and has NOT been implemented yet */
router.post('/', function (req, res, next) {
  addContactToDB(req.body.first_name, req.body.surname, req.body.email_address)
    .then(function (newContactID) {
      res.status(200).send("New contact: ID " + newContactID)
    })
    .catch(function (error) {
      console.log(error)
      res.status(500).end()
    })
    .done()

})

/* Note: this is boilerplate and has NOT been implemented yet */
router.put('/:contact_id', function (req, res, next) {

  verifyIdIsInteger(req.params.contact_id)
    .then(function (id) {
      return checkContactWithIDExists(id)
    })
    .then(function (id) {
      return updateContactDetailsWithId(id, req.body)
    })
    .then(function(){
      res.status(200).end()
    })
    .catch(function (err) {
      console.log(err)
      res.status(500).send(err)
    })
    .done()

})

router.delete('/:contact_id', function (req, res, next) {
  verifyIdIsInteger(req.params.contact_id)
    .then(function (contact_id) {
      return deleteContactFromDB(contact_id)
    })
    .then(function () {
      res.send("Successfully deleted contact " + req.params.contact_id)
    })
    .catch(function (error) {
      console.log(error.message)
      res.status(500).end()
    })
    .done()
})

module.exports = router;<|endoftext|>


<commit_before>module.exports = function() {
  'use strict';

  return {
    options: {
      files: '<%= angularToolbox._.files.pkg %>',
      updateConfigs: ['pkg'],
      commitFiles: [
        '<%= angularToolbox._.files.pkg %>',
        '<%= angularToolbox.folder.dist %>/**/*'
      ],
      pushTo: 'origin'
    }
  };
};
<commit_msg>fix(bump): use explicit package files and no glob<commit_after>module.exports = function() {
  'use strict';

  return {
    options: {
      files: '<%= angularToolbox._.files.pkg %>',
      updateConfigs: ['pkg'],
      commitFiles: [
        '<%= jqueryToolbox.files.bower %>',
        '<%= jqueryToolbox.files.pkg %>',
        '<%= jqueryToolbox.folder.dist %>'
      ],
      pushTo: 'origin'
    }
  };
};
<|endoftext|>


<commit_before>/**
 * Listings API
 */

var rest = require('restler');
var cheerio = require('cheerio');
var async = require('async');
var apps = require('../data/apps.json');

var getAppListing = function(app, callback) {
	var request = rest.get(app.url);
	request.once('complete', function(result) {
		$ = cheerio.load(result);
		app.title = $(".document-title[itemprop='name']").text().trim();
		app.developerName = $(".document-subtitle.primary[itemprop='name']").text().trim();
		app.numberOfInstalls = $(".content[itemprop='numDownloads']").text().trim().split(" ")[0];
		callback();
	});
};

exports.list = function(req, res) {
	async.eachSeries(apps, getAppListing, function(err){
		if(err) {
			console.log(err);
		}
		res.json(apps);
	});
};<commit_msg>Added image url<commit_after>/**
 * Listings API
 */

var rest = require('restler');
var cheerio = require('cheerio');
var async = require('async');
var apps = require('../data/apps.json');

var getAppListing = function(app, callback) {
	var request = rest.get(app.url);
	request.once('complete', function(result) {
		$ = cheerio.load(result);
		app.title = $(".document-title[itemprop='name']").text().trim();
		app.developerName = $(".document-subtitle.primary[itemprop='name']").text().trim();
		app.numberOfInstalls = $(".content[itemprop='numDownloads']").text().trim().split(" ")[0];
		app.imageUrl = $(".cover-image[itemprop='image']").attr('src');
		callback();
	});
};

exports.list = function(req, res) {
	async.eachSeries(apps, getAppListing, function(err){
		if(err) {
			console.log(err);
		}
		//res.set('Cache-Control', 'max-age=3600');
		res.json(apps);
	});
};<|endoftext|>


<commit_before>'use strict';
var Posts = module.parent.parent.require('./posts');
var Settings = module.parent.parent.require('./settings');
var Meta = module.parent.parent.require('./meta');
var Controllers = {};

Controllers.getPost = function(req, res, next){
	var allowOrigin = mySettings.origins.split(',').map(function(value){
		return value.trim();
	});
	if(allowOrigin.includes(req.headers.origin) || mySettings.onlyxhr=="off"){
		res.header("Access-Control-Allow-Origin", req.headers.origin);
		res.header("Access-Control-Allow-Headers", "X-Requested-With");
		Posts.getPostData(req.params.pid,function(err,result){
			res.send(result);
		});
	}else{
		res.send("permission denied");
	}
};

Controllers.renderAdminPage = function (req, res, next) {
	res.render('admin/plugins/ccmtpostinfo', {});
};

Controllers.categoriesPage = function(req, res, next){
	var defaultSetting = {};
	var mySettings = Meta.settings.get('ccmtpostinfo', function(err,mySettings){
		if(err)
		console.log("err:",err);
		res.render('plugins/ccmtpostinfo/categories', mySettings);
	});
}
module.exports = Controllers;

<commit_msg>add err handle againy<commit_after>'use strict';
var Posts = module.parent.parent.require('./posts');
var Settings = module.parent.parent.require('./settings');
var Meta = module.parent.parent.require('./meta');
var Controllers = {};

Controllers.getPost = function(req, res, next){
	Meta.settings.get('ccmtpostinfo', function(err,mySettings){
		if(err)
		console.log("err:",err);
		var allowOrigin = mySettings.origins.split(',').map(function(value){
			return value.trim();
		});
		if(allowOrigin.includes(req.headers.origin) || mySettings.onlyxhr=="off"){
			res.header("Access-Control-Allow-Origin", req.headers.origin);
			res.header("Access-Control-Allow-Headers", "X-Requested-With");
			Posts.getPostData(req.params.pid,function(err,result){
				res.send(result);
			});
		}else{
			res.send("permission denied");
		}
	});
};
Controllers.renderAdminPage = function (req, res, next) {
	res.render('admin/plugins/ccmtpostinfo', {});
};
Controllers.categoriesPage = function(req, res, next){
	var defaultSetting = {};
	var mySettings = Meta.settings.get('ccmtpostinfo', function(err,mySettings){
		if(err)
		console.log("err:",err);
		res.render('plugins/ccmtpostinfo/categories', mySettings);
	});
}
module.exports = Controllers;

<|endoftext|>


<commit_before>const express       = require('express')
const google        = require('googleapis')
const router        = express.Router()
const youtube       = google.youtube('v3')
const defaultConfig = require('../config')
const featured      = require('../data/featured_playlists.js')

router.get('/:id', (req, res) => {
  const videos = []
  var title, description, player

  if (featured.indexOf(req.params.id) == -1) {
    return 'Error'
  }

  // Get config object ready for this request
  var config = Object.assign({
    part: 'snippet,contentDetails',
    playlistId: req.params.id,
    maxResults: 20
  }, defaultConfig)

  youtube.playlists.list(config, (err, playlists) => {
    const series = playlists.items.filter((item) => {
      return item.id == req.params.id
    })

    title = series[0].snippet.title
    description = series[0].snippet.description

    youtube.playlistItems.list(config, (err, playlist) => {
      playlist.items.map((item) => {
        videos.push({
          id: item.contentDetails.videoId,
          title: item.snippet.title,
          description: item.snippet.description
        })
      })

      // Get config object ready for this request
      config = Object.assign({
        id: videos[0].id,
        part: 'player'
      }, defaultConfig)

      youtube.videos.list(config, (err, vids) => {
        player = vids.items.map((video) => {
          return video.player.embedHtml
        })

        res.render('playlist', {
          title: 'Nodecasts',
          message: title,
          videos: videos,
          description: description,
          player: player
        })
      })
    })
  })
})

module.exports = router
<commit_msg>fix bug from playlists<commit_after>const express       = require('express')
const google        = require('googleapis')
const router        = express.Router()
const youtube       = google.youtube('v3')
const defaultConfig = require('../config')

router.get('/:id', (req, res) => {
  const videos = []
  var title, description, player

  // Get config object ready for this request
  var config = Object.assign({
    part: 'snippet,contentDetails',
    playlistId: req.params.id,
    maxResults: 20
  }, defaultConfig)

  youtube.playlists.list(config, (err, playlists) => {
    const series = playlists.items.filter((item) => {
      return item.id == req.params.id
    })

    title = series[0].snippet.title
    description = series[0].snippet.description

    youtube.playlistItems.list(config, (err, playlist) => {
      playlist.items.map((item) => {
        videos.push({
          id: item.contentDetails.videoId,
          title: item.snippet.title,
          description: item.snippet.description
        })
      })

      // Get config object ready for this request
      config = Object.assign({
        id: videos[0].id,
        part: 'player'
      }, defaultConfig)

      youtube.videos.list(config, (err, vids) => {
        player = vids.items.map((video) => {
          return video.player.embedHtml
        })

        res.render('playlist', {
          title: 'Nodecasts',
          message: title,
          videos: videos,
          description: description,
          player: player
        })
      })
    })
  })
})

module.exports = router
<|endoftext|>


<commit_before>/**
 * Camera constructor
 *
 * @class Roguelike.Camera
 * @classdesc A Camera that follows an object in the viewport on the canvas
 *
 * @property {Roguelike.Game} game - Reference to the current game object
 * @param {object} position - The x and y coordinate of this Camera, in pixels
 */
Roguelike.Camera = function(game, position) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {object} position - The x and y top left coordinates of this camera, in pixels
	 */
	this.position = position;

	/**
	 * @property {int} viewportWidth - The width of the game's canvas, in pixels
	 */
	this.viewportWidth = game.settings.canvas.width;

	/**
	 * @property {int} viewportHeight - The height of the game's canvas, in pixels
	 */
	this.viewportHeight = game.settings.canvas.height;

	/**
	 * @property {int} minimumDistanceX - The minimal distance from horizontal borders before the camera starts to move, in pixels
	 */
	this.minimumDistanceX = 0;

	/**
	 * @property {int} minimumDistanceY - The minimal distance from vertical borders before the camera starts to move, in pixels
	 */
	this.minimumDistanceY = 0;

	/**
	 * @property {object} followObject - The object that should be followed by the camera
	 */
	this.followObject = null;

	/**
	 * @property {Roguelike.Boundary} viewportBoundary - The boundary that represents the viewport
	 */
	this.viewportBoundary = new Roguelike.Boundary(
		this.position.x * game.settings.tileSize,
		this.position.y * game.settings.tileSize,
		this.viewportWidth,
		this.viewportHeight
	);

	/**
	 * @property {Roguelike.Boundary} mapBoundary - The boundary that represents the viewport
	 */
	this.mapBoundary = new Roguelike.Boundary(
		0,
		0,
		game.settings.tilesX * game.settings.tileSize,
		game.settings.tilesY * game.settings.tileSize
	);

};

Roguelike.Camera.prototype = {

	/**
	 * Function to call when you want to follow a specific object
	 * @protected
	 *
	 * @param {Roguelike.Entity} followObject - The entity that should be followed by the camera, this entity is required to have the position component
	 * @param {int} minimumDistanceX - The minimal distance from horizontal borders before the camera starts to move
	 * @param {int} minimumDistanceY - The minimal distance from vertical borders before the camera starts to move
	 */
	follow: function(followObject, minimumDistanceX, minimumDistanceY) {

		//Set the follow object to be the object that's passed along
		//Object needs to have a position variable, containing an
		//X and an Y value, in tiles
		this.followObject = followObject.components.position;
		this.minimumDistanceX = minimumDistanceX;
		this.minimumDistanceY = minimumDistanceY;

	},

	/**
	 * Function to update the camera to a new position, for example following an object
	 * @protected
	 */
	update: function() {

		//Check if the camera even has to move
		if(this.followObject !== null) {

			//Move the camera horizontal first
			if((this.followObject.position.x * this.game.settings.tileSize) - this.position.x + this.minimumDistanceX > this.viewportWidth) {

				//Set the new horizontal position for the camera
				this.position.x = (this.followObject.position.x * this.game.settings.tileSize) - (this.viewportWidth - this.minimumDistanceX);

			}else if((this.followObject.position.x * this.game.settings.tileSize) - this.minimumDistanceX < this.position.x) {

				//Set the new horizontal position for the camera
				this.position.x = (this.followObject.position.x * this.game.settings.tileSize) - this.minimumDistanceX;

			}

			//Then move the camera vertical
			if((this.followObject.position.y * this.game.settings.tileSize) - this.position.y + this.minimumDistanceY > this.viewportHeight) {

				//Set the new vertical position for the camera
				this.position.y = (this.followObject.position.y * this.game.settings.tileSize) - (this.viewportHeight - this.minimumDistanceY);

			}else if((this.followObject.position.y * this.game.settings.tileSize) - this.minimumDistanceY < this.position.y) {

				//Set the new vertical position for the camera
				this.position.y = (this.followObject.position.y * this.game.settings.tileSize) - this.minimumDistanceY;

			}

		}

		//Now we update our viewport's boundaries
		this.viewportBoundary.set(this.position.x, this.position.y);

		//We don't want the camera leaving the world's boundaries, for obvious reasons
		if(!this.viewportBoundary.isWithin(this.mapBoundary)) {

			//Left
			if(this.viewportBoundary.left < this.mapBoundary.left) {
				this.position.x = this.mapBoundary.left;
			}

			//Top
			if(this.viewportBoundary.top < this.mapBoundary.top) {
				this.position.y = this.mapBoundary.top;
			}

			//Right
			if(this.viewportBoundary.right > this.mapBoundary.right) {
				this.position.x = this.mapBoundary.right - this.viewportWidth;
			}

			//Bottom
			if(this.viewportBoundary.bottom > this.mapBoundary.bottom) {
				this.position.y = this.mapBoundary.bottom - this.viewportHeight;
			}

		}

	}

};
<commit_msg>The camera object now tracks the position of the specified entities position component.<commit_after>/**
 * Camera constructor
 *
 * @class Roguelike.Camera
 * @classdesc A Camera that follows an object in the viewport on the canvas
 *
 * @property {Roguelike.Game} game - Reference to the current game object
 * @param {object} position - The x and y coordinate of this Camera, in pixels
 */
Roguelike.Camera = function(game, position) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {object} position - The x and y top left coordinates of this camera, in pixels
	 */
	this.position = position;

	/**
	 * @property {int} viewportWidth - The width of the game's canvas, in pixels
	 */
	this.viewportWidth = game.settings.canvas.width;

	/**
	 * @property {int} viewportHeight - The height of the game's canvas, in pixels
	 */
	this.viewportHeight = game.settings.canvas.height;

	/**
	 * @property {int} minimumDistanceX - The minimal distance from horizontal borders before the camera starts to move, in pixels
	 */
	this.minimumDistanceX = 0;

	/**
	 * @property {int} minimumDistanceY - The minimal distance from vertical borders before the camera starts to move, in pixels
	 */
	this.minimumDistanceY = 0;

	/**
	 * @property {object} followObject - The object that should be followed by the camera
	 */
	this.followObject = null;

	/**
	 * @property {Roguelike.Boundary} viewportBoundary - The boundary that represents the viewport
	 */
	this.viewportBoundary = new Roguelike.Boundary(
		this.position.x * game.settings.tileSize,
		this.position.y * game.settings.tileSize,
		this.viewportWidth,
		this.viewportHeight
	);

	/**
	 * @property {Roguelike.Boundary} mapBoundary - The boundary that represents the viewport
	 */
	this.mapBoundary = new Roguelike.Boundary(
		0,
		0,
		game.settings.tilesX * game.settings.tileSize,
		game.settings.tilesY * game.settings.tileSize
	);

};

Roguelike.Camera.prototype = {

	/**
	 * Function to call when you want to follow a specific object
	 * @protected
	 *
	 * @param {Roguelike.Entity} followObject - The entity that should be followed by the camera, this entity is required to have the position component
	 * @param {int} minimumDistanceX - The minimal distance from horizontal borders before the camera starts to move
	 * @param {int} minimumDistanceY - The minimal distance from vertical borders before the camera starts to move
	 */
	follow: function(followObject, minimumDistanceX, minimumDistanceY) {

		//Set the follow object to be the object that's passed along
		//Object needs to have a position variable, containing an
		//X and an Y value, in tiles
		this.followObject = followObject.components.position;
		this.minimumDistanceX = minimumDistanceX;
		this.minimumDistanceY = minimumDistanceY;

	},

	/**
	 * Function to update the camera to a new position, for example following an object
	 * @protected
	 */
	update: function() {

		//Check if the camera even has to move
		if(this.followObject !== null) {

			//Move the camera horizontal first
			if((this.followObject.x * this.game.settings.tileSize) - this.position.x + this.minimumDistanceX > this.viewportWidth) {

				//Set the new horizontal position for the camera
				this.position.x = (this.followObject.x * this.game.settings.tileSize) - (this.viewportWidth - this.minimumDistanceX);

			}else if((this.followObject.x * this.game.settings.tileSize) - this.minimumDistanceX < this.position.x) {

				//Set the new horizontal position for the camera
				this.position.x = (this.followObject.x * this.game.settings.tileSize) - this.minimumDistanceX;

			}

			//Then move the camera vertical
			if((this.followObject.y * this.game.settings.tileSize) - this.position.y + this.minimumDistanceY > this.viewportHeight) {

				//Set the new vertical position for the camera
				this.position.y = (this.followObject.y * this.game.settings.tileSize) - (this.viewportHeight - this.minimumDistanceY);

			}else if((this.followObject.y * this.game.settings.tileSize) - this.minimumDistanceY < this.position.y) {

				//Set the new vertical position for the camera
				this.position.y = (this.followObject.y * this.game.settings.tileSize) - this.minimumDistanceY;

			}

		}

		//Now we update our viewport's boundaries
		this.viewportBoundary.set(this.position.x, this.position.y);

		//We don't want the camera leaving the world's boundaries, for obvious reasons
		if(!this.viewportBoundary.isWithin(this.mapBoundary)) {

			//Left
			if(this.viewportBoundary.left < this.mapBoundary.left) {
				this.position.x = this.mapBoundary.left;
			}

			//Top
			if(this.viewportBoundary.top < this.mapBoundary.top) {
				this.position.y = this.mapBoundary.top;
			}

			//Right
			if(this.viewportBoundary.right > this.mapBoundary.right) {
				this.position.x = this.mapBoundary.right - this.viewportWidth;
			}

			//Bottom
			if(this.viewportBoundary.bottom > this.mapBoundary.bottom) {
				this.position.y = this.mapBoundary.bottom - this.viewportHeight;
			}

		}

	}

};
<|endoftext|>


<commit_before>// Let's serve up the data file via json
var http = require( 'http' );
// Let's get the filestream api to write the temp data
var fs = require( 'fs' );
// Let's get the GPIO api for the rpi
var gpio = require( 'rpi-gpio' );
// Global request object for http get/post
var needle = require('needle');

var spiADC = {
	'options': {
		'channel': 0,
		'resistances_to_keep': 30,
		'ignore_data_beyond_pct': 0.10
	},
	'SPI': require( 'spi' ),
	'isOpen': false,
	'device': '',
	'resistances': [],
	'res_index': 0,
	'series_resistor': 10000,
	'thermistor': {
		'nominal_resistance': 10000,
		'nominal_temp': 25,
		'bcoefficient': 3950
	},
	open: function(){
		if(this.isOpen === true){
			console.log( 'Cannot open a device that is already open!' );
			return;
		}

		this.device = new this.SPI.Spi('/dev/spidev0.0', {}, function(s){s.open();});

		this.isOpen = true;
	},
	handleSpiData: function(device, buf){

		var data = ((buf[1]&3) << 8) + buf[2];

		// Let's exclude data readings that are 0
		// and readings that are more than +/- 10% of the previous reading (indicates a spike we should ignore)
		if( data === 0 && Math.abs( ( data - this.resistances[this.resistances.length-1] ) / this.resistances[this.resistances.length-1] ) > this.options.ignore_data_beyond_pct ){
			// Let's discard this reading
			return -1;
		}
		return data;
	},
	storeSpiData: function( device, data ){
		this.resistances[this.res_index] = data;
		//console.log('[' + this.res_index + '] ' + data + ' on device ' + device.device);
	},
	setNextResistanceIndex: function(){
		this.res_index++;
		if(this.res_index > (this.options.resistances_to_keep -1) ){
			this.res_index = 0;
		}
	},
	read: function(){
		var self = this;
		var txbuf = new Buffer([1, (8 + this.options.channel) << 4, 0]);
		var rxbuf = new Buffer([ 0x00, 0x00, 0x00 ]);

		this.device.transfer( txbuf, rxbuf, function( device, buf ){
			var data = self.handleSpiData( device, buf );

			if( data > 0 ){
				self.storeSpiData( device, data );
				self.setNextResistanceIndex();
			}
		});
	},
	getAverageData: function(){
		if( this.resistances.length === 0 ){
			return 0;
		}

		var sum = 0;
		for(var i = 0; i < this.resistances.length; i++){
			sum += parseInt(this.resistances[i]);
		}

		return sum / this.resistances.length;

	},
	calculate_thermistor_resistance: function( average_raw ){
		console.log('average raw: ' + average_raw);

		var thermistor_resistance =  (1023 / average_raw) - 1;
		thermistor_resistance = this.series_resistor / thermistor_resistance;
		thermistor_resistance = Math.round(thermistor_resistance * 100) / 100;

		var voltage = average_raw * 3.28 / 1023;
		console.log('voltage: ' + voltage);

		return thermistor_resistance;
	},
	steinhart: function( thermistor_resistance ){
		var steinhart = thermistor_resistance / this.thermistor.nominal_resistance;

		steinhart = Math.log( steinhart );
		steinhart = steinhart / this.thermistor.bcoefficient;
		steinhart += 1.0 / (this.thermistor.nominal_temp + 273.15);
		steinhart = 1.0 / steinhart;
		steinhart -= 273.15;
		steinhart = Math.round( steinhart * 100) / 100;

		return steinhart;
	},
	getAverageTemperature: function( average_resistance) {
		var thermistor_resistance = this.calculate_thermistor_resistance( average_resistance );
		var steinhart = this.steinhart( thermistor_resistance );

		console.log('thermistor resistance: ' + thermistor_resistance);
		console.log('thermistor temperature: ' + steinhart);

		return steinhart;
	}
};
var DataLogger = {
	'options': {
		'logfile': '',
		'endpointUrl': 'http://192.168.1.141/dev/test.php',
		'timeout': 5000
	},
	'txError': false,
	'data': [],
	init: function(logfile){
		this.options.logfile = logfile;
		// Return this object to be used once init'd
		return this;
	},
	addDataPoint: function(model){
		this.data.push(model);
	},
	writeDataToFile : function(){
		if( this.txError ) {
			return;
		}

		/* First load in the file contents */
		var self = this;
		fs.readFile(self.options.logfile, {'encoding': 'ascii'}, function (err, data) {
			if (err){
				throw err;
			}

			try{
				var fileData = [];

				if( data !== null && data !== '' ){
					fileData = JSON.parse(data);
				}

				var combinedData = fileData.concat(self.data);

				fs.writeFile(self.options.logfile, JSON.stringify(combinedData), { 'flag' : 'r+'}, function (err) {
					if (err){
						console.log(err);
						throw err;
					}

					self.data = [];
					console.log('It\'s saved!');
				});
			}catch( err ){
				//
			}
		});

	},
	readDataFile : function(){
		return fs.readFileSync(this.options.logfile, {'encoding': 'ascii'} );
	},
	sendDataUpdate: function(){
		var self = this;

		if( self.data.length === 0 ){
			return;
		}

		var postData = {
			payload: {
				value: JSON.stringify(self.data),
				content_type: 'application/json'
			}
		};

		needle.post( self.options.endpointUrl, postData, { timeout: self.options.timeout, multipart: true },
			function (error, response, body) {
				if (error || response.statusCode != 200) {
					/* We've got an error to deal with, let's set the error code till we get a successful send */
					self.txError = true;
				}else{
					self.txError = false;
				}
			}
		);
	}
};

var DataPointModel = {
	create: function(timestamp, data){
		return [timestamp, data];
	}
};

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
	response.writeHead( 200, {
		'Content-Type': 'application/json'
	});

	response.end( DataLogger.readDataFile() );
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

DataLogger.init( '/home/pi/thermo-app/data/readings.data' );

/* Open the spi device */
spiADC.open();
/* Start reading the data from the spi device every XX ms */
setInterval( function(){ spiADC.read(); }, 33);
/* Let's get an average every XX ms */
setInterval( function(){
	var averageData = spiADC.getAverageData();
	var averageTemp = spiADC.getAverageTemperature( averageData );
	var model = DataPointModel.create( Math.round(new Date().getTime() / 1000), averageTemp );
	DataLogger.addDataPoint(model);
}, 2000);
/* Write the data we've captured to the data file and send our updates to the web app */
setInterval( function(){
	DataLogger.sendDataUpdate();
	DataLogger.writeDataToFile();
}, 60000);<commit_msg>tweaking when I round<commit_after>// Let's serve up the data file via json
var http = require( 'http' );
// Let's get the filestream api to write the temp data
var fs = require( 'fs' );
// Let's get the GPIO api for the rpi
var gpio = require( 'rpi-gpio' );
// Global request object for http get/post
var needle = require('needle');

var spiADC = {
	'options': {
		'channel': 0,
		'resistances_to_keep': 30,
		'ignore_data_beyond_pct': 0.10
	},
	'SPI': require( 'spi' ),
	'isOpen': false,
	'device': '',
	'resistances': [],
	'res_index': 0,
	'series_resistor': 10000,
	'thermistor': {
		'nominal_resistance': 10000,
		'nominal_temp': 25,
		'bcoefficient': 3950
	},
	open: function(){
		if(this.isOpen === true){
			console.log( 'Cannot open a device that is already open!' );
			return;
		}

		this.device = new this.SPI.Spi('/dev/spidev0.0', {}, function(s){s.open();});

		this.isOpen = true;
	},
	handleSpiData: function(device, buf){

		var data = ((buf[1]&3) << 8) + buf[2];

		// Let's exclude data readings that are 0
		// and readings that are more than +/- 10% of the previous reading (indicates a spike we should ignore)
		if( data === 0 && Math.abs( ( data - this.resistances[this.resistances.length-1] ) / this.resistances[this.resistances.length-1] ) > this.options.ignore_data_beyond_pct ){
			// Let's discard this reading
			return -1;
		}
		return data;
	},
	storeSpiData: function( device, data ){
		this.resistances[this.res_index] = data;
		//console.log('[' + this.res_index + '] ' + data + ' on device ' + device.device);
	},
	setNextResistanceIndex: function(){
		this.res_index++;
		if(this.res_index > (this.options.resistances_to_keep -1) ){
			this.res_index = 0;
		}
	},
	read: function(){
		var self = this;
		var txbuf = new Buffer([1, (8 + this.options.channel) << 4, 0]);
		var rxbuf = new Buffer([ 0x00, 0x00, 0x00 ]);

		this.device.transfer( txbuf, rxbuf, function( device, buf ){
			var data = self.handleSpiData( device, buf );

			if( data > 0 ){
				self.storeSpiData( device, data );
				self.setNextResistanceIndex();
			}
		});
	},
	getAverageData: function(){
		if( this.resistances.length === 0 ){
			return 0;
		}

		var sum = 0;
		for(var i = 0; i < this.resistances.length; i++){
			sum += parseInt(this.resistances[i]);
		}

		return sum / this.resistances.length;

	},
	calculate_thermistor_resistance: function( average_raw ){
		console.log('average raw: ' + average_raw);

		var thermistor_resistance =  (1023 / average_raw) - 1;
		thermistor_resistance = this.series_resistor / thermistor_resistance;

		var voltage = average_raw * 3.28 / 1023;
		console.log('voltage: ' + voltage);

		return thermistor_resistance;
	},
	steinhart: function( thermistor_resistance ){
		var steinhart = thermistor_resistance / this.thermistor.nominal_resistance;

		steinhart = Math.log( steinhart );
		steinhart = steinhart / this.thermistor.bcoefficient;
		steinhart += 1.0 / (this.thermistor.nominal_temp + 273.15);
		steinhart = 1.0 / steinhart;
		steinhart -= 273.15;
		steinhart = Math.round( steinhart * 100) / 100;

		return steinhart;
	},
	getAverageTemperature: function( average_resistance) {
		var thermistor_resistance = this.calculate_thermistor_resistance( average_resistance );
		var steinhart = this.steinhart( thermistor_resistance );

		console.log('thermistor resistance: ' + thermistor_resistance);
		console.log('thermistor temperature: ' + steinhart);

		return steinhart;
	}
};
var DataLogger = {
	'options': {
		'logfile': '',
		'endpointUrl': 'http://192.168.1.141/dev/test.php',
		'timeout': 5000
	},
	'txError': false,
	'data': [],
	init: function(logfile){
		this.options.logfile = logfile;
		// Return this object to be used once init'd
		return this;
	},
	addDataPoint: function(model){
		this.data.push(model);
	},
	writeDataToFile : function(){
		if( this.txError ) {
			return;
		}

		/* First load in the file contents */
		var self = this;
		fs.readFile(self.options.logfile, {'encoding': 'ascii'}, function (err, data) {
			if (err){
				throw err;
			}

			try{
				var fileData = [];

				if( data !== null && data !== '' ){
					fileData = JSON.parse(data);
				}

				var combinedData = fileData.concat(self.data);

				fs.writeFile(self.options.logfile, JSON.stringify(combinedData), { 'flag' : 'r+'}, function (err) {
					if (err){
						console.log(err);
						throw err;
					}

					self.data = [];
					console.log('It\'s saved!');
				});
			}catch( err ){
				//
			}
		});

	},
	readDataFile : function(){
		return fs.readFileSync(this.options.logfile, {'encoding': 'ascii'} );
	},
	sendDataUpdate: function(){
		var self = this;

		if( self.data.length === 0 ){
			return;
		}

		var postData = {
			payload: {
				value: JSON.stringify(self.data),
				content_type: 'application/json'
			}
		};

		needle.post( self.options.endpointUrl, postData, { timeout: self.options.timeout, multipart: true },
			function (error, response, body) {
				if (error || response.statusCode != 200) {
					/* We've got an error to deal with, let's set the error code till we get a successful send */
					self.txError = true;
				}else{
					self.txError = false;
				}
			}
		);
	}
};

var DataPointModel = {
	create: function(timestamp, data){
		return [timestamp, data];
	}
};

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
	response.writeHead( 200, {
		'Content-Type': 'application/json'
	});

	response.end( DataLogger.readDataFile() );
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

DataLogger.init( '/home/pi/thermo-app/data/readings.data' );

/* Open the spi device */
spiADC.open();
/* Start reading the data from the spi device every XX ms */
setInterval( function(){ spiADC.read(); }, 33);
/* Let's get an average every XX ms */
setInterval( function(){
	var averageData = spiADC.getAverageData();
	var averageTemp = spiADC.getAverageTemperature( averageData );
	var model = DataPointModel.create( Math.round(new Date().getTime() / 1000), averageTemp );
	DataLogger.addDataPoint(model);
}, 2000);
/* Write the data we've captured to the data file and send our updates to the web app */
setInterval( function(){
	DataLogger.sendDataUpdate();
	DataLogger.writeDataToFile();
}, 60000);<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var BluebirdPromise = require('bluebird');
var Class = require('../util/class');
var EntryQuery = require('./query/entry');
var Schema = require('./schema');
var Migration = require('./migration');

/**
 * Create a new database.
 *
 * @since 1.0
 * @public
 * @constructor Database
 * @param {Object} connection The connection information.
 * @param {String} connection.adapter The adapter to use. Possible choices
 * are:
 *   - pg
 *   - mysql
 *   - sqlite
 * @param {String} connection.database The database to connect to.
 * @param {String} connection.username The username to connect with.
 * @param {String} connection.password The password to connect with.
 */
var Database = Class.extend(/** @lends Database# */{
  init: function(connection) {
    this._super();

    if (!connection) { throw new Error('Missing connection information.'); }
    this._connection = connection;
    this._adapter = _.isString(connection.adapter) ?
      this._loadAdapterClass(connection.adapter).create(connection) :
      connection.adapter;
    this._schema = Schema.create(this._adapter);
    this._query = EntryQuery.create(this._adapter);
  },

  /**
   * Disconnect a database.
   *
   * @return {Promise} A promise indicating that the database has been
   * disconnected.
   */
  disconnect: BluebirdPromise.method(function() {
    return this._adapter.disconnectAll();
  }),

  /**
   * Get a new migrator to handle migrations at the given path.
   *
   * @param {String} migrationsPath The path to the directory containing
   * migrations.
   * @return {Migration} The migrator
   */
  migrator: function(migrationsPath) {
    return Migration.create(this._query, this._schema, migrationsPath);
  },

  /**
   * Load an adapter class from an adapter name.
   *
   * @private
   * @param {String} name The name of the Adapter to load
   * @return {Class} The adapter class.
   */
  _loadAdapterClass: function(name) {
    var Adapter;
    try { Adapter = require('./adapters/' + name); }
    catch (e) {
      if (e.code === 'MODULE_NOT_FOUND') {
        throw new Error('No adapter found for ' + name);
      }
      else { throw e; }
    }
    return Adapter;
  }

});

/**
 * Documentation forthcoming.
 *
 * @private
 * @function Database~query
 */
var query = function(name) {
  return function() {
    return this._query[name].apply(this._query, arguments);
  };
};

/**
 * Access to a query object that is tied to this database.
 *
 * @name Database#query
 * @since 1.0
 * @public
 * @type {EntryQuery}
 * @readonly
 */
Database.defineAccessor('query');

/**
 * Access to a schema object that is tied to this database.
 *
 * @name Database#schema
 * @since 1.0
 * @public
 * @type {Schema}
 * @readonly
 */
Database.defineAccessor('schema');

Database.reopen(/** @lends Database# */ {

  /**
   * Shortcut for `db.query.select()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#select}
   */
  select: query('select'),

  /**
   * Shortcut for `db.query.insert()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#insert}
   */
  insert: query('insert'),

  /**
   * Shortcut for `db.query.delete()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#delete}
   */
  delete: query('delete')

});

module.exports = Database.reopenClass({ __name__: 'Database' });
<commit_msg>Better handling of module loading errors.<commit_after>'use strict';

var _ = require('lodash');
var BluebirdPromise = require('bluebird');
var Class = require('../util/class');
var EntryQuery = require('./query/entry');
var Schema = require('./schema');
var Migration = require('./migration');

/**
 * Create a new database.
 *
 * @since 1.0
 * @public
 * @constructor Database
 * @param {Object} connection The connection information.
 * @param {String} connection.adapter The adapter to use. Possible choices
 * are:
 *   - pg
 *   - mysql
 *   - sqlite
 * @param {String} connection.database The database to connect to.
 * @param {String} connection.username The username to connect with.
 * @param {String} connection.password The password to connect with.
 */
var Database = Class.extend(/** @lends Database# */{
  init: function(connection) {
    this._super();

    if (!connection) { throw new Error('Missing connection information.'); }
    this._connection = connection;
    this._adapter = _.isString(connection.adapter) ?
      this._loadAdapterClass(connection.adapter).create(connection) :
      connection.adapter;
    this._schema = Schema.create(this._adapter);
    this._query = EntryQuery.create(this._adapter);
  },

  /**
   * Disconnect a database.
   *
   * @return {Promise} A promise indicating that the database has been
   * disconnected.
   */
  disconnect: BluebirdPromise.method(function() {
    return this._adapter.disconnectAll();
  }),

  /**
   * Get a new migrator to handle migrations at the given path.
   *
   * @param {String} migrationsPath The path to the directory containing
   * migrations.
   * @return {Migration} The migrator
   */
  migrator: function(migrationsPath) {
    return Migration.create(this._query, this._schema, migrationsPath);
  },

  /**
   * Load an adapter class from an adapter name.
   *
   * @private
   * @param {String} name The name of the Adapter to load
   * @return {Class} The adapter class.
   */
  _loadAdapterClass: function(name) {
    var Adapter;
    try { Adapter = require('./adapters/' + name); }
    catch (e) {
      var regex = /'\.\/adapters\/\w+'/;
      if (e.code === 'MODULE_NOT_FOUND' && e.message.match(regex)) {
        throw new Error('No adapter found for ' + name);
      }
      else { throw e; }
    }
    return Adapter;
  }

});

/**
 * Documentation forthcoming.
 *
 * @private
 * @function Database~query
 */
var query = function(name) {
  return function() {
    return this._query[name].apply(this._query, arguments);
  };
};

/**
 * Access to a query object that is tied to this database.
 *
 * @name Database#query
 * @since 1.0
 * @public
 * @type {EntryQuery}
 * @readonly
 */
Database.defineAccessor('query');

/**
 * Access to a schema object that is tied to this database.
 *
 * @name Database#schema
 * @since 1.0
 * @public
 * @type {Schema}
 * @readonly
 */
Database.defineAccessor('schema');

Database.reopen(/** @lends Database# */ {

  /**
   * Shortcut for `db.query.select()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#select}
   */
  select: query('select'),

  /**
   * Shortcut for `db.query.insert()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#insert}
   */
  insert: query('insert'),

  /**
   * Shortcut for `db.query.delete()`.
   *
   * @since 1.0
   * @public
   * @method
   * @see {@link Database#query}
   * @see {@link EntryQuery#delete}
   */
  delete: query('delete')

});

module.exports = Database.reopenClass({ __name__: 'Database' });
<|endoftext|>


<commit_before>require('fastclick')(document.body);
const createApp = require('../createApp');
const createDemo = require('../components/createCloth');
const createAudio = require('../components/createAudio');
const createLoop = require('raf-loop');
const createBackground = require('three-vignette-background');
const palette = require('nice-color-palettes');
const isMobile = require('../isMobile');

const colors = palette[0];
const app = createApp({
  maxPixelRatio: 1.85,
  canvas: document.querySelector('#canvas')
});
app.renderer.setClearColor(colors[0]);
app.renderer.sortObjects = false;
if (!isMobile) app.renderer.shadowMap.enabled = true;
app.renderer.toneMapping = THREE.CineonToneMapping;
app.renderer.gammaInput = true;
app.renderer.gammaOutput = true;
app.renderer.shadowMap.type = THREE.PCFSoftShadowMap;

document.body.style.margin = '0';
document.body.style.overflow = 'hidden';

const header = document.querySelector('header');
const updateCopy = () => {
  header.children[0].textContent = 'TURN ON YOUR SOUND'
  header.children[1].textContent = isMobile ? 'AND TAP + HOLD.' : 'AND HOLD THE SPACE BAR'
};

const bg = createBackground({
  colors: [ colors[0], '#000' ]
});
app.scene.add(bg);

const component = createDemo(app, {
  colors
});
app.scene.add(component.object3d);
app.render();
component.object3d.visible = false;

const updateProgress = (amount) => {
  header.children[1].textContent = `${Math.floor(amount * 100)}%`;
};

const audio = createAudio(() => {
  component.object3d.visible = true;
  audio.removeListener('change', updateProgress);
  updateCopy();
  header.style.display = '';

  audio.once('change', () => {
    header.style.display = 'none';
  });
});

audio.on('progress', updateProgress);

audio.on('rate', rate => {
  component.setRate(rate);
});

createLoop(dt => {
  // audio.updateFrequencies();
  if (component.object3d.visible) {
    component.update(dt);
  }
  bg.style({
    aspect: app.width / app.height,
    aspectCorrection: true,
    scale: 3.5,
    // ensure even grain scale based on width/height
    grainScale: 0
  });
  app.updateControls();
  app.render();
  header.style.left = `${app.left + 20}px`;
  header.style.top = `${app.top + 20}px`;
}).start();
<commit_msg>period<commit_after>require('fastclick')(document.body);
const createApp = require('../createApp');
const createDemo = require('../components/createCloth');
const createAudio = require('../components/createAudio');
const createLoop = require('raf-loop');
const createBackground = require('three-vignette-background');
const palette = require('nice-color-palettes');
const isMobile = require('../isMobile');

const colors = palette[0];
const app = createApp({
  maxPixelRatio: 1.85,
  canvas: document.querySelector('#canvas')
});
app.renderer.setClearColor(colors[0]);
app.renderer.sortObjects = false;
if (!isMobile) app.renderer.shadowMap.enabled = true;
app.renderer.toneMapping = THREE.CineonToneMapping;
app.renderer.gammaInput = true;
app.renderer.gammaOutput = true;
app.renderer.shadowMap.type = THREE.PCFSoftShadowMap;

document.body.style.margin = '0';
document.body.style.overflow = 'hidden';

const header = document.querySelector('header');
const updateCopy = () => {
  header.children[0].textContent = 'TURN ON YOUR SOUND'
  header.children[1].textContent = isMobile ? 'AND TAP + HOLD.' : 'AND HOLD THE SPACE BAR.'
};

const bg = createBackground({
  colors: [ colors[0], '#000' ]
});
app.scene.add(bg);

const component = createDemo(app, {
  colors
});
app.scene.add(component.object3d);
app.render();
component.object3d.visible = false;

const updateProgress = (amount) => {
  header.children[1].textContent = `${Math.floor(amount * 100)}%`;
};

const audio = createAudio(() => {
  component.object3d.visible = true;
  audio.removeListener('change', updateProgress);
  updateCopy();
  header.style.display = '';

  audio.once('change', () => {
    header.style.display = 'none';
  });
});

audio.on('progress', updateProgress);

audio.on('rate', rate => {
  component.setRate(rate);
});

createLoop(dt => {
  // audio.updateFrequencies();
  if (component.object3d.visible) {
    component.update(dt);
  }
  bg.style({
    aspect: app.width / app.height,
    aspectCorrection: true,
    scale: 3.5,
    // ensure even grain scale based on width/height
    grainScale: 0
  });
  app.updateControls();
  app.render();
  header.style.left = `${app.left + 20}px`;
  header.style.top = `${app.top + 20}px`;
}).start();
<|endoftext|>


<commit_before>if (global.GENTLY) require = GENTLY.hijack(require);

var fs = require('fs'),
    sys = require('sys'),
    EventEmitter = require('events').EventEmitter;

var Dirty = exports.Dirty = function(path) {
  if (!(this instanceof Dirty)) return new Dirty(path);

  EventEmitter.call(this);

  this.path = path;
  this.writeBundle = 1000;

  this._docs = {};
  this._keys = [];
  this._queue = [];
  this._readStream = null;
  this._writeStream = null;

  this._load();
};

sys.inherits(Dirty, EventEmitter);
Dirty.Dirty = Dirty;
module.exports = Dirty;

Dirty.prototype.set = function(key, val, cb) {
  if (val === undefined) {
    this._keys.splice(this._keys.indexOf(key), 1)
    delete this._docs[key];
  } else {
    this._keys.push(key);
    this._docs[key] = val;
  }

  if (!cb) {
    this._queue.push(key);
  } else {
    this._queue.push([key, cb]);
  }

  this._maybeFlush();
};

Dirty.prototype.get = function(key) {
  return this._docs[key];
};

Dirty.prototype.rm = function(key, cb) {
  this.set(key, undefined, cb);
};

Dirty.prototype.forEach = function(fn) {
  var self = this,
  StopIteration = new Error("StopIteration");

  try {
    this._keys.forEach(function (key) {
      if (fn(key, self._docs[key]) === false) {
        throw StopIteration;
      }
    });
  } catch (ex) {
    if (ex != StopIteration) throw ex;
  }
};

Dirty.prototype._load = function() {
  if (!this.path) {
    return;
  }

  var self = this, buffer = '', length = 0;
  this._readStream = fs.createReadStream(this.path, {
    encoding: 'utf-8',
    flags: 'r'
  });

  this._readStream
    .on('error', function(err) {
      if (err.errno == process.binding('net').ENOENT) {
        self.emit('load', 0);
        return;
      }

      self.emit('error', err);
    })
    .on('data', function(chunk) {
      buffer += chunk;
      buffer = buffer.replace(/([^\n]+)\n/g, function(m, rowStr) {
        try {
          var row = JSON.parse(rowStr);
          if (!('key' in row)) {
            throw new Error();
          }
        } catch (e) {
          self.emit('error', new Error('Could not load corrupted row: '+rowStr));
          return '';
        }

        if (row.val === undefined) {
          if (row.key in self._docs) {
            length--;
          }
          delete self._docs[row.key];
        } else {
          if (!(row.key in self._docs)) {
            length++;
          }
          self._docs[row.key] = row.val;
        }
        return '';
      });
    })
    .on('end', function() {
      if (buffer.length) {
        self.emit('error', new Error('Corrupted row at the end of the db: '+buffer));
      }
      self.emit('load', length);
    });

  this._writeStream = fs.createWriteStream(this.path, {
    encoding: 'utf-8',
    flags: 'a'
  });

  this._writeStream.on('drain', function() {
    self.flushing = false;

    if (!self._queue.length) {
      self.emit('drain');
    } else {
      self._maybeFlush();
    }
  });
};

Dirty.prototype._maybeFlush = function() {
  if (this.flushing || !this.path || !this._queue.length) {
    return;
  }

  this._flush();
};

Dirty.prototype._flush = function() {
  var self = this,
      length = this._queue.length,
      bundleLength = 0,
      bundleStr = '',
      key,
      cbs = [];

  this.flushing = true;

  for (var i = 0; i < length; i++) {
    key = this._queue[i];
    if (Array.isArray(key)) {
      cbs.push(key[1]);
      key = key[0];
    }

    bundleStr += JSON.stringify({key: key, val: this._docs[key]})+'\n';
    bundleLength++;

    if (bundleLength < this.writeBundle && i < length - 1) {
      continue;
    }

    (function(cbs) {
      self._writeStream.write(bundleStr, function(err) {
        if (!cbs.length && err) {
          self.emit('error', err);
          return;
        }

        while (cbs.length) {
          cbs.shift()(err);
        }
      });
    })(cbs);

    bundleStr = '';
    bundleLength = 0;
    cbs = [];
  }

  this._queue = [];
};
<commit_msg>Make forEach even faster<commit_after>if (global.GENTLY) require = GENTLY.hijack(require);

var fs = require('fs'),
    sys = require('sys'),
    EventEmitter = require('events').EventEmitter;

var Dirty = exports.Dirty = function(path) {
  if (!(this instanceof Dirty)) return new Dirty(path);

  EventEmitter.call(this);

  this.path = path;
  this.writeBundle = 1000;

  this._docs = {};
  this._keys = [];
  this._queue = [];
  this._readStream = null;
  this._writeStream = null;

  this._load();
};

sys.inherits(Dirty, EventEmitter);
Dirty.Dirty = Dirty;
module.exports = Dirty;

Dirty.prototype.set = function(key, val, cb) {
  if (val === undefined) {
    this._keys.splice(this._keys.indexOf(key), 1)
    delete this._docs[key];
  } else {
    this._keys.push(key);
    this._docs[key] = val;
  }

  if (!cb) {
    this._queue.push(key);
  } else {
    this._queue.push([key, cb]);
  }

  this._maybeFlush();
};

Dirty.prototype.get = function(key) {
  return this._docs[key];
};

Dirty.prototype.rm = function(key, cb) {
  this.set(key, undefined, cb);
};

Dirty.prototype.forEach = function(fn) {

  for (var i = 0; i < this._keys.length; i++) {
    var key = this._keys[i];
    if (fn(key, this._docs[key]) === false) {
      break;
    }
  }

};

Dirty.prototype._load = function() {
  if (!this.path) {
    return;
  }

  var self = this, buffer = '', length = 0;
  this._readStream = fs.createReadStream(this.path, {
    encoding: 'utf-8',
    flags: 'r'
  });

  this._readStream
    .on('error', function(err) {
      if (err.errno == process.binding('net').ENOENT) {
        self.emit('load', 0);
        return;
      }

      self.emit('error', err);
    })
    .on('data', function(chunk) {
      buffer += chunk;
      buffer = buffer.replace(/([^\n]+)\n/g, function(m, rowStr) {
        try {
          var row = JSON.parse(rowStr);
          if (!('key' in row)) {
            throw new Error();
          }
        } catch (e) {
          self.emit('error', new Error('Could not load corrupted row: '+rowStr));
          return '';
        }

        if (row.val === undefined) {
          if (row.key in self._docs) {
            length--;
          }
          delete self._docs[row.key];
        } else {
          if (!(row.key in self._docs)) {
            length++;
          }
          self._docs[row.key] = row.val;
        }
        return '';
      });
    })
    .on('end', function() {
      if (buffer.length) {
        self.emit('error', new Error('Corrupted row at the end of the db: '+buffer));
      }
      self.emit('load', length);
    });

  this._writeStream = fs.createWriteStream(this.path, {
    encoding: 'utf-8',
    flags: 'a'
  });

  this._writeStream.on('drain', function() {
    self.flushing = false;

    if (!self._queue.length) {
      self.emit('drain');
    } else {
      self._maybeFlush();
    }
  });
};

Dirty.prototype._maybeFlush = function() {
  if (this.flushing || !this.path || !this._queue.length) {
    return;
  }

  this._flush();
};

Dirty.prototype._flush = function() {
  var self = this,
      length = this._queue.length,
      bundleLength = 0,
      bundleStr = '',
      key,
      cbs = [];

  this.flushing = true;

  for (var i = 0; i < length; i++) {
    key = this._queue[i];
    if (Array.isArray(key)) {
      cbs.push(key[1]);
      key = key[0];
    }

    bundleStr += JSON.stringify({key: key, val: this._docs[key]})+'\n';
    bundleLength++;

    if (bundleLength < this.writeBundle && i < length - 1) {
      continue;
    }

    (function(cbs) {
      self._writeStream.write(bundleStr, function(err) {
        if (!cbs.length && err) {
          self.emit('error', err);
          return;
        }

        while (cbs.length) {
          cbs.shift()(err);
        }
      });
    })(cbs);

    bundleStr = '';
    bundleLength = 0;
    cbs = [];
  }

  this._queue = [];
};
<|endoftext|>