<commit_before>var fs = require('fs');
var beautify = require('js-beautify').js_beautify;
var mkdirp = require('mkdirp');

function index_file(schemas, path) {

    var schemaStr = '\n\n';

    schemas.forEach((schema) => {
        schemaStr += 'require("./' + schema.name + '");' + '\n\n';
    })

    mkdirp(path + '/models', function(err) {
        fs.writeFile(path + "/models/index.js", schemaStr, function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("The file was saved!");
            }
        });

    });

}

function require_schemas(schemas){

    var requireStr ='';

    schemas.forEach((schema) => requireStr += 'var ' + schema.name + ' = require("./' + schema.name + '");' + '\n' )

}

function save_schema(schemas, path) {

    mkdirp(path + '/models', function(err) {

        schemas.forEach((schema) => {

            fs.writeFile(path + "/models/" + schema.name + ".js", generate_schema(schema), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("The file was saved!");
                }
            });
        })
    });

}

function generate_schema(schema) {

    var schemaStr = 'var mongoose = require("mongoose");' + "\n \n" + 'var schema = new mongoose.Schema({';
    var fieldLength = schema.fields.length;

    schema.fields.forEach((field, index) => {
        if (index === fieldLength - 1) {
            schemaStr += '\n' + parse_name_type(field) + '\n' + "});" + '\n \n' + 'mongoose.model("' + schema.name + '", schema);'
        } else {
            schemaStr += '\n' + parse_name_type(field) + ",";
        }

    })

    return beautify(schemaStr, { indent_size: 2 })

}

function generate_schemas_for_seeds(schemas,DB_NAME, questions){

    console.log(DB_NAME);

    DB_NAME = DB_NAME || 'MulchSeed';

    var connectionString = 'mongodb://localhost:27017/'+DB_NAME;

    var amtObj = {};

    questions.forEach(function(question){
        if(question.amount) amtObj[question.name] = question.amount;
    })

    var connectionString= '\nvar db = mongoose.connect("'+connectionString+'").connection; '
    var headerString = 'var mongoose = require("mongoose"); '+connectionString+ ' \nvar mchance = require(\'mchance\')(db);\n '

    var bodyStr = "";
    var footerStr = "db.seed({ ";

    schemas.map(function(schema, index){
        bodyStr+= generate_schema_With_Seed(schema);
        footerStr+= schema.name +": " + amtObj[schema.name] + (index==schemas.length-1?"": ",\n");
    });

    footerStr+= "}).then(function(dbCache){ mongoose.disconnect(); console.log(dbCache)})"

    return headerString +'\n\n'+ bodyStr +'\n \n'+ footerStr;

}

function generate_schema_With_Seed(schema, DB_NAME) {

    var schemaStr = ' \n var schema = new mongoose.Schema({'

    var fieldLength = schema.fields.length;

    schema.fields.forEach((field, index) => {
        if (index === fieldLength - 1) {
            schemaStr += '\n' + parse_name_type_with_seed(field) + '\n' + "});" + '\n \n' + 'mongoose.model("' + schema.name + '", schema);'
        } else {
            schemaStr += '\n' + parse_name_type_with_seed(field) + ",";
        }
    })
    schemaStr+="\n"
    return beautify(schemaStr, { indent_size: 2 })

}

function parse_name_type_with_seed(field) {
    var fieldStr = '';

    //do switch case

    if (field.type === "Array of...") {
        if (field.selectedArrType != 'String' && field.selectedArrType != 'Number' && field.selectedArrType != 'Boolean' && field.selectedArrType != 'Buffer' && field.selectedArrType != 'Date' ) {
            fieldStr += field.name + ': { type: [{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.selectedArrType + '"}], \nseedn: 2}';
        } else {
            fieldStr += field.name + ': { type: [{ type: ' + field.selectedArrType + ', \nseed:mchance.'+field.hint+' ' + parse_options(field.options) + '}], \nseedn: 2} ';
        }

    } else if (field.type === "Embed...") {
        fieldStr += field.name + ':{ type: ' + '[' + field.selectedEmbed + ']' + ' ' + parse_options(field.options) + '}';

    } else if (field.type === 'Reference to...') {

        fieldStr += field.name + ':{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.reference + '",' + parse_options(field.options) + '}';

    } else {

        fieldStr += field.name + ':{ type: ' + field.type + ' ' + parse_options(field.options) + (field.hint?", seed: mchance."+field.hint:"") + '}';
    }

    return fieldStr;

}

function parse_name_type(field) {
    var fieldStr = '';

    //do switch case

    if (field.type === "Array of...") {
        if (field.selectedArrType != 'String' && field.selectedArrType != 'Number' && field.selectedArrType != 'Boolean' && field.selectedArrType != 'Buffer' && field.selectedArrType != 'Date' ) {
            fieldStr += field.name + ':[{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.selectedArrType + '"}]';
        } else {

            fieldStr += field.name + ':{ type: ' + '[' + field.selectedArrType + ']' + ' ' + parse_options(field.options) + '}';

        }

    } else if (field.type === "Embed...") {
        fieldStr += field.name + ':{ type: ' + '[' + field.selectedEmbed + ']' + ' ' + parse_options(field.options) + '}';

    } else if (field.type === 'Reference to...') {

        fieldStr += field.name + ':{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.reference + '",' + parse_options(field.options) + '}';

    } else {

        fieldStr += field.name + ':{ type: ' + field.type + ' ' + parse_options(field.options) + '}';
    }

    return fieldStr;

}

//pasrses the options into a string
function parse_options(schemaOptions) {

    var optionStr = '';
    var size = Object.keys(schemaOptions).length;
    if(size>0) optionStr+=", "

    for (var i = 0; i < size; i++) {

        if (i === size - 1) {
            if (Object.keys(schemaOptions)[i] === 'default') {
                optionStr += Object.keys(schemaOptions)[i] + ': "' + schemaOptions[Object.keys(schemaOptions)[i]] + '"';
            } else {
                optionStr += Object.keys(schemaOptions)[i] + ': ' + schemaOptions[Object.keys(schemaOptions)[i]];
            }

        } else {
            if (Object.keys(schemaOptions)[i] === 'default') {
                optionStr += Object.keys(schemaOptions)[i] + ': "' + schemaOptions[Object.keys(schemaOptions)[i]] + '", ';
            } else {
                optionStr += Object.keys(schemaOptions)[i] + ': ' + schemaOptions[Object.keys(schemaOptions)[i]] + ', ';
            }

        }

    }

    return optionStr;
}

// var x = generate_schema ({name:'User',
// fields:[{name:'George', type:"String",options:{select:true, unique:true, default:"yay"}},{name:'Prakash', type:"String",options:{select:true, unique:true, default:"yay"}},{name:'Jai', type:"String",options:{select:true, unique:true, default:"yay"}<commit_msg>embed works<commit_after>var fs = require('fs');
var beautify = require('js-beautify').js_beautify;
var mkdirp = require('mkdirp');

function index_file(schemas, path) {

    var schemaStr = '\n\n';

    schemas.forEach((schema) => {
        schemaStr += 'require("./' + schema.name + '");' + '\n\n';
    })

    mkdirp(path + '/models', function(err) {
        fs.writeFile(path + "/models/index.js", schemaStr, function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("The file was saved!");
            }
        });

    });

}

function require_schemas(schemas){

    var requireStr ='';

    schemas.forEach((schema) => requireStr += 'var ' + schema.name + ' = require("./' + schema.name + '");' + '\n' )

}

function save_schema(schemas, path) {

    mkdirp(path + '/models', function(err) {

        schemas.forEach((schema) => {

            fs.writeFile(path + "/models/" + schema.name + ".js", generate_schema(schema), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("The file was saved!");
                }
            });
        })
    });

}

function embeded (schema){//ads require for embedded schema
    console.log('got in here');
    var requireStr ='';
    schema.fields.forEach((field) => {
        if(field.type === "Embed...")
            requireStr += 'var ' + field.selectedEmbed + ' = require("./' + field.selectedEmbed + '");' + '\n\n';

    })
    return requireStr;
}

function generate_schema(schema) {

    var embededStr = embeded(schema);

    var schemaStr = 'var mongoose = require("mongoose");' + "\n \n" + embededStr + 'var schema = new mongoose.Schema({';
    var fieldLength = schema.fields.length;

    schema.fields.forEach((field, index) => {
        if (index === fieldLength - 1) {
            schemaStr += '\n' + parse_name_type(field) + '\n' + "});" + '\n \n' + 'mongoose.model("' + schema.name + '", schema);'
        } else {
            schemaStr += '\n' + parse_name_type(field) + ",";
        }

    })

    return beautify(schemaStr, { indent_size: 2 })

}

function generate_schemas_for_seeds(schemas,DB_NAME, questions){

    console.log(DB_NAME);

    DB_NAME = DB_NAME || 'MulchSeed';

    var connectionString = 'mongodb://localhost:27017/'+DB_NAME;

    var amtObj = {};

    questions.forEach(function(question){
        if(question.amount) amtObj[question.name] = question.amount;
    })

    var connectionString= '\nvar db = mongoose.connect("'+connectionString+'").connection; '
    var headerString = 'var mongoose = require("mongoose"); '+connectionString+ ' \nvar mchance = require(\'mchance\')(db);\n '

    var bodyStr = "";
    var footerStr = "db.seed({ ";

    schemas.map(function(schema, index){
        bodyStr+= generate_schema_With_Seed(schema);
        footerStr+= schema.name +": " + amtObj[schema.name] + (index==schemas.length-1?"": ",\n");
    });

    footerStr+= "}).then(function(dbCache){ mongoose.disconnect(); console.log(dbCache)})"

    return headerString +'\n\n'+ bodyStr +'\n \n'+ footerStr;

}

function generate_schema_With_Seed(schema, DB_NAME) {

    var schemaStr = ' \n var schema = new mongoose.Schema({'

    var fieldLength = schema.fields.length;

    schema.fields.forEach((field, index) => {
        if (index === fieldLength - 1) {
            schemaStr += '\n' + parse_name_type_with_seed(field) + '\n' + "});" + '\n \n' + 'mongoose.model("' + schema.name + '", schema);'
        } else {
            schemaStr += '\n' + parse_name_type_with_seed(field) + ",";
        }
    })
    schemaStr+="\n"
    return beautify(schemaStr, { indent_size: 2 })

}

function parse_name_type_with_seed(field) {
    var fieldStr = '';

    //do switch case

    if (field.type === "Array of...") {
        if (field.selectedArrType != 'String' && field.selectedArrType != 'Number' && field.selectedArrType != 'Boolean' && field.selectedArrType != 'Buffer' && field.selectedArrType != 'Date' ) {
            fieldStr += field.name + ': { type: [{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.selectedArrType + '"}], \nseedn: 2}';
        } else {
            fieldStr += field.name + ': { type: [{ type: ' + field.selectedArrType + ', \nseed:mchance.'+field.hint+' ' + parse_options(field.options) + '}], \nseedn: 2} ';
        }

    } else if (field.type === "Embed...") {
        fieldStr += field.name + ':{ type: ' + '[' + field.selectedEmbed + ']' + ' ' + parse_options(field.options) + '}';

    } else if (field.type === 'Reference to...') {

        fieldStr += field.name + ':{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.reference + '",' + parse_options(field.options) + '}';

    } else {

        fieldStr += field.name + ':{ type: ' + field.type + ' ' + parse_options(field.options) + (field.hint?", seed: mchance."+field.hint:"") + '}';
    }

    return fieldStr;

}

function parse_name_type(field) {
    var fieldStr = '';

    //do switch case

    if (field.type === "Array of...") {
        if (field.selectedArrType != 'String' && field.selectedArrType != 'Number' && field.selectedArrType != 'Boolean' && field.selectedArrType != 'Buffer' && field.selectedArrType != 'Date' ) {
            fieldStr += field.name + ':[{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.selectedArrType + '"}]';
        } else {

            fieldStr += field.name + ':{ type: ' + '[' + field.selectedArrType + ']' + ' ' + parse_options(field.options) + '}';

        }

    } else if (field.type === "Embed...") {
        fieldStr += field.name + ':{ type: ' + '[' + field.selectedEmbed + ']' + ' ' + parse_options(field.options) + '}';

    } else if (field.type === 'Reference to...') {

        fieldStr += field.name + ':{ type: mongoose.Schema.Types.ObjectId, ref: "' + field.reference + '",' + parse_options(field.options) + '}';

    } else {

        fieldStr += field.name + ':{ type: ' + field.type + ' ' + parse_options(field.options) + '}';
    }

    return fieldStr;

}

//pasrses the options into a string
function parse_options(schemaOptions) {

    var optionStr = '';
    var size = Object.keys(schemaOptions).length;
    if(size>0) optionStr+=", "

    for (var i = 0; i < size; i++) {

        if (i === size - 1) {
            if (Object.keys(schemaOptions)[i] === 'default') {
                optionStr += Object.keys(schemaOptions)[i] + ': "' + schemaOptions[Object.keys(schemaOptions)[i]] + '"';
            } else {
                optionStr += Object.keys(schemaOptions)[i] + ': ' + schemaOptions[Object.keys(schemaOptions)[i]];
            }

        } else {
            if (Object.keys(schemaOptions)[i] === 'default') {
                optionStr += Object.keys(schemaOptions)[i] + ': "' + schemaOptions[Object.keys(schemaOptions)[i]] + '", ';
            } else {
                optionStr += Object.keys(schemaOptions)[i] + ': ' + schemaOptions[Object.keys(schemaOptions)[i]] + ', ';
            }

        }

    }

    return optionStr;
}

// var x = generate_schema ({name:'User',
// fields:[{name:'George', type:"String",options:{select:true, unique:true, default:"yay"}},{name:'Prakash', type:"String",options:{select:true, unique:true, default:"yay"}},{name:'Jai', type:"String",options:{select:true, unique:true, default:"yay"}<|endoftext|>


<commit_before>(function() {
  var canvas = this.__canvas = new fabric.Canvas('c', { selection: false });
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
  var line, isDown;
  var id = 'a';

  function makeCircle(left, top) {
    var c = new fabric.Circle({
      left: left,
      top: top,
      strokeWidth: 5,
      radius: 12,
      fill: '#fff',
      stroke: '#000',
      hasBorders: false,
      hasControls: false
    });

    // give the node an identifier and increment it for the next node
    c.id = id;
    id = ((parseInt(id, 36)+1).toString(36)).replace(/[0-9]/g,'a');

    // these are the channels that are connected to this node
    c.linesIn = [];
    c.linesOut = [];

    return c;
  } //makeCircle

  function drawLine(x1, y1, x2, y2) {
    // create a line...
    line = new fabric.Line([x1, y1, x2, y2], {
      fill: '#000',
      stroke: '#000',
      strokeWidth: 5,
      hasBorders: false,
      hasControls: false,
      selectable: false
    });

    // ...an arrowhead...
    var a = new fabric.Triangle({
      left: x2,
      top: y2,
      width: 20,
      height: 20,
      angle: calcArrowAngle(x1,y1,x2,y2),
      fill: '#000',
      hasBorders: false,
      hasControls: false
    });

    // ...and two circles
    var c1 = makeCircle(x1,y1);
    var c2 = makeCircle(x2,y2);

    // ...link them all together
    line.set({'arrow': a, 'circle1': c1, 'circle2': c2});
    a.set({'line': line});
    c1.linesOut.push(line);
    c2.linesIn.push(line);
    updateNode(c1);
    updateNode(c2);

    // magic
    updateLine(line, 2);

    // draw everything on the canvas
    canvas.add(line,a,c1,c2);
    canvas.renderAll();
  } //drawLine

  function updateNode(node) {
    if (node.linesIn.length) {
      if (node.linesOut.length)
        node.set({'nodetype':'mixed','fill':'#ff5'});
      else
        node.set({'nodetype':'drain','fill':'#f55'});
    }
    else
      node.set({'nodetype':'source','fill':'#55f'});
  }

  function updateLine(line, end) {
    // we first have update the end coordinates
    var x1 = line.circle1.get('left');
    var y1 = line.circle1.get('top');
    var x2 = line.circle2.get('left');
    var y2 = line.circle2.get('top');
    line.set({'x1':x1, 'y1':y1, 'x2':x2, 'y2':y2});

    if (x1 == x2 && y1 == y2) {
      line.arrow.set({'left': line.get('x2'), 'top': line.get('y2')});
    }
    else {
      // calculate the position of the arrow
      var length = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
      length = length - 22;//circle2.get('radius') - circle2.get('stroke');
      var x = Math.atan(Math.abs(y1-y2)/Math.abs(x1-x2));
      document.getElementById("x").value = x;
      if (end) {
        if (x2 > x1) {
          line.set({'x2': x1 + length * Math.cos(x)});
        } else {
          line.set({'x2': x1 - length * Math.cos(x)});
        }
        if (y2 > y1) {
          line.set({'y2': y1 + length * Math.sin(x)});
        } else {
          line.set({'y2': y1 - length * Math.sin(x)});
        }
      }
      line.arrow.set({'left': line.get('x2'), 'top': line.get('y2')});
      var angle = calcArrowAngle(line.get('x1'), line.get('y1'), line.get('x2'), line.get('y2'));
      line.arrow.set({'angle': angle});
    }

    canvas.renderAll();
    document.getElementById("x1").value = x1;
    document.getElementById("y1").value = y1;
    document.getElementById("x2").value = x2;
    document.getElementById("y2").value = y2;
    document.getElementById("angle").value = angle;
  } //updateLine

  // calculate the correct angle for the arrowhead
  function calcArrowAngle(x1, y1, x2, y2) {
    var angle = 0, x, y;
    x = (x2 - x1);
    y = (y2 - y1);

    if (x === 0) {
      angle = (y === 0) ? 0 : (y > 0) ? Math.PI / 2 : Math.PI * 3 / 2;
    } else if (y === 0) {
      angle = (x > 0) ? 0 : Math.PI;
    } else {
      angle = (x < 0) ? Math.atan(y / x) + Math.PI : (y < 0) ? Math.atan(y / x) + (2 * Math.PI) : Math.atan(y / x);
    }

    return (angle * 180 / Math.PI) + 90;
  } //calcArrowAngle

  function enumerate() {
    document.getElementById('text').innerHTML = "";
    canvas.forEachObject(function(obj) {
      if (obj.type == 'circle')
        document.getElementById('text').innerHTML += obj.id + " ";
    });
  }

  function updateText() {
    var s = '';
    // TODO: traverse id's
    canvas.forEachObject(function(obj) {
      if (obj.type == "line")
        s += 'sync(' + obj.circle1.id + ',' + obj.circle2.id + ') ';
    });
    document.getElementById('text').innerHTML = s;
  }

  canvas.on('object:moving', function(e) {
    var p = e.target;
    p.setCoords();
  }); //object:moving

  canvas.on('object:added', function(e) {
    updateText();
  }); //object:added

  canvas.on('object:removed', function(e) {
    updateText();
  }); //object:added

  canvas.on('mouse:down', function(e) {
    isDown = true;
    if (canvas.getActiveObject())
      return;
    var pointer = canvas.getPointer(e.e);
    drawLine(pointer.x,pointer.y,pointer.x,pointer.y);
    canvas.setActiveObject(line.circle2);
    updateLine(line,2);
  }); //mouse:down

  canvas.on('mouse:move', function(e){
    if (!isDown)
      return;
    var pointer = canvas.getPointer(e.e);
    var p = canvas.getActiveObject();
    p.set({left: pointer.x, top: pointer.y});

    canvas.forEachObject(function(obj) {
      if (obj !== p && obj.get('type') === "circle" && p.intersectsWithObject(obj)) {
        if(Math.abs(p.left-obj.left) < 10 && Math.abs(p.top-obj.top) < 10) {
          p.setLeft(obj.getLeft());
          p.setTop(obj.getTop());
          p.setCoords();
        }
      }

    });

    for (i = 0; i < p.linesIn.length; i++)
      updateLine(p.linesIn[i], 2);
    for (i = 0; i < p.linesOut.length; i++)
      updateLine(p.linesOut[i], 1);
    //canvas.renderAll();
  }); //mouse:move

  canvas.on('mouse:up', function(e){
    isDown = false;
    var p = canvas.getActiveObject();
    canvas.forEachObject(function(obj) {
      if (!obj || obj.id === p.id || obj.get('type') !== "circle")
        return;
      if (p.intersectsWithObject(obj)) {
        if(Math.abs(p.left-obj.left) < 10 && Math.abs(p.top-obj.top) < 10) {
          for (i = 0; i < p.linesIn.length; i++) {
            p.linesIn[i].circle2 = obj;
            obj.linesIn.push(p.linesIn[i]);
          }
          for (i = 0; i < p.linesOut.length; i++) {
            p.linesOut[i].circle1 = obj;
            obj.linesOut.push(p.linesOut[i]);
          }
          canvas.remove(p);
          updateNode(obj);
          obj.bringToFront();
          canvas.renderAll();
        }
      }
    });
  });

  function downloadsvg() {
    var a = document.getElementById("download");
    a.href = 'data:image/svg+xml;base64,' + window.btoa(canvas.toSVG());
    a.click();
  }

  drawLine(100,100,200,100);
  drawLine(300,100,400,100);

})();

<commit_msg>Applied get and set functions<commit_after>(function() {
  var canvas = this.__canvas = new fabric.Canvas('c', { selection: false });
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
  var line, isDown;
  var id = 'a';

  function makeCircle(left, top) {
    var c = new fabric.Circle({
      left: left,
      top: top,
      strokeWidth: 5,
      radius: 12,
      fill: '#fff',
      stroke: '#000',
      hasBorders: false,
      hasControls: false
    });

    // give the node an identifier and increment it for the next node
    c.set({'id': id});
    id = ((parseInt(id, 36)+1).toString(36)).replace(/[0-9]/g,'a');

    // these are the channels that are connected to this node
    c.linesIn = [];
    c.linesOut = [];

    return c;
  } //makeCircle

  function drawLine(x1, y1, x2, y2) {
    // create a line...
    line = new fabric.Line([x1, y1, x2, y2], {
      fill: '#000',
      stroke: '#000',
      strokeWidth: 5,
      hasBorders: false,
      hasControls: false,
      selectable: false
    });

    // ...an arrowhead...
    var a = new fabric.Triangle({
      left: x2,
      top: y2,
      width: 20,
      height: 20,
      angle: calcArrowAngle(x1,y1,x2,y2),
      fill: '#000',
      hasBorders: false,
      hasControls: false
    });

    // ...and two circles
    var c1 = makeCircle(x1,y1);
    var c2 = makeCircle(x2,y2);

    // ...link them all together
    line.set({'arrow': a, 'circle1': c1, 'circle2': c2});
    a.set({'line': line});
    c1.linesOut.push(line);
    c2.linesIn.push(line);
    updateNode(c1);
    updateNode(c2);

    // magic
    updateLine(line, 2);

    // draw everything on the canvas
    canvas.add(line,a,c1,c2);
    canvas.renderAll();
  } //drawLine

  function updateNode(node) {
    if (node.linesIn.length) {
      if (node.linesOut.length)
        node.set({'nodetype':'mixed','fill':'#ff5'});
      else
        node.set({'nodetype':'drain','fill':'#f55'});
    }
    else
      node.set({'nodetype':'source','fill':'#55f'});
  }

  function updateLine(line, end) {
    // we first have to reset the end coordinates
    var x1 = line.circle1.get('left');
    var y1 = line.circle1.get('top');
    var x2 = line.circle2.get('left');
    var y2 = line.circle2.get('top');
    line.set({'x1':x1, 'y1':y1, 'x2':x2, 'y2':y2});

    if (x1 == x2 && y1 == y2) {
      line.arrow.set({'left': line.get('x2'), 'top': line.get('y2')});
    }
    else {
      // calculate the position of the arrow
      var length = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
      length = length - 22;//circle2.get('radius') - circle2.get('stroke');
      var x = Math.atan(Math.abs(y1-y2)/Math.abs(x1-x2));
      document.getElementById("x").value = x;
      if (end) {
        if (x2 > x1) {
          line.set({'x2': x1 + length * Math.cos(x)});
        } else {
          line.set({'x2': x1 - length * Math.cos(x)});
        }
        if (y2 > y1) {
          line.set({'y2': y1 + length * Math.sin(x)});
        } else {
          line.set({'y2': y1 - length * Math.sin(x)});
        }
      }
      line.arrow.set({'left': line.get('x2'), 'top': line.get('y2')});
      var angle = calcArrowAngle(line.get('x1'), line.get('y1'), line.get('x2'), line.get('y2'));
      line.arrow.set({'angle': angle});
    }

    canvas.renderAll();
    document.getElementById("x1").value = x1;
    document.getElementById("y1").value = y1;
    document.getElementById("x2").value = x2;
    document.getElementById("y2").value = y2;
    document.getElementById("angle").value = angle;
  } //updateLine

  // calculate the correct angle for the arrowhead
  function calcArrowAngle(x1, y1, x2, y2) {
    var angle = 0, x, y;
    x = (x2 - x1);
    y = (y2 - y1);

    if (x === 0) {
      angle = (y === 0) ? 0 : (y > 0) ? Math.PI / 2 : Math.PI * 3 / 2;
    } else if (y === 0) {
      angle = (x > 0) ? 0 : Math.PI;
    } else {
      angle = (x < 0) ? Math.atan(y / x) + Math.PI : (y < 0) ? Math.atan(y / x) + (2 * Math.PI) : Math.atan(y / x);
    }

    return ((angle * 180 / Math.PI) + 90) % 360;
  } //calcArrowAngle

  function enumerate() {
    document.getElementById('text').innerHTML = "";
    canvas.forEachObject(function(obj) {
      if (obj.type == 'circle')
        document.getElementById('text').innerHTML += obj.id + " ";
    });
  }

  function updateText() {
    var s = '';
    // TODO: traverse id's
    canvas.forEachObject(function(obj) {
      if (obj.type == "line")
        s += 'sync(' + obj.circle1.id + ',' + obj.circle2.id + ') ';
    });
    document.getElementById('text').innerHTML = s;
  }

  canvas.on('object:moving', function(e) {
    var p = e.target;
    p.setCoords();
  }); //object:moving

  canvas.on('object:added', function(e) {
    updateText();
  }); //object:added

  canvas.on('object:removed', function(e) {
    updateText();
  }); //object:added

  canvas.on('mouse:down', function(e) {
    isDown = true;
    if (canvas.getActiveObject())
      return;
    var pointer = canvas.getPointer(e.e);
    drawLine(pointer.x,pointer.y,pointer.x,pointer.y);
    canvas.setActiveObject(line.circle2);
    updateLine(line,2);
  }); //mouse:down

  canvas.on('mouse:move', function(e){
    if (!isDown)
      return;
    var pointer = canvas.getPointer(e.e);
    var p = canvas.getActiveObject();
    p.set({'left': pointer.x, 'top': pointer.y});

    canvas.forEachObject(function(obj) {
      if (obj !== p && obj.get('type') === "circle" && p.intersectsWithObject(obj)) {
        if(Math.abs(p.left-obj.left) < 10 && Math.abs(p.top-obj.top) < 10) {
          p.set({'left': obj.getLeft(), 'top': obj.getTop()});
          p.setCoords();
        }
      }

    });

    for (i = 0; i < p.linesIn.length; i++)
      updateLine(p.linesIn[i], 2);
    for (i = 0; i < p.linesOut.length; i++)
      updateLine(p.linesOut[i], 1);
    //canvas.renderAll();
  }); //mouse:move

  canvas.on('mouse:up', function(e){
    isDown = false;
    var p = canvas.getActiveObject();
    canvas.forEachObject(function(obj) {
      if (!obj || obj.get('id') == p.get('id') || obj.get('type') !== "circle")
        return;
      if (p.intersectsWithObject(obj)) {
        if(Math.abs(p.left-obj.left) < 10 && Math.abs(p.top-obj.top) < 10) {
          for (i = 0; i < p.linesIn.length; i++) {
            p.linesIn[i].circle2 = obj;
            obj.linesIn.push(p.linesIn[i]);
          }
          for (i = 0; i < p.linesOut.length; i++) {
            p.linesOut[i].circle1 = obj;
            obj.linesOut.push(p.linesOut[i]);
          }
          canvas.remove(p);
          updateNode(obj);
          obj.bringToFront();
          canvas.renderAll();
        }
      }
    });
  });

  function downloadsvg() {
    var a = document.getElementById("download");
    a.href = 'data:image/svg+xml;base64,' + window.btoa(canvas.toSVG());
    a.click();
  }

  drawLine(100,100,200,100);
  drawLine(300,100,400,100);

})();

<|endoftext|>


<commit_before>function GetFile(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onload = () => {
        if (xhr.readyState === xhr.DONE) {
            if (xhr.status === 200) {
                callback(xhr.responseText);
            }
        }
    };

    xhr.send(null);
}

var onLoadCount = 0;
var totalOnLoad = 0;
function LoadScript(scriptUrl, callback) {
    totalOnLoad++;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.onload = () => {
        onLoadCount++;
        if(onLoadCount >= totalOnLoad)
            callback();
    };
    script.src = scriptUrl;
    document.body.appendChild(script);
}

function LoadCSS(cssUrl) {
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = cssUrl;
    document.body.appendChild(css);
}

function AddDependencies(scriptFolder, callback) {
    LoadScript("https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js", callback);
    LoadScript("https://unpkg.com/j-templates/jTemplates.js", callback);
    LoadScript(scriptFolder + "codemirror.js", callback);
    LoadScript(scriptFolder + "javascript.js", callback);
    LoadCSS(scriptFolder + "codemirror.css");
}

function ExecuteTs(code) {
    var js = ts.transpile(code, { target: "es6" });
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.innerHTML = js;
    document.body.appendChild(script);
}

var changeTimeout = null;
function CreateCodeMirror(container, initValue) {
    var cm = CodeMirror(container, { value: initValue });
    cm.on("change", () => {
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(() => {
            ExecuteTs(cm.getDoc().getValue());
        }, 4000);
    });
}

function CreateSample(sample) {
    var curScriptUrl = document.querySelector("[src$='docHelpers.js'").src;
    var curScriptFolder = curScriptUrl.replace(/docHelpers\.js$/, "");
    AddDependencies(curScriptFolder, () => {
        var samplesFolder = curScriptFolder + "../samples/";
        var sampleUrl = samplesFolder + sample + ".ts";

        GetFile(sampleUrl, (text) => {
            var container = document.getElementById(sample);
            container.innerHTML = "";
            CreateCodeMirror(container, text);
            ExecuteTs(text);
        });
    });
}
<commit_msg>switched to iframe<commit_after>function GetFile(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onload = () => {
        if (xhr.readyState === xhr.DONE) {
            if (xhr.status === 200) {
                callback(xhr.responseText);
            }
        }
    };

    xhr.send(null);
}

var onLoadCount = 0;
var totalOnLoad = 0;
function LoadScript(scriptUrl, callback) {
    totalOnLoad++;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.onload = () => {
        onLoadCount++;
        if(onLoadCount >= totalOnLoad)
            callback();
    };
    script.src = scriptUrl;
    document.body.appendChild(script);
}

function LoadCSS(cssUrl) {
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = cssUrl;
    document.body.appendChild(css);
}

function AddDependencies(scriptFolder, callback) {
    LoadScript("https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js", callback);
    LoadScript("https://unpkg.com/j-templates/jTemplates.js", callback);
    LoadScript(scriptFolder + "codemirror.js", callback);
    LoadScript(scriptFolder + "javascript.js", callback);
    LoadCSS(scriptFolder + "codemirror.css");
}

function ExecuteTs(container, code) {
    var iframe = container.querySelector("iframe");
    if(iframe)
        container.removeChild(iframe);

    iframe = document.createElement("iframe");
    iframe.srcDoc = '<!DOCTYPE html>';
    container.appendChild(iframe);
    var js = ts.transpile(code, { target: "es6" });
    var script = iframe.contentDocument.createElement("script");
    script.type = "text/javascript";
    script.innerHTML = js;
    iframe.contentDocument.head.appendChild(script);
}

var changeTimeout = null;
function CreateCodeMirror(container, initValue) {
    var cm = CodeMirror(container, { value: initValue });
    cm.on("change", () => {
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(() => {
            ExecuteTs(container, cm.getDoc().getValue());
        }, 4000);
    });
}

function CreateSample(sample) {
    var curScriptUrl = document.querySelector("[src$='docHelpers.js'").src;
    var curScriptFolder = curScriptUrl.replace(/docHelpers\.js$/, "");
    AddDependencies(curScriptFolder, () => {
        var samplesFolder = curScriptFolder + "../samples/";
        var sampleUrl = samplesFolder + sample + ".ts";

        GetFile(sampleUrl, (text) => {
            var container = document.getElementById(sample);
            container.innerHTML = "";
            CreateCodeMirror(container, text);
            ExecuteTs(text);
        });
    });
}
<|endoftext|>


<commit_before>'use strict';

var catalogs = [
    {
        "name": "Service Recipe",
        "type": "service",
        "description": "This is a sample service catalog recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "soajs",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/heartbeat",
                        "port": "maintenance"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "NODE_ENV": "production",

                    "SOAJS_ENV": "dashboard",
                    "SOAJS_PROFILE": "/opt/soajs/FILES/profiles/profile.js",

                    "SOAJS_SRV_AUTOREGISTERHOST": "true",
                    "SOAJS_SRV_MEMORY": "",

                    "SOAJS_GC_NAME": "", //only for gc services
                    "SOAJS_GC_VERSION": "", //only for gc services

                    "SOAJS_GIT_OWNER": "",
                    "SOAJS_GIT_BRANCH": "",
                    "SOAJS_GIT_COMMIT": "",
                    "SOAJS_GIT_REPO": "",
                    "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_MONGO_NB": "",
                    "SOAJS_MONGO_PREFIX": "",
                    "SOAJS_MONGO_RSNAME": "",
                    "SOAJS_MONGO_AUTH_DB": "",
                    "SOAJS_MONGO_SSL": "",
                    "SOAJS_MONGO_IP_N": "", //replace N with number
                    "SOAJS_MONGO_PORT_N": "", //replace N with number

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Daemon Recipe",
        "type": "daemon",
        "description": "This is a sample daemon recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "soajs",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/heartbeat",
                        "port": "maintenance"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "NODE_ENV": "production",

                    "SOAJS_ENV": "dashboard",
                    "SOAJS_PROFILE": "/opt/soajs/FILES/profiles/profile.js",

                    "SOAJS_SRV_AUTOREGISTERHOST": "true",
                    "SOAJS_SRV_MEMORY": "",

                    "SOAJS_DAEMON_GRP_CONF": "",

                    "SOAJS_GIT_OWNER": "",
                    "SOAJS_GIT_BRANCH": "",
                    "SOAJS_GIT_COMMIT": "",
                    "SOAJS_GIT_REPO": "",
                    "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_MONGO_NB": "",
                    "SOAJS_MONGO_PREFIX": "",
                    "SOAJS_MONGO_RSNAME": "",
                    "SOAJS_MONGO_AUTH_DB": "",
                    "SOAJS_MONGO_SSL": "",
                    "SOAJS_MONGO_IP_N": "", //replace N with number
                    "SOAJS_MONGO_PORT_N": "", //replace N with number

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Nginx Recipe",
        "type": "nginx",
        "description": "This is a sample nginx recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "nginx",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "http"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [], //array of objects
                "ports": {
                    "http": {
                        "exposed": "",
                        "target": "80"
                    },
                    "https": {
                        "exposed": "",
                        "target": "443"
                    }
                }
            },
            "buildOptions": {
                "env": {
                    "SOAJS_ENV": "dashboard",

                    "SOAJS_GIT_DASHBOARD_BRANCH": "", //only for dashboard nginx

                    "SOAJS_NX_DOMAIN": "", //master domain, needed to generate self-signed certs
                    "SOAJS_NX_API_DOMAIN": "",
                    "SOAJS_NX_SITE_DOMAIN": "",

                    "SOAJS_NX_CONTROLLER_NB": "",
                    "SOAJS_NX_CONTROLLER_IP_N": "", //replace N with number
                    "SOAJS_NX_CONTROLLER_PORT_N": "", //replace N with number

                    "SOAJS_NX_API_HTTPS": "",
                    "SOAJS_NX_API_HTTP_REDIRECT": "",
                    "SOAJS_NX_SITE_HTTPS": "",
                    "SOAJS_NX_SITE_HTTP_REDIRECT": "",

                    "SOAJS_NX_CUSTOM_SSL": "", //only for user-provided certs
                    "SOAJS_NX_SSL_CERTS_LOCATION": "/etc/soajs/ssl/", //only for user-provided certs
                    "SOAJS_NX_SSL_SECRET": "", //only for user-provided certs

                    "SOAJS_GIT_OWNER": "",
                    "SOAJS_GIT_BRANCH": "",
                    "SOAJS_GIT_COMMIT": "",
                    "SOAJS_GIT_REPO": "",
                    "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_MONGO_NB": "",
                    "SOAJS_MONGO_PREFIX": "",
                    "SOAJS_MONGO_RSNAME": "",
                    "SOAJS_MONGO_AUTH_DB": "",
                    "SOAJS_MONGO_SSL": "",
                    "SOAJS_MONGO_IP_N": "", //replace N with number
                    "SOAJS_MONGO_PORT_N": "", //replace N with number

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Mongo Recipe",
        "type": "mongo",
        "description": "This is a sample mongo recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "",
                    "name": "mongo",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "27017"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Elasticsearch Recipe",
        "type": "es",
        "description": "This is a sample elasticsearch recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "",
                    "name": "elasticsearch",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "9200"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    }
];

module.exports = catalogs;
<commit_msg>Bug fix in nginx catalog schema<commit_after>'use strict';

var catalogs = [
    {
        "name": "Service Recipe",
        "type": "service",
        "description": "This is a sample service catalog recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "soajs",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/heartbeat",
                        "port": "maintenance"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "NODE_ENV": "production",

                    "SOAJS_ENV": "dashboard",
                    "SOAJS_PROFILE": "/opt/soajs/FILES/profiles/profile.js",

                    "SOAJS_SRV_AUTOREGISTERHOST": "true",
                    "SOAJS_SRV_MEMORY": "",

                    "SOAJS_GC_NAME": "", //only for gc services
                    "SOAJS_GC_VERSION": "", //only for gc services

                    "SOAJS_GIT_OWNER": "",
                    "SOAJS_GIT_BRANCH": "",
                    "SOAJS_GIT_COMMIT": "",
                    "SOAJS_GIT_REPO": "",
                    "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_MONGO_NB": "",
                    "SOAJS_MONGO_PREFIX": "",
                    "SOAJS_MONGO_RSNAME": "",
                    "SOAJS_MONGO_AUTH_DB": "",
                    "SOAJS_MONGO_SSL": "",
                    "SOAJS_MONGO_IP_N": "", //replace N with number
                    "SOAJS_MONGO_PORT_N": "", //replace N with number

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Daemon Recipe",
        "type": "daemon",
        "description": "This is a sample daemon recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "soajs",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/heartbeat",
                        "port": "maintenance"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "NODE_ENV": "production",

                    "SOAJS_ENV": "dashboard",
                    "SOAJS_PROFILE": "/opt/soajs/FILES/profiles/profile.js",

                    "SOAJS_SRV_AUTOREGISTERHOST": "true",
                    "SOAJS_SRV_MEMORY": "",

                    "SOAJS_DAEMON_GRP_CONF": "",

                    "SOAJS_GIT_OWNER": "",
                    "SOAJS_GIT_BRANCH": "",
                    "SOAJS_GIT_COMMIT": "",
                    "SOAJS_GIT_REPO": "",
                    "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_MONGO_NB": "",
                    "SOAJS_MONGO_PREFIX": "",
                    "SOAJS_MONGO_RSNAME": "",
                    "SOAJS_MONGO_AUTH_DB": "",
                    "SOAJS_MONGO_SSL": "",
                    "SOAJS_MONGO_IP_N": "", //replace N with number
                    "SOAJS_MONGO_PORT_N": "", //replace N with number

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Nginx Recipe",
        "type": "nginx",
        "description": "This is a sample nginx recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "soajsorg",
                    "name": "nginx",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "http"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [], //array of objects
                "ports": {
                    "http": {
                        "exposed": "",
                        "target": "80"
                    },
                    "https": {
                        "exposed": "",
                        "target": "443"
                    }
                }
            },
            "buildOptions": {
                "env": {
                    "SOAJS_ENV": "dashboard",

                    "SOAJS_GIT_DASHBOARD_BRANCH": "", //only for dashboard nginx

                    "SOAJS_NX_DOMAIN": "", //master domain, needed to generate self-signed certs
                    "SOAJS_NX_API_DOMAIN": "",
                    "SOAJS_NX_SITE_DOMAIN": "",

                    "SOAJS_NX_CONTROLLER_NB": "",
                    "SOAJS_NX_CONTROLLER_IP_N": "", //replace N with number
                    "SOAJS_NX_CONTROLLER_PORT_N": "", //replace N with number

                    "SOAJS_NX_API_HTTPS": "",
                    "SOAJS_NX_API_HTTP_REDIRECT": "",
                    "SOAJS_NX_SITE_HTTPS": "",
                    "SOAJS_NX_SITE_HTTP_REDIRECT": "",

                    "SOAJS_NX_CUSTOM_SSL": "", //only for user-provided certs
                    "SOAJS_NX_SSL_CERTS_LOCATION": "/etc/soajs/ssl/", //only for user-provided certs
                    "SOAJS_NX_SSL_SECRET": "", //only for user-provided certs

                    // "SOAJS_GIT_OWNER": "",
                    // "SOAJS_GIT_BRANCH": "",
                    // "SOAJS_GIT_COMMIT": "",
                    // "SOAJS_GIT_REPO": "",
                    // "SOAJS_GIT_TOKEN": "", //optional (only if private repo)

                    "SOAJS_DEPLOY_HA": "", //swarm || kubernetes
                    "SOAJS_HA_NAME": "", //computed field

                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Mongo Recipe",
        "type": "mongo",
        "description": "This is a sample mongo recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "",
                    "name": "mongo",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "27017"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    },
    {
        "name": "Elasticsearch Recipe",
        "type": "es",
        "description": "This is a sample elasticsearch recipe",
        "locked": true,
        "recipe": {
            "deployOptions": {
                "image": {
                    "prefix": "",
                    "name": "elasticsearch",
                    "tag": "latest",
                    "pullPolicy": "Always"
                },
                "readinessProbe": {
                    "httpGet": {
                        "path": "/",
                        "port": "9200"
                    },
                    "initialDelaySeconds": "",
                    "timeoutSeconds": "",
                    "periodSeconds": "",
                    "successThreshold": "",
                    "failureThreshold": ""
                },
                "volumes": [] //array of objects
            },
            "buildOptions": {
                "env": {
                    "SOAJS_CONFIG_REPO_PROVIDER": "", //github|bitbucket|bitbucket_enterprise
                    "SOAJS_CONFIG_REPO_OWNER": "",
                    "SOAJS_CONFIG_REPO_BRANCH": "",
                    "SOAJS_CONFIG_REPO_NAME": "",
                    "SOAJS_CONFIG_REPO_TOKEN": ""
                },
                "cmd": {
                    "pre_install": [],
                    "install": [],
                    "post_install": [],
                    "pre_deploy": [],
                    "deploy": [],
                    "post_deploy": []
                }
            }
        }
    }
];

module.exports = catalogs;
<|endoftext|>


<commit_before>exports.name = 'builtin:serve'

exports.cli = api => {
  const { command, args } = api

  command.option('-s, --serve', 'Serve assets on a local server')

  if (!args.has('s') && !args.has('serve')) return

  command
    .option('-p, --port <port>', 'Server port', { default: '4000' })
    .option('--host <host>', 'Server host', { default: '0.0.0.0' })
    .option('--proxy <url>', 'Proxy API requests')
    .option('--no-hot', 'Disable hot reloading')
    .option('-o, --open', 'Open in browser')

  command.action(async () => {
    const devServer = Object.assign({}, api.config.devServer)
    delete devServer.hotEntries

    const { https, host, port: _port, open } = devServer
    const port = await require('get-port')({ port: _port, host })

    const webpackConfig = api.createWebpackChain().toConfig()

    // No need to print URLs in test mode
    if (api.mode !== 'test') {
      webpackConfig.plugins.push({
        apply(compiler) {
          let isFirstBuild = true
          // TODO: figure out why using .tap() can't catch error
          compiler.hooks.done.tap('print-serve-urls', stats => {
            if (stats.hasErrors() || stats.hasWarnings()) return

            require('@poi/dev-utils/printServeMessage')({
              https,
              host,
              port,
              expectedPort: _port,
              open,
              isFirstBuild,
              publicUrl: api.config.output.publicUrl
            })

            isFirstBuild = false
          })
        }
      })
    }

    const compiler = api.createWebpackCompiler(webpackConfig)

    const devServerConfig = Object.assign(
      {
        noInfo: true,
        historyApiFallback: true,
        overlay: false,
        disableHostCheck: true,
        compress: true,
        // Silence WebpackDevServer's own logs since they're generally not useful.
        // It will still show compile warnings and errors with this setting.
        clientLogLevel: 'none',
        // Prevent a WS client from getting injected as we're already including
        // `webpackHotDevClient`.
        injectClient: false,
        publicPath: webpackConfig.output.publicPath,
        contentBase:
          api.config.publicFolder && api.resolveCwd(api.config.publicFolder),
        watchContentBase: true,
        stats: 'none'
      },
      devServer,
      {
        proxy:
          typeof devServer.proxy === 'string'
            ? require('@poi/dev-utils/prepareProxy')(
                devServer.proxy,
                api.resolveCwd(api.config.publicFolder),
                api.cli.options.debug
              )
            : devServer.proxy
      }
    )

    const existingBefore = devServerConfig.before
    devServerConfig.before = server => {
      api.hooks.invoke('beforeDevMiddlewares', server)

      server.use(
        require('@poi/dev-utils/launchEditorEndpoint'),
        require('launch-editor-middleware')(() =>
          console.log(
            `To specify an editor, sepcify the EDITOR env variable or ` +
              `add "editor" field to your Vue project config.\n`
          )
        )
      )
      server.use(require('@poi/dev-utils/skipServiceWorker')())
      existingBefore && existingBefore(server)
    }

    const exitingAfter = devServerConfig.after
    devServerConfig.after = server => {
      exitingAfter && exitingAfter(server)
      api.hooks.invoke('onCreateServer', server) // TODO: remove this in the future

      api.hooks.invoke('afterDevMiddlewares', server)
    }

    api.hooks.invoke('createDevServerConfig', devServerConfig)

    const WebpackDevServer = require('webpack-dev-server')
    const server = new WebpackDevServer(compiler, devServerConfig)

    api.hooks.invoke('createServer', { server, port, host })

    server.listen(port, host)
  })
}

exports.apply = api => {
  api.hook('createWebpackChain', config => {
    if (!api.cli.options.serve) return

    if (api.config.devServer.hot) {
      const hotEntries =
        api.config.devServer.hotEntries.length > 0
          ? api.config.devServer.hotEntries
          : config.entryPoints.store.keys()
      for (const entry of hotEntries) {
        if (config.entryPoints.has(entry)) {
          config.entry(entry).prepend('#webpack-hot-client')
        }
      }

      const { HotModuleReplacementPlugin } = require('webpack')
      HotModuleReplacementPlugin.__expression = `require('webpack').HotModuleReplacementPlugin`

      config.plugin('hot').use(HotModuleReplacementPlugin)
    }

    // Point sourcemap entries to original disk location (format as URL on Windows)
    // Useful for react-error-overlay
    config.output.devtoolModuleFilenameTemplate(info =>
      info.absoluteResourcePath.replace(/\\/g, '/')
    )

    // Don't show bundled files in --serve
    if (config.plugins.has('print-status')) {
      config.plugin('print-status').tap(([options]) => [
        Object.assign(options, {
          printFileStats: false
        })
      ])
    }

    // Don't copy public folder, since we serve it instead
    config.plugins.delete('copy-public-folder')
  })
}
<commit_msg>fix: With publicPath and historyApiFallback, manually set fallback index (#764)<commit_after>exports.name = 'builtin:serve'

exports.cli = api => {
  const { command, args } = api

  command.option('-s, --serve', 'Serve assets on a local server')

  if (!args.has('s') && !args.has('serve')) return

  command
    .option('-p, --port <port>', 'Server port', { default: '4000' })
    .option('--host <host>', 'Server host', { default: '0.0.0.0' })
    .option('--proxy <url>', 'Proxy API requests')
    .option('--no-hot', 'Disable hot reloading')
    .option('-o, --open', 'Open in browser')

  command.action(async () => {
    const devServer = Object.assign({}, api.config.devServer)
    delete devServer.hotEntries

    const { https, host, port: _port, open } = devServer
    const port = await require('get-port')({ port: _port, host })

    const webpackConfig = api.createWebpackChain().toConfig()

    // No need to print URLs in test mode
    if (api.mode !== 'test') {
      webpackConfig.plugins.push({
        apply(compiler) {
          let isFirstBuild = true
          // TODO: figure out why using .tap() can't catch error
          compiler.hooks.done.tap('print-serve-urls', stats => {
            if (stats.hasErrors() || stats.hasWarnings()) return

            require('@poi/dev-utils/printServeMessage')({
              https,
              host,
              port,
              expectedPort: _port,
              open,
              isFirstBuild,
              publicUrl: api.config.output.publicUrl
            })

            isFirstBuild = false
          })
        }
      })
    }

    const compiler = api.createWebpackCompiler(webpackConfig)

    const devServerConfig = Object.assign(
      {
        noInfo: true,
        historyApiFallback: true,
        overlay: false,
        disableHostCheck: true,
        compress: true,
        // Silence WebpackDevServer's own logs since they're generally not useful.
        // It will still show compile warnings and errors with this setting.
        clientLogLevel: 'none',
        // Prevent a WS client from getting injected as we're already including
        // `webpackHotDevClient`.
        injectClient: false,
        publicPath: webpackConfig.output.publicPath,
        contentBase:
          api.config.publicFolder && api.resolveCwd(api.config.publicFolder),
        watchContentBase: true,
        stats: 'none'
      },
      devServer,
      {
        proxy:
          typeof devServer.proxy === 'string'
            ? require('@poi/dev-utils/prepareProxy')(
                devServer.proxy,
                api.resolveCwd(api.config.publicFolder),
                api.cli.options.debug
              )
            : devServer.proxy
      }
    )

    if (devServerConfig.publicPath && devServerConfig.historyApiFallback) {
      devServerConfig.historyApiFallback = {
        index: `${devServerConfig.publicPath}/index.html`.replace(/\/+/, '/'),
        ...devServerConfig.historyApiFallback
      }
    }

    const existingBefore = devServerConfig.before
    devServerConfig.before = server => {
      api.hooks.invoke('beforeDevMiddlewares', server)

      server.use(
        require('@poi/dev-utils/launchEditorEndpoint'),
        require('launch-editor-middleware')(() =>
          console.log(
            `To specify an editor, sepcify the EDITOR env variable or ` +
              `add "editor" field to your Vue project config.\n`
          )
        )
      )
      server.use(require('@poi/dev-utils/skipServiceWorker')())
      existingBefore && existingBefore(server)
    }

    const exitingAfter = devServerConfig.after
    devServerConfig.after = server => {
      exitingAfter && exitingAfter(server)
      api.hooks.invoke('onCreateServer', server) // TODO: remove this in the future

      api.hooks.invoke('afterDevMiddlewares', server)
    }

    api.hooks.invoke('createDevServerConfig', devServerConfig)

    const WebpackDevServer = require('webpack-dev-server')
    const server = new WebpackDevServer(compiler, devServerConfig)

    api.hooks.invoke('createServer', { server, port, host })

    server.listen(port, host)
  })
}

exports.apply = api => {
  api.hook('createWebpackChain', config => {
    if (!api.cli.options.serve) return

    if (api.config.devServer.hot) {
      const hotEntries =
        api.config.devServer.hotEntries.length > 0
          ? api.config.devServer.hotEntries
          : config.entryPoints.store.keys()
      for (const entry of hotEntries) {
        if (config.entryPoints.has(entry)) {
          config.entry(entry).prepend('#webpack-hot-client')
        }
      }

      const { HotModuleReplacementPlugin } = require('webpack')
      HotModuleReplacementPlugin.__expression = `require('webpack').HotModuleReplacementPlugin`

      config.plugin('hot').use(HotModuleReplacementPlugin)
    }

    // Point sourcemap entries to original disk location (format as URL on Windows)
    // Useful for react-error-overlay
    config.output.devtoolModuleFilenameTemplate(info =>
      info.absoluteResourcePath.replace(/\\/g, '/')
    )

    // Don't show bundled files in --serve
    if (config.plugins.has('print-status')) {
      config.plugin('print-status').tap(([options]) => [
        Object.assign(options, {
          printFileStats: false
        })
      ])
    }

    // Don't copy public folder, since we serve it instead
    config.plugins.delete('copy-public-folder')
  })
}
<|endoftext|>


<commit_before>'use strict';

const amqp = require('amqplib/callback_api')

class Messenger {
  constructor (options) {
    this.options = options || {}
    this.assertedQueues = {}
  }

  config (options) {
    Object.assign(this.options, options)
  }

  start (callback) {
    const amqp_url = this.options.amqp || 'amqp://localhost';
    amqp.connect(amqp_url, (err, conn) => {
      this.AssertNoError(err);

      conn.createChannel( (err, channel) => {
        this.AssertNoError(err);
        this.channel = channel;
        callback(this)
      });
    });
  }

  AssertNoError (err) {
    if (err){
      console.error(err);
      process.exit(1);
    }
  }

  ack (msg) {
    this.channel.ack(msg);
  }

  consume (queue, callback) {
    this.assertQueue(queue);
    this.channel.consume(queue, (msg) => {
      msg.content = JSON.parse(msg.content)
      callback(msg.content);
      this.ack(msg);
    })
  }

  publish (queue, json) {
    this.assertQueue(queue);

    const message = new Buffer(JSON.stringify(json));

    this.channel.sendToQueue(
      queue,
      message,
      {persistent: true}
    );

    console.log(`Published message to ${queue}: `, json.payload);
  }

  assertQueue (queue) {
    if (queue in this.assertedQueues)
      return

    this.channel.assertQueue(queue, {durable: true});
    this.assertedQueues[queue] = true;
  }
}

module.exports = Messenger<commit_msg>add broadcast method<commit_after>'use strict';

const amqp = require('amqplib/callback_api')

class Messenger {
  constructor (options) {
    this.options = options || {}
    this.assertedQueues = {}
  }

  config (options) {
    Object.assign(this.options, options)
  }

  start (callback) {
    const amqp_url = this.options.amqp || 'amqp://localhost';
    amqp.connect(amqp_url, (err, conn) => {
      this.AssertNoError(err);

      conn.createChannel( (err, channel) => {
        this.AssertNoError(err);
        this.channel = channel;
        this.channel.assertExchange(
          exchange=this.options.changeExchange,
          'topic',
          {durable: false}
        )

        callback(this)
      });
    });
  }

  AssertNoError (err) {
    if (err){
      console.error(err);
      process.exit(1);
    }
  }

  ack (msg) {
    this.channel.ack(msg);
  }

  consume (queue, callback) {
    this.assertQueue(queue);
    this.channel.consume(queue, (msg) => {
      msg.content = JSON.parse(msg.content)
      callback(msg.content);
      this.ack(msg);
    })
  }

  broadcast (topic, json) {
    body = new Buffer(JSON.stringify(json));
    this.channel.publish(this.options.changeExchange, key, body)
  }

  publish (queue, json) {
    this.assertQueue(queue);

    const message = new Buffer(JSON.stringify(json));

    this.channel.sendToQueue(
      queue,
      message,
      {persistent: true}
    );

    console.log(`Published message to ${queue}: `, json.payload);
  }

  assertQueue (queue) {
    if (queue in this.assertedQueues)
      return

    this.channel.assertQueue(queue, {durable: true});
    this.assertedQueues[queue] = true;
  }
}

module.exports = Messenger<|endoftext|>


<commit_before>// Copyright 2015 Senorsen <sen@senorsen.com>
//

var logger = require('./setlogger.js');
var dns = require('native-dns');
var util = require('util');
var express = require('express');
var config = require('./config.json');

var app = express();
app.set('trust proxy', 'loopback, 127.0.0.1');
app.get('/', function(req, res) {
    var name = req.query.name;
    var ip = req.ip;
    logger.log('info', 'client ' + ip + ' query: ' + name);
    if (typeof name == 'undefined') {
        return res.json({
            err: 2,
            msg: 'parameter error'
        });
    }
    var question = dns.Question({
        name: name,
        type: 'A'
    });
    var dnsreq = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'tcp' },
        timeout: 1000
    });
    dnsreq.on('timeout', function () {
        logger.log('warn', 'name: ' + name + ' lookup timeout');
        res.json({
            err: 1,
            msg: 'timeout'
        });
    });
    dnsreq.on('message', function (err, answer) {
        logger.log('info', 'name: ' + name + ', query reached.');
        res.json({
            err: err,
            msg: err ? 'error' : 'success',
            obj: answer.answer
        });
    });
});

app.listen(config.vps_port);
logger.log('info', 'http server listen at ' + config.vps_port);

<commit_msg>Forget to fix<commit_after>// Copyright 2015 Senorsen <sen@senorsen.com>
//

var logger = require('./setlogger.js');
var dns = require('native-dns');
var util = require('util');
var express = require('express');
var config = require('./config.json');

var app = express();
app.set('trust proxy', 'loopback, 127.0.0.1');
app.get('/', function(req, res) {
    var name = req.query.name;
    var ip = req.ip;
    logger.log('info', 'client ' + ip + ' query: ' + name);
    if (typeof name == 'undefined') {
        return res.json({
            err: 2,
            msg: 'parameter error'
        });
    }
    var question = dns.Question({
        name: name,
        type: 'A'
    });
    var dnsreq = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'tcp' },
        timeout: 1000
    });
    dnsreq.on('timeout', function () {
        logger.log('warn', 'name: ' + name + ' lookup timeout');
        res.json({
            err: 1,
            msg: 'timeout'
        });
    });
    dnsreq.on('message', function (err, answer) {
        logger.log('info', 'name: ' + name + ', query reached.');
        res.json({
            err: err,
            msg: err ? 'error' : 'success',
            obj: answer.answer
        });
    });
    dnsreq.send();
});

app.listen(config.vps_port);
logger.log('info', 'http server listen at ' + config.vps_port);

<|endoftext|>


<commit_before>/* Module: Random -- Adds a command, "random", which outputs a random number. */

var Module = require('./Module.js');
var random = require('meteor-random');

class ModRandom extends Module {

    get requiredModules() { return [
        'Commands'
    ]; }

    constructor(name) {
        super('Random', name);
    }

    initialize(envs, mods, moduleRequest) {
        if (!super.initialize(envs, mods, moduleRequest)) return false;

        //Register callbacks

        this.mod('Commands').registerCommand(this, 'random', {
            description: "Generates a random number using a cryptographically secure source of randomness.",
            args: ["max", "pub"],
            details: [
                "If MAX is not passed, a floating point number between 0 and 1 is returned.",
                "If MAX is a positive integer, an integer between 0 and MAX is returned.",
                "Pass PUB as 1 to display the resulting random number in public even if you used the command in private."
            ],
            minArgs: 0
        }, (env, type, userid, channelid, command, args, handle, ep) => {

            var val;

            if (args.max) {
                if (args.max.match(/^[0-9]+$/)) {
                    val = Math.floor(random.fraction() * args.max);
                } else {
                    ep.reply("Invalid argument.");
                    return false;
                }
            } else {
                val = random.fraction();
            }

            if (args.pub) {
                ep.pub(env.idToDisplayName(userid) + ': ' + val);
            } else {
                ep.reply(env.idToDisplayName(userid) + ': ' + val);
            }

            return true;
        });

        this.mod('Commands').registerCommand(this, 'roll', {
            description: "Generates a dice roll using a cryptographically secure source of randomness.",
            args: ["expr", true],
            details: [
                "EXPR is an expression containing sums and subtractions between dice (in the format AdB where A and B are integers) and constants."
            ],
            minArgs: 1
        }, (env, type, userid, channelid, command, args, handle, ep) => {

            var expr = args.expr.join(" ").replace(/(\+ *-|- *\+)/g, '-').replace(/([0-9])([+-])/g, '$1 $2').replace(/([+-])([0-9])/g, '$1 $2').replace(/ +/g, " ").split(" ");
            for (let i = 1; i < expr.length; i += 2) {
                if (expr[i] != "-" && expr[i] != "+") {
                    ep.reply("Invalid token '" + expr[i] + "' on position " + i + ".");
                    return true;
                }
            }

            var dicepos = {};
            var resolved = expr.slice();
            for (let i = 0; i < resolved.length; i++) {
                let facets = resolved[i].match(/^([1-9][0-9]?)?d([1-9][0-9]?)$/);
                if (facets) {
                    let val = 0;
                    for (let j = 0; j < (facets[1] || 1); j++) {
                        val += Math.floor(random.fraction() * facets[2]) + 1;
                    }
                    resolved[i] = val;
                    dicepos[i] = true;
                } else if (resolved[i].match(/^[0-9]+$/)) {
                    resolved[i] = parseInt(resolved[i]);
                }
            }

            var rep = expr.join(" ");

            if (Object.keys(dicepos).length > 0) {
                rep += ' = ' + resolved.map((val, i) => {
                    if (dicepos[i]) {
                        return "__" + val + "__";
                    }
                    return val;
                }).join(" ");
            }

            if (resolved.length > 1) {
                let result = resolved[0];
                for (let i = 2; i < resolved.length; i++) {
                    if (resolved[i-1] == "+") {
                        result += resolved[i];
                    } else if (resolved[i-1] == "-") {
                        result -= resolved[i];
                    }
                }
                rep += ' = **' + result + '**';
            }

            ep.reply(env.idToDisplayName(userid) + ': ' + rep);

            return true;
        });

        return true;
    };

}

module.exports = ModRandom;

<commit_msg>Even better!<commit_after>/* Module: Random -- Adds a command, "random", which outputs a random number. */

var Module = require('./Module.js');
var random = require('meteor-random');

class ModRandom extends Module {

    get requiredModules() { return [
        'Commands'
    ]; }

    constructor(name) {
        super('Random', name);
    }

    initialize(envs, mods, moduleRequest) {
        if (!super.initialize(envs, mods, moduleRequest)) return false;

        //Register callbacks

        this.mod('Commands').registerCommand(this, 'random', {
            description: "Generates a random number using a cryptographically secure source of randomness.",
            args: ["max", "pub"],
            details: [
                "If MAX is not passed, a floating point number between 0 and 1 is returned.",
                "If MAX is a positive integer, an integer between 0 and MAX is returned.",
                "Pass PUB as 1 to display the resulting random number in public even if you used the command in private."
            ],
            minArgs: 0
        }, (env, type, userid, channelid, command, args, handle, ep) => {

            var val;

            if (args.max) {
                if (args.max.match(/^[0-9]+$/)) {
                    val = Math.floor(random.fraction() * args.max);
                } else {
                    ep.reply("Invalid argument.");
                    return false;
                }
            } else {
                val = random.fraction();
            }

            if (args.pub) {
                ep.pub(env.idToDisplayName(userid) + ': ' + val);
            } else {
                ep.reply(env.idToDisplayName(userid) + ': ' + val);
            }

            return true;
        });

        this.mod('Commands').registerCommand(this, 'roll', {
            description: "Generates a dice roll using a cryptographically secure source of randomness.",
            args: ["expr", true],
            details: [
                "EXPR is an expression containing sums and subtractions between dice (in the format AdB where A and B are integers) and constants."
            ],
            minArgs: 1
        }, (env, type, userid, channelid, command, args, handle, ep) => {

            var expr = args.expr.join(" ").replace(/(\+ *-|- *\+)/g, '-').replace(/([0-9])([+-])/g, '$1 $2').replace(/([+-])([0-9])/g, '$1 $2').replace(/ +/g, " ").split(" ");
            for (let i = 1; i < expr.length; i += 2) {
                if (expr[i] != "-" && expr[i] != "+") {
                    ep.reply("Invalid token '" + expr[i] + "' on position " + i + ".");
                    return true;
                }
            }

            var dicepos = {};
            var resolved = expr.slice();
            for (let i = 0; i < resolved.length; i++) {
                let facets = resolved[i].match(/^(#?)([1-9][0-9]?)?d([1-9][0-9]?)$/);
                if (facets) {
                    let val = 0;
                    let dice = [];
                    for (let j = 0; j < (facets[2] || 1); j++) {
                        let die = Math.floor(random.fraction() * facets[3]) + 1;
                        dice.push(die);
                        val += die;
                    }
                    resolved[i] = val;
                    dicepos[i] = (facets[1] ? dice : true);
                } else if (resolved[i].match(/^[0-9]+$/)) {
                    resolved[i] = parseInt(resolved[i]);
                }
            }

            var rep = expr.join(" ");

            if (Object.keys(dicepos).length > 0) {
                rep += '\n    = ' + resolved.map((val, i) => {
                    if (dicepos[i]) {
                        if (dicepos[i] !== true) {
                            return "__" + val + "__ [" + dicepos[i].join(" ") + "]";
                        } else {
                            return "__" + val + "__";
                        }
                    }
                    return val;
                }).join(" ");
            }

            if (resolved.length > 1) {
                let result = resolved[0];
                for (let i = 2; i < resolved.length; i++) {
                    if (resolved[i-1] == "+") {
                        result += resolved[i];
                    } else if (resolved[i-1] == "-") {
                        result -= resolved[i];
                    }
                }
                rep += '\n    = **' + result + '**';
            }

            ep.reply(env.idToDisplayName(userid) + ': ' + rep);

            return true;
        });

        return true;
    };

}

module.exports = ModRandom;

<|endoftext|>


<commit_before>'use strict';
var mongoose = require('mongoose');
var projector = require("nodetiles-core").projector;
var __ = require("lodash");

/**
 * Turn stored a stored parcel result into geoJSON
 * TODO: Can save time and memory by not creating a new object here.
 * @param  {Object} item  A single response
 * @return {Object}       A single response structured as geoJSON
 */
function resultToGeoJSON(item) {
  item.type = 'Feature';

  // Get the geo info
  if (item.geo_info.geometry !== undefined) {
    item.id = item.object_id;
    item.geometry = item.geo_info.geometry;
  }else {
    // Or if there isn't one, use the centroid.
    item.id = item._id;
    item.geometry = {};
    item.geometry.type = 'Point';
    item.geometry.coordinates = item.geo_info.centroid;
  }

  // Copy all the responses into properties.
  // Used later for filters.
  item.properties = {};
  __.extend(item.properties, item.responses);

  // Add the geometries to the properties for use in the UTF grids
  // We need to do a deep copy here, otherwise we'll get the reprojected
  // geometries later.
  item.properties = {
    geometry: __.cloneDeep(item.geo_info.geometry),
    name: item.geo_info.humanReadableName
  };

  // Clean up a bit
  delete item.geo_info.centroid;
  delete item.geo_info.geometry;
  delete item.responses;

  // Project the object
  //if (self._projection !== mapProjection){
  //  return projector.project.Feature(self._projection, mapProjection, item);
  //}
  return item;
}

var MongoSource = function(options) {
  this._projection = projector.util.cleanProjString(options.projection || 'EPSG:4326');
  // Either options.db or options.connectionString is required.
  if (options.db) {
    this._db = options.db;
  } else {
    this._connectionString = options.connectionString;
    mongoose.connect(this._connectionString);
    this._db = mongoose.connection;
  }
  this._collectionName = options.collectionName;     // required
  this._geoKey = options.key;                        // required - name of the geodata field
  this._query =   options.query;                     // required - a query to get started with
  this._select = options.select;                     // required - fields to select
  this._filter = options.filter;                     // optional - key to filter data
  this.sourceName = options.name || 'localdata';
  return this;
};

MongoSource.prototype = {
  constructor: MongoSource,

  getShapes: function(minX, minY, maxX, maxY, mapProjection, callback) {

    // First, we need to turn the coordinates into a bounds query for Mongo
    var min = [minX, minY];
    var max = [maxX, maxY];

    // project request coordinates into data coordinates
    if (mapProjection !== this._projection) {
      min = projector.project.Point(mapProjection, this._projection, min);
      max = projector.project.Point(mapProjection, this._projection, max);
    }

    var query = this._query || {};
    var parsedBbox = [[min[0], min[1]], [max[0],  max[1]]];
    query[this._geoKey] = { '$within': { '$box': parsedBbox } };

    var start;

    function handleStream(stream) {
      var features = [];

      function addFeature(doc) {
        features.push(resultToGeoJSON(doc));
      }

      stream.on('data', addFeature);

      stream.on('close', function() {
        console.log("Fetched and processed " + features.length + " responses in " + (Date.now() - start) + "ms");

        callback(null, {
          type: 'FeatureCollection',
          features: features
        });
      });
    }

    var self = this;
    function handleCursor(cursor) {
      // The same thing as above, except using toArray
      // NB -- conversion to a format that the renderer wants is broken
      cursor.toArray(function(error, results) {
        if(error) {
          console.log("Error fetching results: ", error);
        }

        if(results) {
          console.log("Fetched " + results.length + " responses in " + (Date.now() - start) + "ms");
        }

        start = Date.now();
        var len = results.length;

        // Convert the results to geojson
        for (var i = 0; i < len; i++) {
          results[i] = resultToGeoJSON(results[i]);
        }

        var fc = {
          type: 'FeatureCollection',
          features: results
        };

        if (self._projection !== mapProjection) {
          fc = projector.project.FeatureCollection(self._projection, mapProjection, fc);
        }

        console.log("Processed " + results.length + " responses in " + (Date.now() - start) + "ms");

        callback(null, fc);

      }.bind(this));
    }

      start = Date.now();

      // console.log("Query %j %j", this._query, this._select);

      // ----------------------------------------------------------
      // Get the data
      // Set to true to try streaming
      // Streaming is both broken and not optimized
      if(false) {
        var stream = this._db.collection(this._collectionName)
          .find(this._query, this._select)
          .stream();
        handleStream(stream);
      } else {
        this._db.collection(this._collectionName)
        .find(this._query, this._select, function (error, cursor) {
          if (error) {
            console.log(error);
            callback(error);
          }
          handleCursor(cursor);
        });
      }

      // Going to skip reprojecting
      // features.push(projectFeature(mapProjection, geoJSONDoc));
    //}.bind(this));
  }
};

module.exports = MongoSource;
<commit_msg>Remove unneded copy, log<commit_after>'use strict';
var mongoose = require('mongoose');
var projector = require("nodetiles-core").projector;
var __ = require("lodash");

/**
 * Turn stored a stored parcel result into geoJSON
 * TODO: Can save time and memory by not creating a new object here.
 * @param  {Object} item  A single response
 * @return {Object}       A single response structured as geoJSON
 */
function resultToGeoJSON(item) {
  item.type = 'Feature';

  // Get the geo info
  if (item.geo_info.geometry !== undefined) {
    item.id = item.object_id;
    item.geometry = item.geo_info.geometry;
  }else {
    // Or if there isn't one, use the centroid.
    item.id = item._id;
    item.geometry = {};
    item.geometry.type = 'Point';
    item.geometry.coordinates = item.geo_info.centroid;
  }

  // Fill out the properties.
  // These are used for UTF grids
  item.properties = {};

  // Copy all the responses
  __.extend(item.properties, item.responses);

  // Add the geometries to the properties for use in the UTF grids
  // We need to do a deep copy here, otherwise we'll get the reprojected
  // geometries later.
  // TODO: if we're  generating PNGs, we don't need to copy geometries.
  item.properties.geometry = __.cloneDeep(item.geo_info.geometry),
  item.properties.name = item.geo_info.humanReadableName

  // Clean up a bit
  delete item.geo_info.centroid;
  delete item.geo_info.geometry;
  delete item.responses;

  return item;
}

var MongoSource = function(options) {
  this._projection = projector.util.cleanProjString(options.projection || 'EPSG:4326');
  // Either options.db or options.connectionString is required.
  if (options.db) {
    this._db = options.db;
  } else {
    this._connectionString = options.connectionString;
    mongoose.connect(this._connectionString);
    this._db = mongoose.connection;
  }
  this._collectionName = options.collectionName;     // required
  this._geoKey = options.key;                        // required - name of the geodata field
  this._query =   options.query;                     // required - a query to get started with
  this._select = options.select;                     // required - fields to select
  this._filter = options.filter;                     // optional - key to filter data
  this.sourceName = options.name || 'localdata';
  return this;
};

MongoSource.prototype = {
  constructor: MongoSource,

  getShapes: function(minX, minY, maxX, maxY, mapProjection, callback) {

    // First, we need to turn the coordinates into a bounds query for Mongo
    var min = [minX, minY];
    var max = [maxX, maxY];

    // project request coordinates into data coordinates
    if (mapProjection !== this._projection) {
      min = projector.project.Point(mapProjection, this._projection, min);
      max = projector.project.Point(mapProjection, this._projection, max);
    }

    var query = this._query || {};
    var parsedBbox = [[min[0], min[1]], [max[0],  max[1]]];
    query[this._geoKey] = { '$within': { '$box': parsedBbox } };

    var start;

    function handleStream(stream) {
      var features = [];

      function addFeature(doc) {
        features.push(resultToGeoJSON(doc));
      }

      stream.on('data', addFeature);

      stream.on('close', function() {
        console.log("Fetched and processed " + features.length + " responses in " + (Date.now() - start) + "ms");

        callback(null, {
          type: 'FeatureCollection',
          features: features
        });
      });
    }

    var self = this;
    function handleCursor(cursor) {
      // The same thing as above, except using toArray
      // NB -- conversion to a format that the renderer wants is broken
      cursor.toArray(function(error, results) {
        if(error) {
          console.log("Error fetching results: ", error);
        }

        if(results) {
          console.log("Fetched " + results.length + " responses in " + (Date.now() - start) + "ms");
        }

        start = Date.now();
        var len = results.length;

        // Convert the results to geojson
        for (var i = 0; i < len; i++) {
          results[i] = resultToGeoJSON(results[i]);
        }

        var fc = {
          type: 'FeatureCollection',
          features: results
        };

        if (self._projection !== mapProjection) {
          fc = projector.project.FeatureCollection(self._projection, mapProjection, fc);
        }

        console.log("Processed " + results.length + " responses in " + (Date.now() - start) + "ms");

        callback(null, fc);

      }.bind(this));
    }

      start = Date.now();

      // console.log("Query %j %j", this._query, this._select);

      // ----------------------------------------------------------
      // Get the data
      // Set to true to try streaming
      // Streaming is both broken and not optimized
      if(false) {
        var stream = this._db.collection(this._collectionName)
          .find(this._query, this._select)
          .stream();
        handleStream(stream);
      } else {
        this._db.collection(this._collectionName)
        .find(this._query, this._select, function (error, cursor) {
          if (error) {
            console.log(error);
            callback(error);
          }
          handleCursor(cursor);
        });
      }

      // Going to skip reprojecting
      // features.push(projectFeature(mapProjection, geoJSONDoc));
    //}.bind(this));
  }
};

module.exports = MongoSource;
<|endoftext|>