<commit_before>/*jslint browser: true*/
/*global Tangram, gui */

map = (function () {
    'use strict';

    var map_start_location = [35.3470, 138.7379, 12.175]; // SF

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');

    if (url_hash.length == 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    // setView expects format ([lat, long], zoom)
    map.setView(map_start_location.slice(0, 3), map_start_location[2]);

    var hash = new L.Hash(map);

    /***** Render loop *****/

    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
        });
        layer.addTo(map);
    });

    return map;

}());

var canvas = document.getElementById('kcanvas');

canvas.onselectstart = function(){ return false; };
canvas.onselectend = function(){ console.log('done'); };
var x = 0;
var y = 0;
var lastX;
var lastY;
var colorHex = "ffffff";
var color = {r: 100, g: 100, b: 100};
var blurring = false;
var rotating = false;

function updateColor(val) {
    resetFX();
    valRGB = hexToRgb(val);
    color = {r: valRGB.r, g: valRGB.g, b: valRGB.b};
    document.getElementById("picker").value = val;
}
function setColor(val) {
    document.getElementById('picker').jscolor.fromString(val);
    updateColor(val);
}
function updateWidth(val) {
    resetFX();
    w = val;
    document.getElementById("width").value = val;
}
function updateAlpha(val) {
    resetFX();
    alpha = val;
    document.getElementById("alpha").value = val;
}
function updateScale(val) {
    resetFX();
    scene.styles.hillshade.shaders.uniforms.u_scale = parseFloat(1/(Math.pow(2,val)-1));
    scene.requestRedraw();
    document.getElementById("scale").value = val;
}
function updateBlur(val) {
    if (!blurring) {
        blurring = true;
    }
    if (rotating) {
        resetRotate();
    }
    stackBlurImage( 'lastCanvas', 'kcanvas', val, false );
    scene.loadTextures();
    scene.requestRedraw();
}
function updateLines(val) {
    scene.config.global.lines = val;
    scene.config.layers.earth.draw.lines.visible = val;
    scene.config.layers.water.draw.lines.visible = val;
    scene.config.layers.boundaries.draw.dots.visible = val;
    scene.rebuild();
}
function updateLabels(val) {
    scene.config.global.lines = val;
    scene.config.layers.places.countries.draw.points.visible = val;
    scene.config.layers.places.cities.draw.points.visible = val;
    scene.config.layers.places.states.draw.text.visible = val;
    scene.rebuild();
}
function updateOcean(val) {
    scene.config.global.water = val;
    scene.config.layers.water.draw.polygons.visible = val;
    scene.rebuild();
}

function updateRotate(val) {
    val *= -1;
    if (!rotating) {
        rotating = true;
    }
    if (blurring) {
        saveCanvas(false, rotate, val);
        resetBlur();
    } else {
        rotate(val);
    }
}

// rotate the canvas
function rotate(val) {
    // get the last saved canvas
    lastCanvas.src = undos[undos.length - 1];
    // transform the canvas - move so the rotate point is in the center of the image
    ctx.translate(canvas.width/2, canvas.height/2);
    // rotate
    ctx.rotate(Math.PI/180*val);
    // move back to original position
    ctx.translate(-canvas.width/2, -canvas.height/2);
    // draw the saved image on the transformed canvas
    ctx.drawImage(lastCanvas, 0, 0);
    // freeze current transform state
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    // update map
    scene.loadTextures();
    scene.requestRedraw();

}

function resetFX() {
    if (rotating || blurring) {
        saveCanvas();
    }
    if (rotating) resetRotate();
    if (blurring) resetBlur();
}

function resetRotate() {
    if (rotating) {
        saveCanvas();
        rotating = false;
        ctx.resetTransform();
        ctx.restore();
        document.getElementById('rotate').value = 0;
    }
}

// scrub levels of undo
function rewind(val) {
    resetFX();
    lastCanvas.src = undos[val];
    lastCanvas.onload = function() {
        ctx.drawImage(lastCanvas, 0, 0);
        scene.loadTextures();
    };
}

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function draw(x,y,w,r,g,b,a){
        var gradient = ctx.createRadialGradient(x, y, 0, x, y, w);
        gradient.addColorStop(0, 'rgba('+r+', '+g+', '+b+', '+a+')');
        gradient.addColorStop(1, 'rgba('+r+', '+g+', '+b+', 0)');

        ctx.beginPath();
        ctx.arc(x, y, w, 0, 2 * Math.PI);
        ctx.fillStyle = gradient;
        ctx.fill();
        ctx.closePath();
};

var ctx = canvas.getContext('2d');
var w = 10;
var radius = w/2;
var drawing = false;
var undos = []
canvas.addEventListener("mousedown", function(e){
    resetFX();
    drawing = true;
    lastX = e.offsetX;
    lastY = e.offsetY;
    draw(lastX, lastY,w,color.r,color.g,color.b, alpha);
});
canvas.addEventListener("mouseup", function(){
    drawing = false;
    scene.loadTextures();
    saveCanvas();
});

function saveCanvas(overwrite, callback) {
    // save current state to undo history
    canvas.toBlob(function(blob, overwrite) {
        lastCanvas.src = URL.createObjectURL(blob);
        if (overwrite) {
            undos[undos.length] = lastCanvas.src;
            if (typeof callback != 'undefined') callback;
            // if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
        } else {
            undos.push(lastCanvas.src);
            updateRewindSlider();
            if (typeof callback != 'undefined') {
                callback(arguments[arguments.length-1]);
            }
            // if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
        }
    });
}

function resetBlur() {
    if (blurring) {
        blurring = false;
        document.getElementById('blur').value = 0;
    }
}

function updateRewindSlider() {
    if (undos.length > 1) {
        document.getElementById('rewind').disabled = false;
        percentWidth = (100 / Math.max(undos.length - 1, 1)) * .875;
        rule = "#rewindwrapper { background-position: left; background-image: url('line.png'); background-size: "+percentWidth + "% 100%; background-position: top 0px left 10px; }";
        document.styleSheets[3].deleteRule(0);
        document.styleSheets[3].insertRule(rule, 0);

        document.getElementById('rewind').max = undos.length - 1;
        document.getElementById('rewind').value = undos.length - 1;
    }
}

// based on http://stackoverflow.com/a/17359298/738675
canvas.addEventListener("mousemove", function(e){
    if(drawing == true){
        x = e.offsetX;
        y = e.offsetY;
        // the distance the mouse has moved since last mousemove event
        var dis = Math.sqrt(Math.pow(lastX-x, 2)+Math.pow(lastY-y, 2));

        // for each pixel distance, draw a circle on the line connecting the two points
        // to get a continous line.
        for (i=0;i<dis;i+=1) {
            var s = i/dis;
            draw(lastX*s + x*(1-s), lastY*s + y*(1-s),w,color.r,color.g,color.b, alpha);
        }
        lastX = x;
        lastY = y;
        scene.loadTextures();
    };
});

updateColor(document.getElementById("picker").value);
updateWidth(document.getElementById("width").value);
updateAlpha(document.getElementById("alpha").value);
// fill canvas with white
ctx.beginPath();
ctx.rect(0, 0, 512, 512);
ctx.fillStyle = "white";
ctx.fill();

// undo
// var lastCanvas = new Image;
// lastCanvas.id = "lastCanvas";
lastCanvas = document.getElementById("lastCanvas");
var prevCanvas = new Image;
prevCanvas.id = "prevCanvas";
var rewindSlider = document.getElementById("rewind");

function KeyPress(e) {
    var evtobj = window.event? event : e;
    // if ctrl-z
    if (evtobj.which == 90 && evtobj.ctrlKey && !evtobj.shiftKey ||
        evtobj.which == 90 && evtobj.metaKey && !evtobj.shiftKey ) {
        rewindSlider.value -= 1;
        rewind(rewindSlider.value);
    // if ctrl-shift-z
    } else if (evtobj.which == 90 && evtobj.ctrlKey && evtobj.shiftKey ||
        evtobj.which == 90 && evtobj.metaKey && evtobj.shiftKey ) {
        rewindSlider.value = parseInt(rewindSlider.value) + 1;
        rewind(rewindSlider.value);
    // if esc
    } else if (evtobj.which == 27) {
        hidePicker();
    }
}

// fill canvas with white
function clearCanvas() {
    ctx.beginPath();
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "white";
    ctx.fill();
 }

 function loadCanvas(dataurl) {
    blurring = false;
    rotating = false;
    clearCanvas();
    var img = new Image;
    img.onload = function(){
      ctx.drawImage(img,0,0,canvas.width,canvas.height);
      updateMap();
      saveCanvas();
    };
    img.src = dataurl;
 }

function updateMap(){
    scene.loadTextures();
}

document.onkeydown = KeyPress;
var myDropzone;

function testDropzone(file) {
}

Dropzone.options.canvaswrapper = {
    paramName: "file", // The name that will be used to transfer the file
    maxFilesize: 5, // MB
    accept: function(file, done) {
        testDropzone(file); // prevents upload attempt
    },
    thumbnail: function(file, dataUrl) {
        // use Dropzone's thumbnail as the canvas image
        loadCanvas(dataUrl);
    },
    thumbnailWidth: 512,
    thumbnailHeight: 512,
    previewTemplate: document.getElementById('preview-template').innerHTML
};

window.onload = function() {
        // subscribe to Tangram's published view_complete event
    scene.subscribe({
        // trigger promise resolution
        view_complete: function () {
                // viewCompleteResolve();
            },
        warning: function(e) {
            }
    });
    // load dropzone
    myDropzone = new Dropzone("div#canvaswrapper", { url: "#"});
    // fill canvas with white
    clearCanvas();
    // init first undo
    saveCanvas();
}

function exportCanvas() {
    saveCanvas();
    window.open(
      lastCanvas.src,
      '_blank' // <- This is what makes it open in a new window.
    );
}
<commit_msg>don't use resetTransform()<commit_after>/*jslint browser: true*/
/*global Tangram, gui */

map = (function () {
    'use strict';

    var map_start_location = [35.3470, 138.7379, 12.175]; // SF

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');

    if (url_hash.length == 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    // setView expects format ([lat, long], zoom)
    map.setView(map_start_location.slice(0, 3), map_start_location[2]);

    var hash = new L.Hash(map);

    /***** Render loop *****/

    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
        });
        layer.addTo(map);
    });

    return map;

}());

var canvas = document.getElementById('kcanvas');

canvas.onselectstart = function(){ return false; };
canvas.onselectend = function(){ console.log('done'); };
var x = 0;
var y = 0;
var lastX;
var lastY;
var colorHex = "ffffff";
var color = {r: 100, g: 100, b: 100};
var blurring = false;
var rotating = false;

function updateColor(val) {
    resetFX();
    valRGB = hexToRgb(val);
    color = {r: valRGB.r, g: valRGB.g, b: valRGB.b};
    document.getElementById("picker").value = val;
}
function setColor(val) {
    document.getElementById('picker').jscolor.fromString(val);
    updateColor(val);
}
function updateWidth(val) {
    resetFX();
    w = val;
    document.getElementById("width").value = val;
}
function updateAlpha(val) {
    resetFX();
    alpha = val;
    document.getElementById("alpha").value = val;
}
function updateScale(val) {
    resetFX();
    scene.styles.hillshade.shaders.uniforms.u_scale = parseFloat(1/(Math.pow(2,val)-1));
    scene.requestRedraw();
    document.getElementById("scale").value = val;
}
function updateBlur(val) {
    if (!blurring) {
        blurring = true;
    }
    if (rotating) {
        resetRotate();
    }
    stackBlurImage( 'lastCanvas', 'kcanvas', val, false );
    scene.loadTextures();
    scene.requestRedraw();
}
function updateLines(val) {
    scene.config.global.lines = val;
    scene.config.layers.earth.draw.lines.visible = val;
    scene.config.layers.water.draw.lines.visible = val;
    scene.config.layers.boundaries.draw.dots.visible = val;
    scene.rebuild();
}
function updateLabels(val) {
    scene.config.global.lines = val;
    scene.config.layers.places.countries.draw.points.visible = val;
    scene.config.layers.places.cities.draw.points.visible = val;
    scene.config.layers.places.states.draw.text.visible = val;
    scene.rebuild();
}
function updateOcean(val) {
    scene.config.global.water = val;
    scene.config.layers.water.draw.polygons.visible = val;
    scene.rebuild();
}

function updateRotate(val) {
    val *= -1;
    if (!rotating) {
        rotating = true;
    }
    if (blurring) {
        saveCanvas(false, rotate, val);
        resetBlur();
    } else {
        rotate(val);
    }
}

// rotate the canvas
function rotate(val) {
    // get the last saved canvas
    lastCanvas.src = undos[undos.length - 1];
    // transform the canvas - move so the rotate point is in the center of the image
    ctx.translate(canvas.width/2, canvas.height/2);
    // rotate
    ctx.rotate(Math.PI/180*val);
    // move back to original position
    ctx.translate(-canvas.width/2, -canvas.height/2);
    // draw the saved image on the transformed canvas
    ctx.drawImage(lastCanvas, 0, 0);
    // freeze current transform state
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    // update map
    scene.loadTextures();
    scene.requestRedraw();

}

function resetFX() {
    if (rotating || blurring) {
        saveCanvas();
    }
    if (rotating) resetRotate();
    if (blurring) resetBlur();
}

function resetRotate() {
    if (rotating) {
        saveCanvas();
        rotating = false;
        ctx.restore();
        document.getElementById('rotate').value = 0;
    }
}

// scrub levels of undo
function rewind(val) {
    resetFX();
    lastCanvas.src = undos[val];
    lastCanvas.onload = function() {
        ctx.drawImage(lastCanvas, 0, 0);
        scene.loadTextures();
    };
}

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function draw(x,y,w,r,g,b,a){
        var gradient = ctx.createRadialGradient(x, y, 0, x, y, w);
        gradient.addColorStop(0, 'rgba('+r+', '+g+', '+b+', '+a+')');
        gradient.addColorStop(1, 'rgba('+r+', '+g+', '+b+', 0)');

        ctx.beginPath();
        ctx.arc(x, y, w, 0, 2 * Math.PI);
        ctx.fillStyle = gradient;
        ctx.fill();
        ctx.closePath();
};

var ctx = canvas.getContext('2d');
var w = 10;
var radius = w/2;
var drawing = false;
var undos = []
canvas.addEventListener("mousedown", function(e){
    resetFX();
    drawing = true;
    lastX = e.offsetX;
    lastY = e.offsetY;
    draw(lastX, lastY,w,color.r,color.g,color.b, alpha);
});
canvas.addEventListener("mouseup", function(){
    drawing = false;
    scene.loadTextures();
    saveCanvas();
});

function saveCanvas(overwrite, callback) {
    // save current state to undo history
    canvas.toBlob(function(blob, overwrite) {
        lastCanvas.src = URL.createObjectURL(blob);
        if (overwrite) {
            undos[undos.length] = lastCanvas.src;
            if (typeof callback != 'undefined') callback;
            // if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
        } else {
            undos.push(lastCanvas.src);
            updateRewindSlider();
            if (typeof callback != 'undefined') {
                callback(arguments[arguments.length-1]);
            }
            // if (typeof callback != 'undefined') callback(arguments[arguments.length -1]);
        }
    });
}

function resetBlur() {
    if (blurring) {
        blurring = false;
        document.getElementById('blur').value = 0;
    }
}

function updateRewindSlider() {
    if (undos.length > 1) {
        document.getElementById('rewind').disabled = false;
        percentWidth = (100 / Math.max(undos.length - 1, 1)) * .875;
        rule = "#rewindwrapper { background-position: left; background-image: url('line.png'); background-size: "+percentWidth + "% 100%; background-position: top 0px left 10px; }";
        document.styleSheets[3].deleteRule(0);
        document.styleSheets[3].insertRule(rule, 0);

        document.getElementById('rewind').max = undos.length - 1;
        document.getElementById('rewind').value = undos.length - 1;
    }
}

// based on http://stackoverflow.com/a/17359298/738675
canvas.addEventListener("mousemove", function(e){
    if(drawing == true){
        x = e.offsetX;
        y = e.offsetY;
        // the distance the mouse has moved since last mousemove event
        var dis = Math.sqrt(Math.pow(lastX-x, 2)+Math.pow(lastY-y, 2));

        // for each pixel distance, draw a circle on the line connecting the two points
        // to get a continous line.
        for (i=0;i<dis;i+=1) {
            var s = i/dis;
            draw(lastX*s + x*(1-s), lastY*s + y*(1-s),w,color.r,color.g,color.b, alpha);
        }
        lastX = x;
        lastY = y;
        scene.loadTextures();
    };
});

updateColor(document.getElementById("picker").value);
updateWidth(document.getElementById("width").value);
updateAlpha(document.getElementById("alpha").value);
// fill canvas with white
ctx.beginPath();
ctx.rect(0, 0, 512, 512);
ctx.fillStyle = "white";
ctx.fill();

// undo
// var lastCanvas = new Image;
// lastCanvas.id = "lastCanvas";
lastCanvas = document.getElementById("lastCanvas");
var prevCanvas = new Image;
prevCanvas.id = "prevCanvas";
var rewindSlider = document.getElementById("rewind");

function KeyPress(e) {
    var evtobj = window.event? event : e;
    // if ctrl-z
    if (evtobj.which == 90 && evtobj.ctrlKey && !evtobj.shiftKey ||
        evtobj.which == 90 && evtobj.metaKey && !evtobj.shiftKey ) {
        rewindSlider.value -= 1;
        rewind(rewindSlider.value);
    // if ctrl-shift-z
    } else if (evtobj.which == 90 && evtobj.ctrlKey && evtobj.shiftKey ||
        evtobj.which == 90 && evtobj.metaKey && evtobj.shiftKey ) {
        rewindSlider.value = parseInt(rewindSlider.value) + 1;
        rewind(rewindSlider.value);
    // if esc
    } else if (evtobj.which == 27) {
        hidePicker();
    }
}

// fill canvas with white
function clearCanvas() {
    ctx.beginPath();
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "white";
    ctx.fill();
 }

 function loadCanvas(dataurl) {
    blurring = false;
    rotating = false;
    clearCanvas();
    var img = new Image;
    img.onload = function(){
      ctx.drawImage(img,0,0,canvas.width,canvas.height);
      updateMap();
      saveCanvas();
    };
    img.src = dataurl;
 }

function updateMap(){
    scene.loadTextures();
}

document.onkeydown = KeyPress;
var myDropzone;

function testDropzone(file) {
}

Dropzone.options.canvaswrapper = {
    paramName: "file", // The name that will be used to transfer the file
    maxFilesize: 5, // MB
    accept: function(file, done) {
        testDropzone(file); // prevents upload attempt
    },
    thumbnail: function(file, dataUrl) {
        // use Dropzone's thumbnail as the canvas image
        loadCanvas(dataUrl);
    },
    thumbnailWidth: 512,
    thumbnailHeight: 512,
    previewTemplate: document.getElementById('preview-template').innerHTML
};

window.onload = function() {
        // subscribe to Tangram's published view_complete event
    scene.subscribe({
        // trigger promise resolution
        view_complete: function () {
                // viewCompleteResolve();
            },
        warning: function(e) {
            }
    });
    // load dropzone
    myDropzone = new Dropzone("div#canvaswrapper", { url: "#"});
    // fill canvas with white
    clearCanvas();
    // init first undo
    saveCanvas();
}

function exportCanvas() {
    saveCanvas();
    window.open(
      lastCanvas.src,
      '_blank' // <- This is what makes it open in a new window.
    );
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

process.on('uncaughtException', function(err) {
    console.error('uncaughtException: ' + (err.stack || err.message || err.toString()));
});

process.chdir(__dirname);
var config = require('./config');

var model = require('./build/default/model_' + config.modelBackend);
model.start(config.modelConfig);

var controller = require('./build/default/controller');
controller.setModel(model);

var xmpp = require('./build/default/xmpp_pubsub');
xmpp.setController(controller);
xmpp.start(config);
<commit_msg>rm main.js<commit_after><|endoftext|>


<commit_before>annyang.start()

function save_data(){
var input = document.getElementById("fname");
localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
}
annyang. addCallback('resultNoMatch', function(){speak('I dont know what you mean');  document.getElementById("#resultplace").innerHTML = "I dont know what you mean.";});
// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        window.location.href = 'https://www.youtube.com/results?search_query='+term;
    },

    google: function (term) {
        window.location.href = 'https://www.google.com/#q='+term;
    },
    d20: function () {
      var d20 = Math.floor(Math.random() * 20);
      speak(d20);
      document.getElementById("#resultplace").innerHTML = d20;
    },

    d6: function () {
      var d6 = Math.floor(Math.random() * 6);
      speak(d6);
      document.getElementById("#resultplace").innerHTML = d6;
    },
  wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
        };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
  },
  weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
      speak(theweather.temp);

  });

}
}

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },
        '(aubrey) Who made you': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        'youtube *term': actions.youtube,
        'search *term': actions.search,
        'google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
    };

    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}
<commit_msg>added new UI v2<commit_after>annyang.start()

function save_data(){
var input = document.getElementById("fname");
localStorage.setItem("fname", input.value);
}
var firstname = localStorage.getItem("fname");

function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
}
annyang. addCallback('resultNoMatch', function(){speak('I dont know what you mean');  document.getElementById("#resultplace").innerHTML = "I dont know what you mean.";});
// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        window.location.href = 'https://www.youtube.com/results?search_query='+term;
    },

    google: function (term) {
        window.location.href = 'https://www.google.com/#q='+term;
    },
    d20: function () {
      var d20 = Math.floor(Math.random() * 20);
      speak(d20);
      document.getElementById("#resultplace").innerHTML = d20;
    },

    d6: function () {
      var d6 = Math.floor(Math.random() * 6);
      speak(d6);
      document.getElementById("#resultplace").innerHTML = d6;
    },
  wolfram: function(term) {
    $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
        speak(wolfram__);
        };
    //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
    //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
    //speak(wolfram_);
  },
  weather: function (term) {
    $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
      speak(theweather.temp);

  });

}
}

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },
        '(aubrey) (Who made you)(Who created you)': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        'youtube *term': actions.youtube,
        'search *term': actions.search,
        'google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
    };

    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}
<|endoftext|>


<commit_before>"use strict";

var renderLoop;
(function($){
	$(document).ready(function (){
		console.log("main.js");
		setup();
		renderLoop = setInterval(update, 30);
		$(document).keydown(handleInput);
		$(document).keyup(handleInput);
	});
})(jQuery);

var red = d3.select("#red");
var blue = d3.select("#blue");
var field = d3.select('#field');

function setup() {
	red.x = 50.;
	red.y = Math.floor(500*Math.random())+50;
	red.rot = 90;
	red.xv = 0.0;
	red.yv = 0.0;
	red.attr("transform","translate("+red.x+","+red.y+"),rotate("+red.rot+")");

	blue.x = 800-50.;
	blue.y = Math.floor(500*Math.random())+50;
	blue.rot = -90;
	blue.xv = 0.0;
	blue.yv = 0.0;
	blue.attr("transform","translate("+blue.x+","+blue.y+"),rotate("+blue.rot+")");
}

function update() {
	checkKeys();

	if (missiles.length){
		var filteredMissiles = [];
		for (var i=0; i<missiles.length; i++) {
			var m = missiles[i];
			if (new Date() - m.time < 2250){
				m.x += m.xv;
				m.x = (m.x+800)%800;
				m.y += m.yv;
				m.y = (m.y+600)%600;
				filteredMissiles.push(m);
			}
		}
		missiles = filteredMissiles;

		var dots = d3.select("#field").selectAll('.missile').data(missiles);
		dots.attr("cx", function(d){ return d.x; })
			.attr("cy", function(d){ return d.y; });
		dots.exit().remove();
	}

	if (red.xv*red.xv + red.yv*red.yv > 400){
		red.xv = 15.*red.xv/Math.sqrt(red.xv*red.xv + red.yv*red.yv);
		red.yv = 15.*red.yv/Math.sqrt(red.xv*red.xv + red.yv*red.yv);
	}
	red.x += red.xv;
	red.x = (red.x+800)%800;
	red.y += red.yv;
	red.y = (red.y+600)%600;
	d3.select('#red').attr("transform","translate("+red.x+","+red.y+"),rotate("+red.rot+")");

	if (blue.xv*blue.xv + blue.yv*blue.yv > 400){
		blue.xv = 15.*blue.xv/Math.sqrt(blue.xv*blue.xv + blue.yv*blue.yv);
		blue.yv = 15.*blue.yv/Math.sqrt(blue.xv*blue.xv + blue.yv*blue.yv);
	}
	blue.x += blue.xv;
	blue.x = (blue.x+800)%800;
	blue.y += blue.yv;
	blue.y = (blue.y+600)%600;
	d3.select('#blue').attr("transform","translate("+blue.x+","+blue.y+"),rotate("+blue.rot+")");
}

function redMove(action) {
	switch (action){
		case "thrust":
		red.xv += 0.5*Math.cos(Math.radians(red.rot-90));
		red.yv += 0.5*Math.sin(Math.radians(red.rot-90));
		break;
		case "fire":
		fireMissile("red");
		break;
		case "turn right":
		red.rot = red.rot + 5;
		break;
		case "turn left":
		red.rot = red.rot - 5;
		break;
		case "hyperspace":
		break;
	}
}

function blueMove(action) {
	switch (action){
		case "thrust":
		blue.xv += 0.5*Math.cos(Math.radians(blue.rot-90));
		blue.yv += 0.5*Math.sin(Math.radians(blue.rot-90));
		break;
		case "fire":
		fireMissile("blue");
		break;
		case "turn right":
		blue.rot = blue.rot + 5;
		break;
		case "turn left":
		blue.rot = blue.rot - 5;
		break;
		case "hyperspace":
		break;
	}
}

var missiles = [];
// class Missile {
	// constructor(x,y,xv,yv) {
		// this.x = x;
		// this.y = y;
		// this.xv = xv;
		// this.yv = yv;
		// if (missiles.length > 0){
			// this.id = missiles[missiles.length-1].id + 1;
		// } else {
			// this.id = 1;
		// }
		// this.name = "missile"+this.id;
	// }
// }

function fireMissile(color) {
	var mx,my,mxv,myv;
	var p;

	switch (color) {
		case "red":
		p = red;
		break;
		case "blue":
		p = blue;
		break;
	}
	mx = p.x;
	my = p.y;
	mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90));
	myv = p.yv + 10*Math.sin(Math.radians(p.rot-90));

	// missiles.push(new Missile(mx,my,mxv,myv));
	missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date()});
	missiles[missiles.length-1]['id'] = missiles.length;

	d3.select("#field").selectAll(".missile")
		.data(missiles)
	  .enter().append("circle")
		.attr("cx", function(d){ return d.x; })
		.attr("cy", function(d){ return d.y; })
		.attr("r", 2)
		.style("fill","white")
		.attr("class", "missile");
}

var keystates = {};
function handleInput(event) {
	if (event.which == 27){
		clearInterval(renderLoop);
		renderLoop = false;
		return;
	} else if (event.which == 13){
		event.preventDefault();
		if (!renderLoop){ renderLoop = setInterval(update, 30); }
		return;
	}

	if (event.which == 191){ event.preventDefault(); };

	if (event.type == 'keydown'){ keystates[event.which] = true;  }
	if (event.type == 'keyup')  { keystates[event.which] = false; }
}

var keysOfInterest = [90,88,67,86,66, 78,77,188,190,191];
function checkKeys() {
	keysOfInterest.forEach(function(k){
		if (keystates[k]){
			switch (k){
				// RED
				case 90:
				redMove("turn left");
				break;
				case 88:
				redMove("turn right");
				break;
				case 67:
				redMove("hyperspace");
				break;
				case 86:
				redMove("thrust");
				break;
				case 66:
				redMove("fire");
				break;

				// BLUE
				case 78:
				blueMove("turn left");
				break;
				case 77:
				blueMove("turn right");
				break;
				case 188:
				blueMove("hyperspace");
				break;
				case 190:
				blueMove("thrust");
				break;
				case 191:
				blueMove("fire");
				break;
			}
		}
	});
}

Math.radians = function(degrees) {
	return degrees * Math.PI / 180;
};
Math.degrees = function(radians) {
	return radians * 180 / Math.PI;
};<commit_msg>Moved repeated code into callable functions<commit_after>"use strict";

var renderLoop;
(function($){
	$(document).ready(function (){
		console.log("main.js");
		setup();
		renderLoop = setInterval(update, 30);
		$(document).keydown(handleInput);
		$(document).keyup(handleInput);
	});
})(jQuery);

var red = d3.select("#red");
var blue = d3.select("#blue");
var field = d3.select('#field');
var missileTimeout = 2250;
var fieldWidth = 800;
var fieldHeight = 600;
Math.radians = function(degrees) {
	return degrees * Math.PI / 180;
};
Math.degrees = function(radians) {
	return radians * 180 / Math.PI;
};

function setup() {
	red.x = 50;
	red.y = Math.floor((fieldHeight-100)*Math.random())+50;
	red.rot = 90;
	red.xv = 0.0;
	red.yv = 0.0;
	updateGraphics("red");
	//red.attr("transform","translate("+red.x+","+red.y+"),rotate("+red.rot+")");

	blue.x = fieldWidth-50;
	blue.y = Math.floor((fieldHeight-100)*Math.random())+50;
	blue.rot = -90;
	blue.xv = 0.0;
	blue.yv = 0.0;
	updateGraphics("blue");
	//blue.attr("transform","translate("+blue.x+","+blue.y+"),rotate("+blue.rot+")");
}

function updatePosition(team){
	var teamObj = window[team];
	if (teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv > 400){
		teamObj.xv = 15.*teamObj.xv/Math.sqrt(teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv);
		teamObj.yv = 15.*teamObj.yv/Math.sqrt(teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv);
	}
	teamObj.x += teamObj.xv;
	teamObj.x = (teamObj.x+fieldWidth)%fieldWidth;
	teamObj.y += teamObj.yv;
	teamObj.y = (teamObj.y+fieldWidth)%fieldWidth;
}

function updateGraphics(team){
	var teamObj = window[team];
	d3.select(team).attr("transform","translate("+teamObj.x+","+teamObj.y+"),rotate("+teamObj.rot+")")l
}

function update() {
	checkKeys();

	if (missiles.length){
		var filteredMissiles = [];
		for (var i=0; i<missiles.length; i++) {
			var m = missiles[i];
			if (new Date() - m.time < missileTimeout){
				m.x += m.xv;
				m.x = (m.x+fieldWidth)%fieldWidth;
				m.y += m.yv;
				m.y = (m.y+600)%600;
				filteredMissiles.push(m);
			}
		}
		missiles = filteredMissiles;

		var dots = d3.select("#field").selectAll('.missile').data(missiles);
		dots.attr("cx", function(d){ return d.x; })
			.attr("cy", function(d){ return d.y; });
		dots.exit().remove();
	}

	updatePosition("red");
	updateGraphics("red");

	updatePosition("blue");
	updateGraphics("blue");
}

function teamMove(team,action) {
	var teamObj = window[team];
	switch (action){
		case "thrust":
			teamObj.xv += 0.5*Math.cos(Math.radians(teamObj));
			teamObj.yv += 0.5*Math.sin(Math.radians(teamObj.rot-90));
			break;
		case "fire":
			fireMissile(team);
			break;
		case "turn right":
			teamObj.rot = teamObj.rot + 5;
			break;
		case "turn left":
			teamObj.rot = teamObj.rot - 5;
			break;
		case "hyperspace":
			break;
	}
}

var missiles = [];
/* class Missile {
	constructor(x,y,xv,yv) {
		this.x = x;
		this.y = y;
		this.xv = xv;
		this.yv = yv;
		if (missiles.length > 0){
			this.id = missiles[missiles.length-1].id + 1;
		} else {
			this.id = 1;
		}
		this.name = "missile"+this.id;
	}
} */

function fireMissile(team) {
	var mx,my,mxv,myv;
	var p = window[team];
	mx = p.x;
	my = p.y;
	mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90));
	myv = p.yv + 10*Math.sin(Math.radians(p.rot-90));

	// missiles.push(new Missile(mx,my,mxv,myv));
	missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date()});
	missiles[missiles.length-1]['id'] = missiles.length;

	d3.select("#field").selectAll(".missile")
		.data(missiles)
	  .enter().append("circle")
		.attr("cx", function(d){ return d.x; })
		.attr("cy", function(d){ return d.y; })
		.attr("r", 2)
		.style("fill","white")
		.attr("class", "missile");
}

var keystates = {};
function handleInput(event) {
	if (event.which == 27){
		clearInterval(renderLoop);
		renderLoop = false;
		return;
	} else if (event.which == 13){
		event.preventDefault();
		if (!renderLoop){ renderLoop = setInterval(update, 30); }
		return;
	}

	if (event.which == 191){ event.preventDefault(); };

	if (event.type == 'keydown'){ keystates[event.which] = true;  }
	if (event.type == 'keyup')  { keystates[event.which] = false; }
}

var keysOfInterest = [
			90,88,67,86,66,
			78,77,188,190,191
		     ];
function checkKeys() {
	keysOfInterest.forEach(function(k){
		if (keystates[k]){
			switch (k){
				// RED
				case 90:
					teamMove("red","turn left");
					break;
				case 88:
					teamMove("red","turn right");
					break;
				case 67:
					teamMove("red","hyperspace");
					break;
				case 86:
					teamMove("red","thrust");
					break;
				case 66:
					teamMove("red","fire");
					break;

				// BLUE
				case 78:
					teamMove("blue","turn left");
					break;
				case 77:
					teamMove("blue","turn right");
					break;
				case 188:
					teamMove("blue","hyperspace");
					break;
				case 190:
					teamMove("blue","thrust");
					break;
				case 191:
					teamMove("blue","fire");
					break;
			}
		}
	});
}
<|endoftext|>


<commit_before>require('prototype.spawn')();
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepairer = require('role.repairer');
var roleWallRepairer = require('role.wallRepairer');

var cpuUsage = {};

var minimumEnergyNewCreep = 200;
var minimumNumberOfHarvesters = 5;
var minimumNumberOfUpgraders = 1;
var minimumNumberOfBuilders = 10;
var minimumNumberOfRepairers = 1;
var minimumNumberOfWallRepairers = 0;

module.exports.loop = function() {
  if (Memory.dbg === undefined) {
    Memory.dbg = true;
    console.log("Variable 'dbg' was non-existent in memory, added with default value of 'true'");
  }
  var numberOfHarvesters = 0;
  var numberOfUpgraders = 0;
  var numberOfBuilders = 0;
  var numberOfRepairers = 0;
  var numberOfWallRepairers = 0;
  var startCpu = Game.cpu.getUsed();
  for (let name in Memory.creeps) {
    if (Game.creeps[name] == undefined) {
      delete Memory.creeps[name];
    }
  }
  cpuUsage['memory'] = Game.cpu.getUsed() - startCpu;

  var startCpu = Game.cpu.getUsed();
  for (let name in Game.creeps) {
    var creep = Game.creeps[name];
    if (creep.memory.role === 'harvester') {
      numberOfHarvesters++;
      roleHarvester.run(creep);
    } else if (creep.memory.role === 'upgrader') {
      numberOfUpgraders++;
      roleUpgrader.run(creep);
    } else if (creep.memory.role === 'builder') {
      numberOfBuilders++;
      roleBuilder.run(creep);
    } else if (creep.memory.role == 'repairer') {
      numberOfRepairers++;
      roleRepairer.run(creep);
    } else if (creep.memory.role == 'wallRepairer') {
      numberOfWallRepairers++;
      roleWallRepairer.run(creep);
    }
  }
  cpuUsage['creep'] = Game.cpu.getUsed() - startCpu;
  var towers = Game.spawns.Spawn1.room.find(FIND_STRUCTURES, {
    filter: (s) => s.structureType == STRUCTURE_TOWER
  });
  for (let tower of towers) {
    var target = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    if (target != undefined) {
      tower.attack(target);
    }
  }

  var energy = Game.spawns.Spawn1.energy;
  if (energy >= minimumEnergyNewCreep) {
    var name = undefined;
    if (numberOfHarvesters < minimumNumberOfHarvesters) {
      console.log("Need new harvester");
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'harvester');
    // if (name == ERR_NOT_ENOUGH_ENERGY && numberOfHarvesters == 0) {
    //   name = Game.spawns.Spawn1.createCustomCreep(
    //     Game.spawns.Spawn1.room.energyAvailable, 'harvester');
    // }
    } else if (numberOfUpgraders < minimumNumberOfUpgraders) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'upgrader');
    } else if (numberOfBuilders < minimumNumberOfBuilders) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    } else if (numberOfRepairers < minimumNumberOfRepairers) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'repairer');
    } else if (numberOfWallRepairers < minimumNumberOfWallRepairers) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'wallRepairer');
    }
    if (name !== undefined && !name < 0) {
      console.log("Spawned new creep: " + name);
    }
  }
  (Memory.dbg) ? console.log(
    "Total: " + (Math.round(Game.cpu.getUsed() * 100) / 100) +
    "\tBucket: " + Game.cpu.bucket + "/10000" +
    "\tCreeps: " + (Math.round(cpuUsage['creep'] * 100) / 100) +
    "\tMemory: " + (Math.round(cpuUsage['memory'] * 100) / 100) +
    "") : null;
  if (Game.time % 10 === 0) {
    console.log(numberOfHarvesters + "/" + minimumNumberOfHarvesters + " Harvesters\t" +
      numberOfUpgraders + "/" + minimumNumberOfUpgraders + " Upgraders\t" +
      numberOfBuilders + "/" + minimumNumberOfBuilders + " Builders\t" +
      numberOfRepairers + "/" + minimumNumberOfRepairers + " Repairers\t" +
      numberOfWallRepairers + "/" + minimumNumberOfWallRepairers + " WallRepairers");
  }
};
<commit_msg>Moved minimal values into memory<commit_after>require('prototype.spawn')();
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepairer = require('role.repairer');
var roleWallRepairer = require('role.wallRepairer');

var cpuUsage = {};

if (Memory.minimumEnergyNewCreep === undefined) {
  Memory.minimumEnergyNewCreep = 200;
  console.log("Variable 'minimumEnergyNewCreep' was non-existent in memory, added with default value of '" + Memory.minimumEnergyNewCreep + "'");
}
if (Memory.minimumNumberOfHarvesters === undefined) {
  Memory.minimumNumberOfHarvesters = 1;
  console.log("Variable 'minimumNumberOfHarvesters' was non-existent in memory, added with default value of '" + Memory.minimumNumberOfHarvesters + "'");
}
if (Memory.minimumNumberOfUpgraders === undefined) {
  Memory.minimumNumberOfUpgraders = 1;
  console.log("Variable 'minimumNumberOfUpgraders' was non-existent in memory, added with default value of '" + Memory.minimumNumberOfUpgraders + "'");
}
if (Memory.minimumNumberOfBuilders === undefined) {
  Memory.minimumNumberOfBuilders = 1;
  console.log("Variable 'minimumNumberOfBuilders' was non-existent in memory, added with default value of '" + Memory.minimumNumberOfBuilders + "'");
}
if (Memory.minimumNumberOfRepairers === undefined) {
  Memory.minimumNumberOfRepairers = 0;
  console.log("Variable 'minimumNumberOfRepairers' was non-existent in memory, added with default value of '" + Memory.minimumNumberOfRepairers + "'");
}
if (Memory.minimumNumberOfWallRepairers === undefined) {
  Memory.minimumNumberOfWallRepairers = 0;
  console.log("Variable 'minimumNumberOfWallRepairers' was non-existent in memory, added with default value of '" + Memory.minimumNumberOfWallRepairers + "'");
}

module.exports.loop = function() {
  if (Memory.dbg === undefined) {
    Memory.dbg = true;
    console.log("Variable 'dbg' was non-existent in memory, added with default value of 'true'");
  }
  var numberOfHarvesters = 0;
  var numberOfUpgraders = 0;
  var numberOfBuilders = 0;
  var numberOfRepairers = 0;
  var numberOfWallRepairers = 0;
  var startCpu = Game.cpu.getUsed();
  for (let name in Memory.creeps) {
    if (Game.creeps[name] == undefined) {
      delete Memory.creeps[name];
    }
  }
  cpuUsage['memory'] = Game.cpu.getUsed() - startCpu;

  var startCpu = Game.cpu.getUsed();
  for (let name in Game.creeps) {
    var creep = Game.creeps[name];
    if (creep.memory.role === 'harvester') {
      numberOfHarvesters++;
      roleHarvester.run(creep);
    } else if (creep.memory.role === 'upgrader') {
      numberOfUpgraders++;
      roleUpgrader.run(creep);
    } else if (creep.memory.role === 'builder') {
      numberOfBuilders++;
      roleBuilder.run(creep);
    } else if (creep.memory.role == 'repairer') {
      numberOfRepairers++;
      roleRepairer.run(creep);
    } else if (creep.memory.role == 'wallRepairer') {
      numberOfWallRepairers++;
      roleWallRepairer.run(creep);
    }
  }
  cpuUsage['creep'] = Game.cpu.getUsed() - startCpu;
  var towers = Game.spawns.Spawn1.room.find(FIND_STRUCTURES, {
    filter: (s) => s.structureType == STRUCTURE_TOWER
  });
  for (let tower of towers) {
    var target = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
    if (target != undefined) {
      tower.attack(target);
    }
  }

  var energy = Game.spawns.Spawn1.energy;
  if (energy >= Memory.minimumEnergyNewCreep) {
    var name = undefined;
    if (numberOfHarvesters < Memory.minimumNumberOfHarvesters) {
      console.log("Need new harvester");
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'harvester');
    // if (name == ERR_NOT_ENOUGH_ENERGY && numberOfHarvesters == 0) {
    //   name = Game.spawns.Spawn1.createCustomCreep(
    //     Game.spawns.Spawn1.room.energyAvailable, 'harvester');
    // }
    } else if (numberOfUpgraders < Memory.minimumNumberOfUpgraders) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'upgrader');
    } else if (numberOfBuilders < Memory.minimumNumberOfBuilders) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    } else if (numberOfRepairers < Memory.minimumNumberOfRepairers) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'repairer');
    } else if (numberOfWallRepairers < Memory.minimumNumberOfWallRepairers) {
      name = Game.spawns.Spawn1.createCustomCreep(energy, 'wallRepairer');
    }
    if (name !== undefined && !name < 0) {
      console.log("Spawned new creep: " + name);
    }
  }
  (Memory.dbg) ? console.log(
    "Total: " + (Math.round(Game.cpu.getUsed() * 100) / 100) +
    "\tBucket: " + Game.cpu.bucket + "/10000" +
    "\tCreeps: " + (Math.round(cpuUsage['creep'] * 100) / 100) +
    "\tMemory: " + (Math.round(cpuUsage['memory'] * 100) / 100) +
    "") : null;
  if (Game.time % 10 === 0) {
    console.log(numberOfHarvesters + "/" + minimumNumberOfHarvesters + " Harvesters\t" +
      numberOfUpgraders + "/" + minimumNumberOfUpgraders + " Upgraders\t" +
      numberOfBuilders + "/" + minimumNumberOfBuilders + " Builders\t" +
      numberOfRepairers + "/" + minimumNumberOfRepairers + " Repairers\t" +
      numberOfWallRepairers + "/" + minimumNumberOfWallRepairers + " WallRepairers");
  }
};
<|endoftext|>


<commit_before>/*
Copyright (C) 2017 Nathan Nichols

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL NATHAN NICHOLS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// runs when button is clicked
free_salsa_submit = function( e ){
	console.log("\nFORM SUBMITTED\n");
	var orig_url = document.location.href;
	var possible_matches = document.getElementById("mainForm").children[0].children[0];
	var url = possible_matches.action;
	var required_fields = document.getElementsByName("required")[0].value.split(",");
	var field;
	var form_good = true;
	var form_data = {};
	for(var i = 0; i < required_fields.length; i++){
		if(document.getElementsByName(required_fields[i])[0] !== undefined){
			field = document.getElementsByName(required_fields[i])[0];
			form_data[field.name] = field.value;
			if(field.value !== ""){
				//console.log(field.value);
			}	else{
				form_good = false;
				//console.log("[blank]");
			}
		}
	}
	if(!form_good){
		window.alert("please fill out required fields.");
		return false; // will cause the form not to submit
	}else{
		var redirect;
		var http1 = new XMLHttpRequest();
		http1.open('POST', url, true);
		http1.onload = function (){
			redirect = document.body.innerHTML.substr(document.body.innerHTML.indexOf("URL")+4,document.body.innerHTML.length);
			redirect = document.location.href.substr(0,document.location.href.indexOf(".com")+4) + redirect;
      location.assign(redirect)
		};
		http1.send(form_data);
	}
	return true;
}
// set the onsubmit function of the form to add-on's own free javascript
if(typeof(document.getElementsByClassName("salsa actions")[0]) != "undefined" ){
	var possible_matches = document.getElementById("mainForm").children[0];
	possible_matches.onsubmit = free_salsa_submit;
}
<commit_msg>Refactor an if statement and add a break statement if the form_good condition is false, as all fields must be filled in. If one isn't, there is no point in continuing to check<commit_after>/*
Copyright (C) 2017 Nathan Nichols

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL NATHAN NICHOLS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

// runs when button is clicked
free_salsa_submit = function( e ){
	var orig_url = document.location.href;
	var possible_matches = document.getElementById("mainForm").children[0].children[0];
	var url = possible_matches.action;
	var required_fields = document.getElementsByName("required")[0].value.split(",");
	var field;
	var form_good = true;
	var form_data = {};
	for(var i = 0; i < required_fields.length; i++){
		if(document.getElementsByName(required_fields[i])[0] !== undefined){
			field = document.getElementsByName(required_fields[i])[0];
			form_data[field.name] = field.value;
			if(field.value === ""){
        form_good = false;
        break;
      }
		}
	}
	if(!form_good){
		window.alert("please fill out required fields.");
		return false; // will cause the form not to submit
	}else{
		var redirect;
		var http1 = new XMLHttpRequest();
		http1.open('POST', url, true);
		http1.onload = function (){
			redirect = document.body.innerHTML.substr(document.body.innerHTML.indexOf("URL")+4,document.body.innerHTML.length);
			redirect = document.location.href.substr(0,document.location.href.indexOf(".com")+4) + redirect;
      location.assign(redirect)
		};
		http1.send(form_data);
	}
	return true;
}
// set the onsubmit function of the form to add-on's own free javascript
if(typeof(document.getElementsByClassName("salsa actions")[0]) != "undefined" ){
	var possible_matches = document.getElementById("mainForm").children[0];
	possible_matches.onsubmit = free_salsa_submit;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require("fs"),
    rss = require("rss"),
    mustache = require("mustache"),
    chalk = require("chalk"),
    ncp = require("ncp"),
    prompt = require("prompt"),
    dateFormat = require("dateformat"),
    markdown = require("markdown").markdown.toHTML,
    optp = require("nomnom").script("shock");

var success = chalk.green,
    failure = chalk.red;

function isMarkdown(name) {
    return name.split(".")[name.split(".").length-1] === "md";
}
function ensureHTML(name) {
    return isMarkdown(name) ? name.replace(/\.md$/, ".html") : name;
}

prompt.message = "(shock)";

optp.command("init")
    .callback(function() {
        prompt.start();
        prompt.get(['title', 'author', 'description', 'url'], function(err, x) {
            if (err) {
                console.log(failure("Aborted."));
                process.exit();
            }
            ncp(__dirname+"/init", ".", function(err) {
                if (err) {
                    console.log(failure("Failed to create directory structure. Hmph."));
                    process.exit();
                }
                fs.readFile("index.json", function(err, data) {
                    var index = JSON.parse(data);
                    index.title = x.title;
                    index.author = x.author;
                    index.description = x.description;
                    index.url = x.url;
                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Minimal shock site initialized."));
                    });
                });
            });
        });
    });

optp.command("compile")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                throw err;
            }
            var index;
            try {
                index = JSON.parse(data);
            } catch(e) {
                console.log(failure("index.json failed to parse (it has to be honest json, not a js object literal!)"));
                process.exit();
            }

            var header = fs.readFileSync("templates/" + index.templates.header).toString();
            var footer = fs.readFileSync("templates/" + index.templates.footer).toString();
            var postpage = fs.readFileSync("templates/" + index.templates.postpage).toString();
            var home = fs.readFileSync("templates/" + index.templates.home).toString();
            var notfound = fs.readFileSync("templates/" + index.templates["404"]).toString();

            // Create RSS feed
            var feed = new rss({
                title: index.title,
                description: index.description,
                site_url: index.url,
                author: index.author,
                language: index.lang || "en",
            });

            var items = index.posts.sort(function(a, b) {
                return new Date(b.date).getTime() - new Date(a.date).getTime();
            });
            items.forEach(function(item) {
                feed.item({
                    title: item.title,
                    description: item.description,
                    url: index.url + "/" + item.file,
                    date: item.date,
                    author: item.author || index.author
                });
                var content = fs.readFileSync("content/" + item.file).toString();
                var view = {
                    title: item.title,
                    description: item.description,
                    date: dateFormat(new Date(item.date), "fullDate"),
                    author: item.author,
                    header: header,
                    footer: footer,
                    content: item.markdown ? markdown(content) : content
                }
                fs.writeFile(ensureHTML(item.file), mustache.render(postpage, view), function() {
                    console.log(success("Created " + item.file));
                });

            });

            fs.writeFile("feed.xml", feed.xml("    "), function() {
                console.log(success("Created RSS feed."));
            });
            fs.writeFile("404.html", mustache.render(notfound, {
                header: header,
                footer: footer,
            }), function() {
                console.log(success("Created 404.html"));
            });

            fs.writeFile("index.html", mustache.render(home, {
                header: header,
                footer: footer,
                posts: items.map(function(i) {
                    i.file = ensureHTML(i.file);
                    i.date = dateFormat(new Date(i.date), "shortDate");
                    return i;
                })
            }), function() {
                console.log(success("Created homepage."));
            });
        });
    });

optp.command("newpost")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);
            prompt.start();
            prompt.get(
                ['title', 'author', 'description', 'file', 'date'],
                function(err, data) {
                    if (err) {
                        console.log(failure("Aborted."));
                        process.exit();
                    }
                    if (isMarkdown(data.file)) {
                        data.markdown = true;
                    }
                    data.author = data.author || index.author;
                    data.date = data.date || dateFormat(Date.now(), "shortDate");
                    index.posts.push(data);

                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Post created."));
                    });
                });
        })
    });

var opts = optp.parse();
<commit_msg>deletion<commit_after>#!/usr/bin/env node

var fs = require("fs"),
    rss = require("rss"),
    mustache = require("mustache"),
    chalk = require("chalk"),
    ncp = require("ncp"),
    prompt = require("prompt"),
    dateFormat = require("dateformat"),
    markdown = require("markdown").markdown.toHTML,
    optp = require("nomnom").script("shock");

var success = chalk.green,
    failure = chalk.red;

function isMarkdown(name) {
    return name.split(".")[name.split(".").length-1] === "md";
}
function ensureHTML(name) {
    return isMarkdown(name) ? name.replace(/\.md$/, ".html") : name;
}

prompt.message = "(shock)";

optp.command("init")
    .callback(function() {
        prompt.start();
        prompt.get(['title', 'author', 'description', 'url'], function(err, x) {
            if (err) {
                console.log(failure("Aborted."));
                process.exit();
            }
            ncp(__dirname+"/init", ".", function(err) {
                if (err) {
                    console.log(failure("Failed to create directory structure. Hmph."));
                    process.exit();
                }
                fs.readFile("index.json", function(err, data) {
                    var index = JSON.parse(data);
                    index.title = x.title;
                    index.author = x.author;
                    index.description = x.description;
                    index.url = x.url;
                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Minimal shock site initialized."));
                    });
                });
            });
        });
    });

optp.command("compile")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                throw err;
            }
            var index;
            try {
                index = JSON.parse(data);
            } catch(e) {
                console.log(failure("index.json failed to parse (it has to be honest json, not a js object literal!)"));
                process.exit();
            }

            var header = fs.readFileSync("templates/" + index.templates.header).toString();
            var footer = fs.readFileSync("templates/" + index.templates.footer).toString();
            var postpage = fs.readFileSync("templates/" + index.templates.postpage).toString();
            var home = fs.readFileSync("templates/" + index.templates.home).toString();
            var notfound = fs.readFileSync("templates/" + index.templates["404"]).toString();

            // Create RSS feed
            var feed = new rss({
                title: index.title,
                description: index.description,
                site_url: index.url,
                author: index.author,
                language: index.lang || "en",
            });

            var items = index.posts.sort(function(a, b) {
                return new Date(b.date).getTime() - new Date(a.date).getTime();
            });
            items.forEach(function(item) {
                feed.item({
                    title: item.title,
                    description: item.description,
                    url: index.url + "/" + item.file,
                    date: item.date,
                    author: item.author || index.author
                });
                var content = fs.readFileSync("content/" + item.file).toString();
                var view = {
                    title: item.title,
                    description: item.description,
                    date: dateFormat(new Date(item.date), "fullDate"),
                    author: item.author,
                    header: header,
                    footer: footer,
                    content: item.markdown ? markdown(content) : content
                }
                fs.writeFile(ensureHTML(item.file), mustache.render(postpage, view), function() {
                    console.log(success("Created " + item.file));
                });

            });

            fs.writeFile("feed.xml", feed.xml("    "), function() {
                console.log(success("Created RSS feed."));
            });
            fs.writeFile("404.html", mustache.render(notfound, {
                header: header,
                footer: footer,
            }), function() {
                console.log(success("Created 404.html"));
            });

            fs.writeFile("index.html", mustache.render(home, {
                header: header,
                footer: footer,
                posts: items.map(function(i) {
                    i.file = ensureHTML(i.file);
                    i.date = dateFormat(new Date(i.date), "shortDate");
                    return i;
                })
            }), function() {
                console.log(success("Created homepage."));
            });
        });
    });

optp.command("newpost")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);
            prompt.start();
            prompt.get(
                ['title', 'author', 'description', 'file', 'date'],
                function(err, data) {
                    if (err) {
                        console.log(failure("Aborted."));
                        process.exit();
                    }
                    if (isMarkdown(data.file)) {
                        data.markdown = true;
                    }
                    data.author = data.author || index.author;
                    data.date = data.date || dateFormat(Date.now(), "shortDate");
                    index.posts.push(data);

                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Post created."));
                    });
                });
        })
    });

optp.command("rm")
    .option("name", {
        position: 1,
        required: true
    })
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);

            for (var i=0; i<index.posts.length; i++) {
                if (index.posts[i].file === opts.name) {
                    index.posts.splice(i, 1);
                    console.log(success("Deleted."));
                    break;
                }
            }
            if (i === index.posts.length) {
                console.log(failure("Nothing deleted."));
            }

            fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                console.log(success("Updated index."));
            });

        })
    });

var opts = optp.parse();
<|endoftext|>


<commit_before>const net = require('net')
const readline = require('readline')

const { app, BrowserWindow } = require('electron')
app.commandLine.appendSwitch('--disable-http-cache')

require('electron-reload')(
  `${__dirname}/renderer`,
  { electron: `${__dirname}/node_modules/.bin/electron` }
)

const Options = require('./cli/options')
const options = new Options(process.argv)

let server

app.on('ready', () => {
  if (server) return

  server = net.createServer((socket) => {
    let win = new BrowserWindow({ height: 800, width: 900 })
    const indexPath = `file://${__dirname}/renderer/index.html`
    win.loadURL(indexPath)

    win.on('closed', () => { win = null })

    win.webContents.on('did-finish-load', () => {
      const socketSession = readline.createInterface({ input: socket })

      socketSession.on('line', (line) => {
        const message = JSON.parse(line)
        if (options.debug) console.log(JSON.stringify(message, null, 2))
        win.webContents.send(message['type'], message)
      })

      socketSession.on('close', () => win.webContents.send('end'))
    })
  })

  server.listen(options.port || 0, () => {
    console.log('Cucumber GUI listening for events on port ' + server.address().port)
  })
})<commit_msg>Clean up<commit_after>const net = require('net')
const readline = require('readline')

const { app, BrowserWindow } = require('electron')
app.commandLine.appendSwitch('--disable-http-cache')

require('electron-reload')(
  `${__dirname}/renderer`,
  { electron: `${__dirname}/node_modules/.bin/electron` }
)

const Options = require('./cli/options')
const options = new Options(process.argv)

let server

app.on('ready', () => {
  server = net.createServer((socket) => {
    let win = new BrowserWindow({ height: 800, width: 900 })
    const indexPath = `file://${__dirname}/renderer/index.html`
    win.loadURL(indexPath)

    win.on('closed', () => { win = null })

    win.webContents.on('did-finish-load', () => {
      const socketSession = readline.createInterface({ input: socket })

      socketSession.on('line', (line) => {
        const message = JSON.parse(line)
        if (options.debug) console.log(JSON.stringify(message, null, 2))
        win.webContents.send(message['type'], message)
      })

      socketSession.on('close', () => win.webContents.send('end'))
    })
  })

  server.listen(options.port || 0, () => {
    console.log('Cucumber GUI listening for events on port ' + server.address().port)
  })
})<|endoftext|>


<commit_before>var app = require('app');
var BrowserWindow = require('browser-window');

var mainWindow = null;

var openFileDialog = require('./main-process/dialogs/open-file.js');
openFileDialog();

var errorDialog = require('./main-process/dialogs/error.js');
errorDialog();

var infoDialog = require('./main-process/dialogs/information.js');
infoDialog();

var saveDialog = require('./main-process/dialogs/save.js');
saveDialog();

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', () => {
  mainWindow = new BrowserWindow({ width: 800, height: 900 });

  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // mainWindow.openDevTools();

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
});
<commit_msg>Loop through main process scripts<commit_after>var app = require('app');
var BrowserWindow = require('browser-window');
var glob = require('glob');

var mainWindow = null;

// Require and setup each JS file in the main-process dir
glob('main-process/**/*.js', function (error, files) {
  files.forEach(function (file) {
    require('./' + file).setup();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', () => {
  mainWindow = new BrowserWindow({ width: 800, height: 900 });

  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // mainWindow.openDevTools();

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
});
<|endoftext|>


<commit_before>/*
  IMPORTANT: Don't use ES6 here, as some people are still on Node 4.
*/

var b = require('substance-bundler')
var path = require('path')

// Constants
// ---------

var TEST ='.test/'
var NPM = '.npm/'
var NPMDIST = NPM+'dist/'
var STUFF = [
  'package.json',
  'LICENSE.md',
  'README.md',
  'CHANGELOG.md',
  'make.js'
]

// Helpers
// -------
// Doing the actual work

// creates a browser bundle
function _browser(DIST, transpileToES5, production) {
  b.js('./index.es.js', {
    target: {
      dest: DIST+'substance.js',
      format: 'umd', moduleName: 'substance',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance',
      useStrict: !transpileToES5,
    },
    buble: transpileToES5,
    eslint: { exclude: [ 'dom/vendor.js' ] },
    cleanup: Boolean(production)
  })
  b.css('substance.css', DIST+'substance.css', { variables: true })
  b.css('substance.css', DIST+'substance.next.css')
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.css', {variables: true})
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.next.css')
  b.css('substance-reset.css', DIST+'substance-reset.css', {variables: true})
  b.css('substance-reset.css', DIST+'substance-reset.next.css')
}

// creates a server bundle
function _server(DIST, transpileToES5, production) {
  b.js('./index.es.js', {
    target: {
      dest: DIST+'substance.cjs.js',
      format: 'cjs',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    },
    buble: transpileToES5,
    eslint: { exclude: [ 'dom/vendor.js' ] },
    cleanup: Boolean(production)
  })
}

// bundles the test suite to be run in a browser
function _testBrowser(transpileToES5, coverage) {

  b.js('./test/index.js', {
    target: {
      dest: TEST+'tests.js',
      format: 'umd', moduleName: 'tests'
    },
    buble: transpileToES5,
    external: { 'substance-test': 'substanceTest' },
    istanbul: coverage ? {
      include: [
        'collab/*.js',
        'dom/*.js',
        'model/**/*.js',
        // 'packages/**/*.js',
        'ui/*.js',
        // 'util/*.js'
      ],
      exclude: [ 'dom/vendor.js' ]
    } : false
  })
}

function _testNode() {
  b.js('./test/index.js', {
    target: {
      dest: TEST+'tests.cjs.js',
      format: 'cjs'
    },
    external: ['substance-test'],
    buble: true,
    commonjs: true
  })
}

function _runTestBrowser() {
  b.custom('Running browser tests...', {
    execute: function() {
      let karma = require('karma')
      const browser = process.env.TRAVIS ? 'ChromeTravis': 'Chrome'
      return new Promise(function(resolve) {
        let fails = 0
        const server = new karma.Server({
          configFile: __dirname + '/karma.conf.js',
          browsers: [browser],
          singleRun: true,
          failOnEmptyTestSuite: false
        }, function() {
          // why is exitCode always == 1?
          if (fails > 0) {
            process.exit(1)
          } else {
            resolve()
          }
        })
        server.on('run_complete', function(browsers, results) {
          if (results && results.failed > 0) {
            fails += results.failed
          }
        })
        server.start()
      })
    }
  })
}

function _runTestNode() {
  b.custom('Running nodejs tests...', {
    execute: function() {
      let cp = require('child_process')
      return new Promise(function(resolve, reject) {
        const child = cp.fork(path.join(__dirname, '.test/run-tests.js'))
        child.on('message', function(msg) {
          if (msg === 'done') { resolve() }
        })
        child.on('error', function(error) {
          reject(new Error(error))
        })
        child.on('close', function(exitCode) {
          if (exitCode !== 0) {
            process.exit(exitCode)
          } else {
            resolve()
          }
        })
      });
    }
  })
}

// generates API documentation
function _docs(mode, dest) {
  var docgen = require('substance-docgen')
  docgen.bundle(b, {
    src: [
      './*.md',
      './doc/*.md',
      './collab/*.js',
      './dom/*.js',
      './model/**/*.js',
      './packages/**/*.js',
      './ui/*.js',
      './util/*.js',
    ],
    dest: dest,
    config: './.docgenrc.js',
    mode: mode // one of: 'source', 'json', 'site' (default: 'json')
  })
}

function _vendor_xdom() {
  b.js('./dom/_vendor.js', {
    target: {
      dest: './dom/vendor.js',
      format: 'es'
    },
    ignore: [ 'events', 'entities' ],
    alias: {
      'dom-serializer': path.join(__dirname, 'dom/_domSerializer.js'),
      'inherits': path.join(__dirname, 'dom/_stub.js')
    },
    commonjs: true,
    json: true
  })
}

// Tasks
// -----

b.task('clean', function() {
  b.rm('./dist')
  b.rm('./.test')
  b.rm('./.docs')
  b.rm('./.npm')
})

b.task('browser:pure', function() {
  _browser('./dist/', false)
})

b.task('browser', function() {
  _browser('./dist/', true)
})

b.task('server', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', true)
})

b.task('server:pure', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', false)
})

b.task('test:clean', function() {
  b.rm(TEST)
})

b.task('test:assets', function() {
  // TODO: it would be nice to treat such glob patterns
  // differently, so that we do not need to specify glob root
  b.copy('./node_modules/substance-test/dist/*', TEST, { root: './node_modules/substance-test/dist' })
})

b.task('test:browser', ['test:clean', 'test:assets'], function() {
  // buble necessary here, as travis has old browser versions
  _testBrowser(true)
})

b.task('test:browser:pure', ['test:clean', 'test:assets'], function() {
  // Pure ES6, and no buble here, for better dev experience
  _testBrowser(false)
})

b.task('test:browser:coverage', ['test:clean', 'test:assets'], function() {
  _testBrowser(true, true)
})

b.task('test:node', ['test:clean', 'test:assets'], _testNode)

b.task('run:test:browser', ['test:browser'], _runTestBrowser)

b.task('run:test:node', ['test:node'], _runTestNode)

b.task('run:test:coverage', ['test:browser:coverage'], _runTestBrowser)

b.task('npm:clean', function() {
  b.rm(NPM)
})

b.task('npm:copy:sources', function() {
  b.copy('index.es.js', NPM)
  b.copy('collab/*.js', NPM)
  b.copy('dom/**/*.js', NPM)
  b.copy('model/**/*.js', NPM)
  b.copy('packages/**/*.js', NPM)
  b.copy('ui/*.js', NPM)
  b.copy('util/*.js', NPM)
  b.copy('test/**/*.js', NPM)
  b.copy('*.css', NPM)
  b.copy('packages/**/*.css', NPM)
  STUFF.forEach(function(f) {
    b.copy(f, NPM)
  })
})

b.task('docs', function() {
  // creates a data.js file with prebuilt documentation
  // this gives the best trade-off between build and load time
  _docs('json', '.docs/')
})

b.task('npm:docs', function() {
  _docs('site', NPM+'docs/')
})

b.task('npm:browser', function() {
  _browser(NPMDIST, true, true)
})

b.task('npm:server', function() {
  _server(NPMDIST, true, true)
})

b.task('build', ['clean', 'browser', 'server'])

b.task('build:pure', ['clean', 'browser:pure', 'server:pure'])

b.task('test', ['test:clean', 'test:assets', 'run:test:browser', 'run:test:node'])

b.task('npm', ['npm:clean', 'npm:copy:sources', 'npm:docs', 'npm:browser', 'npm:server'])

b.task('vendor:xdom', _vendor_xdom)

b.task('default', ['build'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'browser:pure', 'test:assets', 'test:browser:pure' , 'docs'])

// HTTP server
// -----------

// starts a server when CLI argument '-s' is set
b.setServerPort(5550)
b.serve({ static: true, route: '/', folder: 'dist' })
b.serve({ static: true, route: '/test/', folder: '.test' })
b.serve({ static: true, route: '/docs/', folder: '.docs' })
<commit_msg>Added a note<commit_after>/*
  IMPORTANT: Don't use ES6 here, as some people are still on Node 4.
*/

var b = require('substance-bundler')
var path = require('path')

// Constants
// ---------

var TEST ='.test/'
var NPM = '.npm/'
var NPMDIST = NPM+'dist/'
var STUFF = [
  'package.json',
  'LICENSE.md',
  'README.md',
  'CHANGELOG.md',
  'make.js'
]

// Helpers
// -------
// Doing the actual work

// creates a browser bundle
function _browser(DIST, transpileToES5, production) {
  b.js('./index.es.js', {
    target: {
      dest: DIST+'substance.js',
      format: 'umd', moduleName: 'substance',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance',
      useStrict: !transpileToES5,
    },
    buble: transpileToES5,
    eslint: { exclude: [ 'dom/vendor.js' ] },
    cleanup: Boolean(production)
  })
  b.css('substance.css', DIST+'substance.css', { variables: true })
  b.css('substance.css', DIST+'substance.next.css')
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.css', {variables: true})
  b.css('substance-pagestyle.css', DIST+'substance-pagestyle.next.css')
  b.css('substance-reset.css', DIST+'substance-reset.css', {variables: true})
  b.css('substance-reset.css', DIST+'substance-reset.next.css')
}

// creates a server bundle
function _server(DIST, transpileToES5, production) {
  b.js('./index.es.js', {
    target: {
      dest: DIST+'substance.cjs.js',
      format: 'cjs',
      sourceMapRoot: __dirname, sourceMapPrefix: 'substance'
    },
    buble: transpileToES5,
    eslint: { exclude: [ 'dom/vendor.js' ] },
    cleanup: Boolean(production)
  })
}

// bundles the test suite to be run in a browser
function _testBrowser(transpileToES5, coverage) {

  b.js('./test/index.js', {
    target: {
      dest: TEST+'tests.js',
      format: 'umd', moduleName: 'tests'
    },
    buble: transpileToES5,
    external: { 'substance-test': 'substanceTest' },
    istanbul: coverage ? {
      include: [
        'collab/*.js',
        'dom/*.js',
        'model/**/*.js',
        // 'packages/**/*.js',
        'ui/*.js',
        // 'util/*.js'
      ],
      exclude: [ 'dom/vendor.js' ]
    } : false
  })
}

function _testNode() {
  b.js('./test/index.js', {
    target: {
      dest: TEST+'tests.cjs.js',
      format: 'cjs'
    },
    external: ['substance-test'],
    buble: true,
    commonjs: true
  })
}

function _runTestBrowser() {
  b.custom('Running browser tests...', {
    execute: function() {
      let karma = require('karma')
      const browser = process.env.TRAVIS ? 'ChromeTravis': 'Chrome'
      return new Promise(function(resolve) {
        let fails = 0
        const server = new karma.Server({
          configFile: __dirname + '/karma.conf.js',
          browsers: [browser],
          singleRun: true,
          failOnEmptyTestSuite: false
        }, function() {
          // why is exitCode always == 1?
          if (fails > 0) {
            process.exit(1)
          } else {
            resolve()
          }
        })
        server.on('run_complete', function(browsers, results) {
          if (results && results.failed > 0) {
            fails += results.failed
          }
        })
        server.start()
      })
    }
  })
}

// TODO: this should go into a helper provided by substance-test
// otherwise we need to write this again and again
function _runTestNode() {
  b.custom('Running nodejs tests...', {
    execute: function() {
      let cp = require('child_process')
      return new Promise(function(resolve, reject) {
        const child = cp.fork(path.join(__dirname, '.test/run-tests.js'))
        child.on('message', function(msg) {
          if (msg === 'done') { resolve() }
        })
        child.on('error', function(error) {
          reject(new Error(error))
        })
        child.on('close', function(exitCode) {
          if (exitCode !== 0) {
            process.exit(exitCode)
          } else {
            resolve()
          }
        })
      });
    }
  })
}

// generates API documentation
function _docs(mode, dest) {
  var docgen = require('substance-docgen')
  docgen.bundle(b, {
    src: [
      './*.md',
      './doc/*.md',
      './collab/*.js',
      './dom/*.js',
      './model/**/*.js',
      './packages/**/*.js',
      './ui/*.js',
      './util/*.js',
    ],
    dest: dest,
    config: './.docgenrc.js',
    mode: mode // one of: 'source', 'json', 'site' (default: 'json')
  })
}

function _vendor_xdom() {
  b.js('./dom/_vendor.js', {
    target: {
      dest: './dom/vendor.js',
      format: 'es'
    },
    ignore: [ 'events', 'entities' ],
    alias: {
      'dom-serializer': path.join(__dirname, 'dom/_domSerializer.js'),
      'inherits': path.join(__dirname, 'dom/_stub.js')
    },
    commonjs: true,
    json: true
  })
}

// Tasks
// -----

b.task('clean', function() {
  b.rm('./dist')
  b.rm('./.test')
  b.rm('./.docs')
  b.rm('./.npm')
})

b.task('browser:pure', function() {
  _browser('./dist/', false)
})

b.task('browser', function() {
  _browser('./dist/', true)
})

b.task('server', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', true)
})

b.task('server:pure', function() {
  // for the time being we transpile the cjs bundle
  // so it works in node 4 too
  _server('./dist/', false)
})

b.task('test:clean', function() {
  b.rm(TEST)
})

b.task('test:assets', function() {
  // TODO: it would be nice to treat such glob patterns
  // differently, so that we do not need to specify glob root
  b.copy('./node_modules/substance-test/dist/*', TEST, { root: './node_modules/substance-test/dist' })
})

b.task('test:browser', ['test:clean', 'test:assets'], function() {
  // buble necessary here, as travis has old browser versions
  _testBrowser(true)
})

b.task('test:browser:pure', ['test:clean', 'test:assets'], function() {
  // Pure ES6, and no buble here, for better dev experience
  _testBrowser(false)
})

b.task('test:browser:coverage', ['test:clean', 'test:assets'], function() {
  _testBrowser(true, true)
})

b.task('test:node', ['test:clean', 'test:assets'], _testNode)

b.task('run:test:browser', ['test:browser'], _runTestBrowser)

b.task('run:test:node', ['test:node'], _runTestNode)

b.task('run:test:coverage', ['test:browser:coverage'], _runTestBrowser)

b.task('npm:clean', function() {
  b.rm(NPM)
})

b.task('npm:copy:sources', function() {
  b.copy('index.es.js', NPM)
  b.copy('collab/*.js', NPM)
  b.copy('dom/**/*.js', NPM)
  b.copy('model/**/*.js', NPM)
  b.copy('packages/**/*.js', NPM)
  b.copy('ui/*.js', NPM)
  b.copy('util/*.js', NPM)
  b.copy('test/**/*.js', NPM)
  b.copy('*.css', NPM)
  b.copy('packages/**/*.css', NPM)
  STUFF.forEach(function(f) {
    b.copy(f, NPM)
  })
})

b.task('docs', function() {
  // creates a data.js file with prebuilt documentation
  // this gives the best trade-off between build and load time
  _docs('json', '.docs/')
})

b.task('npm:docs', function() {
  _docs('site', NPM+'docs/')
})

b.task('npm:browser', function() {
  _browser(NPMDIST, true, true)
})

b.task('npm:server', function() {
  _server(NPMDIST, true, true)
})

b.task('build', ['clean', 'browser', 'server'])

b.task('build:pure', ['clean', 'browser:pure', 'server:pure'])

b.task('test', ['test:clean', 'test:assets', 'run:test:browser', 'run:test:node'])

b.task('npm', ['npm:clean', 'npm:copy:sources', 'npm:docs', 'npm:browser', 'npm:server'])

b.task('vendor:xdom', _vendor_xdom)

b.task('default', ['build'])

// Default dev mode, only browser bundles are made and no ES5 transpilation happens
b.task('dev', ['clean', 'browser:pure', 'test:assets', 'test:browser:pure' , 'docs'])

// HTTP server
// -----------

// starts a server when CLI argument '-s' is set
b.setServerPort(5550)
b.serve({ static: true, route: '/', folder: 'dist' })
b.serve({ static: true, route: '/test/', folder: '.test' })
b.serve({ static: true, route: '/docs/', folder: '.docs' })
<|endoftext|>