<commit_before>MORSE = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    "D": "-..",
    "E": ".",
    "F": "..-.",
    "G": "--.",
    "H": "....",
    "I": "..",
    "J": ".---",
    "K": "-.-",
    "L": ".-..",
    "M": "--",
    "N": "-.",
    "O": "---",
    "P": ".--.",
    "Q": "--.-",
    "R": ".-.",
    "S": "...",
    "T": "-",
    "U": "..-",
    "V": "...-",
    "W": ".--",
    "X": "-..-",
    "Y": "-.--",
    "Z": "--..",
    // Numbers
    "1": ".----",
    "2": "..---",
    "3": "...--",
    "4": "....-",
    "5": ".....",
    "6": "-....",
    "7": "--...",
    "8": "---..",
    "9": "----.",
    "0": "-----"
};

jQuery(document).ready(function() {
	function play_morse() {
		var audioCtx = new (window.AudioContext || window.webkitAudioContext)();

		oscillator = audioCtx.createOscillator();
		oscillator.frequency.value = 750; // value in hertz

		var gainNode = audioCtx.createGain();
		gainNode.gain.value = 0;
		oscillator.connect(gainNode);
		gainNode.connect(audioCtx.destination);

		oscillator.start(0);

		var data = $('.input_morse').val().toUpperCase();
		var text = $('.morsecode');

		text.val('');
		text.show();

		var t = 0;
		var dot = 1.2 / 20;

		for(var i = 0; i < data.length; i++) {
			if(data[i] == ' ') {
				text.val(text.val() + ' ');
				t += dot * 3;
			} else if(MORSE[data[i]] !== undefined) {
				var code = MORSE[data[i]];
				for(var j = 0; j < code.length; j++) {
					switch(code[j]) {
						case '.':
							gainNode.gain.setValueAtTime(1.0, t);
							t += dot;
							gainNode.gain.setValueAtTime(0.0, t);
							break;
						case '-':
							gainNode.gain.setValueAtTime(1.0, t);
							t += dot * 3;
							gainNode.gain.setValueAtTime(0.0, t);
							break;
					}
					text.val(text.val() + code[j]);

					t += 3 * dot;
				}
				text.val(text.val() + ' ');
			}
		}
	}

	$('.play').on('click', function() {
		play_morse();
	});
	$('.morsecode').hide();
});
<commit_msg>Close audiocontext when clicking on play.<commit_after>MORSE = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    "D": "-..",
    "E": ".",
    "F": "..-.",
    "G": "--.",
    "H": "....",
    "I": "..",
    "J": ".---",
    "K": "-.-",
    "L": ".-..",
    "M": "--",
    "N": "-.",
    "O": "---",
    "P": ".--.",
    "Q": "--.-",
    "R": ".-.",
    "S": "...",
    "T": "-",
    "U": "..-",
    "V": "...-",
    "W": ".--",
    "X": "-..-",
    "Y": "-.--",
    "Z": "--..",
    // Numbers
    "1": ".----",
    "2": "..---",
    "3": "...--",
    "4": "....-",
    "5": ".....",
    "6": "-....",
    "7": "--...",
    "8": "---..",
    "9": "----.",
    "0": "-----"
};

jQuery(document).ready(function() {
  var audioCtx;

	function play_morse() {
	  if (audioCtx === undefined) {
      audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    } else {
      audioCtx.close();
      audioCtx = undefined;
      play_morse();
    }

		oscillator = audioCtx.createOscillator();
		oscillator.frequency.value = 750; // value in hertz

		var gainNode = audioCtx.createGain();
		gainNode.gain.value = 0;
		oscillator.connect(gainNode);
		gainNode.connect(audioCtx.destination);

		oscillator.start(0);

		var data = $('.input_morse').val().toUpperCase();
		var text = $('.morsecode');

		text.val('');
		text.show();

		var t = 0;
		var dot = 1.2 / 20;

		for(var i = 0; i < data.length; i++) {
			if(data[i] == ' ') {
				text.val(text.val() + ' ');
				t += dot * 3;
			} else if(MORSE[data[i]] !== undefined) {
				var code = MORSE[data[i]];
				for(var j = 0; j < code.length; j++) {
					switch(code[j]) {
						case '.':
							gainNode.gain.setValueAtTime(1.0, t);
							t += dot;
							gainNode.gain.setValueAtTime(0.0, t);
							break;
						case '-':
							gainNode.gain.setValueAtTime(1.0, t);
							t += dot * 3;
							gainNode.gain.setValueAtTime(0.0, t);
							break;
					}
					text.val(text.val() + code[j]);

					t += 3 * dot;
				}
				text.val(text.val() + ' ');
			}
		}
	}

	$('.play').on('click', function() {
		play_morse();
	});
	$('.morsecode').hide();
});
<|endoftext|>


<commit_before>var fs               = require('fs')
,   util             = require('util')
,   events           = require('events')
,   moment           = require('moment')
,   Playlist         = require('./api/Playlist')
,   Melted           = require('./api/Melted')
,   Media            = require('./api/Media')
,   ScheduledMedia   = require('./api/ScheduledMedia')
,   mvcp_server      = require('./drivers/mvcp/mvcp-driver')
,   playlists_driver = require('./drivers/playlists/playlists-driver')
,   status_driver    = require('./drivers/status/pubsub')
,   utils            = require('./utils')
,   config           = require('mbc-common').config.Mosto.General
,   _                = require('underscore')
,   heartbeats        = require('./heartbeats')
,   models           = require('./models/Mosto')
;

function mosto(customConfig) {

    /** CONFIGURATION */
    this.config = customConfig || config;
    this.server = undefined;
    this.server_started = false;
    this.pl_driver = undefined;
    this.status_driver = undefined;

    /* MODULES */
    this.heartbeats = undefined;

    events.EventEmitter.call(this);
}

util.inherits(mosto, events.EventEmitter);

mosto.prototype.initDriver = function() {
    var self = this;
    console.log("mbc-mosto: [INFO] Initializing playlists driver");

    self.pl_driver.on ("create", function(playlist) {
        var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
        self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        self.playlists.get("melted_medias").sync();
    } );
    self.pl_driver.on ("update", function(playlist) {
        var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
        self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        self.playlists.get("melted_medias").sync();
    } );
    self.pl_driver.on ("delete", function(playlist) {
        self.playlists.get("playlists").remove(playlist.id);
        self.playlists.get("melted_medias").sync();
    } );

    self.pl_driver.start();
};

mosto.prototype.stopDriver = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Stopping playlists driver");

    self.pl_driver.stop();

    self.pl_driver.removeAllListeners("create");
    self.pl_driver.removeAllListeners("update");
    self.pl_driver.removeAllListeners("delete");
};

mosto.prototype.startMvcpServer = function(callback) {
    var self = this;
    var result = self.server.initServer();
    result.then(function() {
        console.log("mbc-mosto: [INFO] MVCP server started");
        self.server_started = true;
        if (callback !== undefined) {
            callback();
        }
    }, function(err) {
        var e = new Error("mbc-mosto: [ERROR] Error starting MVCP server: " + err + ".\nRetrying in 2 seconds...");
        console.error(e);
        setTimeout(function() {
            self.startMvcpServer(callback);
        }, 2000);
    });
};

mosto.prototype.initHeartbeats = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Initializing heartbeats");

    self.heartbeats.on('frameStatus', function(status) {
        self.status_driver.setStatusClip(StatusClip(
            status.media.id,
            status.media.get('playlist_order'),
            status.media.playlist.id,
            status.media.get('fps'),
            status.frame,
            status.media.get('length')
        ));
    });
    self.heartbeats.on('clipStatus', function(media) {
        var melted_medias = self.playlists.get('melted_medias');
        var playlists = self.playlists.get('playlists');
        var status = {
            clip:{
                previous: undefined,
                current: undefined,
                next: undefined
            },
            show: {
                previous: undefined,
                current: undefined,
                next: undefined
            },
            position: 0,
            clips: melted_medias.toJSON(),
            status: none
        };
        /* clips */
        var index = melted_medias.indexOf(media);
        status.clip.current = media.toJSON();
        if( index > 0 )
            status.clip.previous = melted_medias.at(index-1).toJSON();
        if( index < melted_medias.length )
            status.clip.next = melted_medias.at(index+1).toJSON();
        /* shows */
        var playlist = playlists.find(function(pl) {
            return pl.indexOf(media) >= 0;
        });
        index = playlists.indexOf(playlist);
        status.show.current = playlist.toJSON();
        if( index > 0 )
            status.show.previous = playlists.at(index-1).toJSON();
        if( index < playlists.length )
            status.show.next = playlists.at(index+1).toJSON();
        self.status_driver.setStatus(status);
    });

    self.heartbeats.on("forceCheckout", function(window) {
        self.fetchPlaylists(window);
    });
    self.heartbeats.init();
};
mosto.prototype.fetchPlaylists = function(window) {
    self.driver.getPlaylists(window, function(playlists) {
        playlists.forEach(function(playlist) {
            var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
            self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        });
        self.playlists.get("melted_medias").sync();
    });
};

mosto.prototype.getModelPlaylistFromApiPlaylist = function(playlist) {
    //TODO: Remove this function and change driver to send Caspa Models
    var playlistJson   = {};
    playlistJson.name  = playlist.name;
    playlistJson.start = moment(playlist.startDate);
    playlistJson.end   = moment(playlist.endDate);
    playlistJson.id    = playlist.id;

    var start = playlistJson.start;
    var medias = new Mosto.MediaCollection();
    playlist.medias.forEach(function(media) {
        var mediaJson = {};
        mediaJson.playlist_order = media.orig_order;
        mediaJson.name           = media.name;
        mediaJson.type           = media.type;
        mediaJson.file           = media.file;
        //TODO: ASSUMING LENGTH COMES IN SOME KIND OF DATE FORMAT THAT CAN BE USED BY MOMENT
        mediaJson.length         = (moment(media.length) / 1000) * media.fps;
        mediaJson.fps            = media.fps;
        mediaJson.start          = start;
        mediaJson.end            = start + moment(media.length);
        mediaJson.id             = media.id;

        var mostoMedia = new Mosto.Media(mediaJson);
        medias.add(mostoMedia);

        start = start + moment(media.length);
    });

    playlistJson.medias = medias;

    return new Mosto.Playlist(playlistJson);
};

mosto.prototype.stopHeartbeats = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Stopping heartbeats");

    self.heartbeats.stop();

    self.heartbeats.removeAllListeners("frameStatus");
    self.heartbeats.removeAllListeners("clipStatus");
};

mosto.prototype.init = function( melted, callback) {
    console.log("mbc-mosto: [INFO] Init mbc-mosto... ") ;
    var self = this;
    /*
     * inicializar los drivers
     * inicializar los modelos backbone
     * inicializar los heartbeats
     * linkear los eventos entre pl driver y backbone driver
     * linkear heartbeat con status driver
     */
    function startall() {
        self.server        = new mvcp_server(self.config.mvcp_server);
        self.pl_driver     = new playlists_driver(self.config.playlist_server);
        self.status_driver = new status_driver();
        self.playlists     = models.Playlists;
        self.heartbeats    = new heartbeats();

        self.initDriver();
        self.initHeartbeats();

        self.startMvcpServer( function() {
            self.fetchPlaylists({from: now, to: now + (4 * 60 * 60 * 1000)});
            if (callback) callback();
        } );
    }

    function check_and_start() {
        Melted.is_running(function(running) {
            if (!running) {
                Melted.start(function(pid) {
                    Melted.setup( undefined, undefined, function(result) {
                        startall();
                    });
                });
            } else {
                startall();
            }
        });
    };

    if (melted!==undefined) {
        Melted = melted;
        check_and_start();
    }
    else
        Melted.take( check_and_start );

};

mosto.prototype.finish = function(callback) {
    console.log("mbc-mosto: [INFO] Finish mbc-mosto... ") ;
    self.stopDriver();
    self.player.stop();
    Melted.stop(function(pid) {
        setTimeout( function() {
            Melted.leave();
            if (callback) callback();
        }, 1000 );
    });
}

}

exports = module.exports = function(customConfig) {
    var mosto_server = new mosto(customConfig);
    return mosto_server;
};
/*

  mosto tiene que:

  * inicializar melted
  * inicializar los drivers
  * inicializar los modelos backbone
  * inicializar los heartbeats
  * linkear los eventos entre pl driver y backbone driver
  * linkear heartbeat con status driver

  */
<commit_msg>Modified finish to include stopHeartbeats<commit_after>var fs               = require('fs')
,   util             = require('util')
,   events           = require('events')
,   moment           = require('moment')
,   Playlist         = require('./api/Playlist')
,   Melted           = require('./api/Melted')
,   Media            = require('./api/Media')
,   ScheduledMedia   = require('./api/ScheduledMedia')
,   mvcp_server      = require('./drivers/mvcp/mvcp-driver')
,   playlists_driver = require('./drivers/playlists/playlists-driver')
,   status_driver    = require('./drivers/status/pubsub')
,   utils            = require('./utils')
,   config           = require('mbc-common').config.Mosto.General
,   _                = require('underscore')
,   heartbeats        = require('./heartbeats')
,   models           = require('./models/Mosto')
;

function mosto(customConfig) {

    /** CONFIGURATION */
    this.config = customConfig || config;
    this.server = undefined;
    this.server_started = false;
    this.pl_driver = undefined;
    this.status_driver = undefined;

    /* MODULES */
    this.heartbeats = undefined;

    events.EventEmitter.call(this);
}

util.inherits(mosto, events.EventEmitter);

mosto.prototype.initDriver = function() {
    var self = this;
    console.log("mbc-mosto: [INFO] Initializing playlists driver");

    self.pl_driver.on ("create", function(playlist) {
        var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
        self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        self.playlists.get("melted_medias").sync();
    } );
    self.pl_driver.on ("update", function(playlist) {
        var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
        self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        self.playlists.get("melted_medias").sync();
    } );
    self.pl_driver.on ("delete", function(playlist) {
        self.playlists.get("playlists").remove(playlist.id);
        self.playlists.get("melted_medias").sync();
    } );

    self.pl_driver.start();
};

mosto.prototype.stopDriver = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Stopping playlists driver");

    self.pl_driver.stop();

    self.pl_driver.removeAllListeners("create");
    self.pl_driver.removeAllListeners("update");
    self.pl_driver.removeAllListeners("delete");
};

mosto.prototype.startMvcpServer = function(callback) {
    var self = this;
    var result = self.server.initServer();
    result.then(function() {
        console.log("mbc-mosto: [INFO] MVCP server started");
        self.server_started = true;
        if (callback !== undefined) {
            callback();
        }
    }, function(err) {
        var e = new Error("mbc-mosto: [ERROR] Error starting MVCP server: " + err + ".\nRetrying in 2 seconds...");
        console.error(e);
        setTimeout(function() {
            self.startMvcpServer(callback);
        }, 2000);
    });
};

mosto.prototype.initHeartbeats = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Initializing heartbeats");

    self.heartbeats.on('frameStatus', function(status) {
        self.status_driver.setStatusClip(StatusClip(
            status.media.id,
            status.media.get('playlist_order'),
            status.media.playlist.id,
            status.media.get('fps'),
            status.frame,
            status.media.get('length')
        ));
    });
    self.heartbeats.on('clipStatus', function(media) {
        var melted_medias = self.playlists.get('melted_medias');
        var playlists = self.playlists.get('playlists');
        var status = {
            clip:{
                previous: undefined,
                current: undefined,
                next: undefined
            },
            show: {
                previous: undefined,
                current: undefined,
                next: undefined
            },
            position: 0,
            clips: melted_medias.toJSON(),
            status: none
        };
        /* clips */
        var index = melted_medias.indexOf(media);
        status.clip.current = media.toJSON();
        if( index > 0 )
            status.clip.previous = melted_medias.at(index-1).toJSON();
        if( index < melted_medias.length )
            status.clip.next = melted_medias.at(index+1).toJSON();
        /* shows */
        var playlist = playlists.find(function(pl) {
            return pl.indexOf(media) >= 0;
        });
        index = playlists.indexOf(playlist);
        status.show.current = playlist.toJSON();
        if( index > 0 )
            status.show.previous = playlists.at(index-1).toJSON();
        if( index < playlists.length )
            status.show.next = playlists.at(index+1).toJSON();
        self.status_driver.setStatus(status);
    });

    self.heartbeats.on("forceCheckout", function(window) {
        self.fetchPlaylists(window);
    });

    self.heartbeats.init();
};

mosto.prototype.fetchPlaylists = function(window) {
    self.driver.getPlaylists(window, function(playlists) {
        playlists.forEach(function(playlist) {
            var mostoPlaylist = self.getModelPlaylistFromApiPlaylist(playlist);
            self.playlists.get("playlists").add(mostoPlaylist, {merge: true});
        });
        self.playlists.get("melted_medias").sync();
    });
};

mosto.prototype.getModelPlaylistFromApiPlaylist = function(playlist) {
    //TODO: Remove this function and change driver to send Caspa Models
    var playlistJson   = {};
    playlistJson.name  = playlist.name;
    playlistJson.start = moment(playlist.startDate);
    playlistJson.end   = moment(playlist.endDate);
    playlistJson.id    = playlist.id;

    var start = playlistJson.start;
    var medias = new Mosto.MediaCollection();
    playlist.medias.forEach(function(media) {
        var mediaJson = {};
        mediaJson.playlist_order = media.orig_order;
        mediaJson.name           = media.name;
        mediaJson.type           = media.type;
        mediaJson.file           = media.file;
        //TODO: ASSUMING LENGTH COMES IN SOME KIND OF DATE FORMAT THAT CAN BE USED BY MOMENT
        mediaJson.length         = (moment(media.length) / 1000) * media.fps;
        mediaJson.fps            = media.fps;
        mediaJson.start          = start;
        mediaJson.end            = start + moment(media.length);
        mediaJson.id             = media.id;

        var mostoMedia = new Mosto.Media(mediaJson);
        medias.add(mostoMedia);

        start = start + moment(media.length);
    });

    playlistJson.medias = medias;

    return new Mosto.Playlist(playlistJson);
};

mosto.prototype.stopHeartbeats = function() {
    var self = this;

    console.log("mbc-mosto: [INFO] Stopping heartbeats");

    self.heartbeats.stop();

    self.heartbeats.removeAllListeners("frameStatus");
    self.heartbeats.removeAllListeners("clipStatus");
};

mosto.prototype.init = function( melted, callback) {
    console.log("mbc-mosto: [INFO] Init mbc-mosto... ") ;
    var self = this;
    /*
     * inicializar los drivers
     * inicializar los modelos backbone
     * inicializar los heartbeats
     * linkear los eventos entre pl driver y backbone driver
     * linkear heartbeat con status driver
     */
    function startall() {
        self.server        = new mvcp_server(self.config.mvcp_server);
        self.pl_driver     = new playlists_driver(self.config.playlist_server);
        self.status_driver = new status_driver();
        self.playlists     = models.Playlists;
        self.heartbeats    = new heartbeats();

        self.initDriver();
        self.initHeartbeats();

        self.startMvcpServer( function() {
            self.fetchPlaylists({from: now, to: now + (4 * 60 * 60 * 1000)});
            if (callback) callback();
        } );
    }

    function check_and_start() {
        Melted.is_running(function(running) {
            if (!running) {
                Melted.start(function(pid) {
                    Melted.setup( undefined, undefined, function(result) {
                        startall();
                    });
                });
            } else {
                startall();
            }
        });
    };

    if (melted!==undefined) {
        Melted = melted;
        check_and_start();
    }
    else
        Melted.take( check_and_start );

};

mosto.prototype.finish = function(callback) {
    var self = this;

    console.log("mbc-mosto: [INFO] Finish mbc-mosto... ") ;
    self.stopDriver();
    self.stopHeartbeats();
    self.player.stop();
    Melted.stop(function(pid) {
        setTimeout( function() {
            Melted.leave();
            if (callback) callback();
        }, 1000 );
    });
};

exports = module.exports = function(customConfig) {
    var mosto_server = new mosto(customConfig);
    return mosto_server;
};
/*

  mosto tiene que:

  * inicializar melted
  * inicializar los drivers
  * inicializar los modelos backbone
  * inicializar los heartbeats
  * linkear los eventos entre pl driver y backbone driver
  * linkear heartbeat con status driver

  */
<|endoftext|>


<commit_before>module.exports = (function jsHintOptions() {

    return {
        'globalOptions': {
            'maxerr': 50,
            'bitwise': true,
            'camelcase': true,
            'curly': true,
            'eqeqeq': true,
            'forin': true,
            'freeze': true,
            'immed': true,
            'indent': 4,
            'latedef': true,
            'newcap': true,
            'noarg': true,
            'noempty': true,
            'nonbsp': true,
            'nonew': false,
            'plusplus': false,
            'quotmark': 'single',
            'undef': true,
            'unused': true,
            'strict': true,
            'maxparams': 3,
            'maxdepth': false,
            'maxstatements': false,
            'maxcomplexity': false,
            'maxlen': 240,
            'asi': false,
            'boss': true,
            'debug': false,
            'eqnull': false,
            'es5': false,
            'esnext': false,
            'moz': false,
            'evil': false,
            'expr': false,
            'funcscope': false,
            'globalstrict': true,
            'iterator': false,
            'lastsemic': false,
            'laxbreak': false,
            'laxcomma': false,
            'loopfunc': false,
            'multistr': false,
            'noyield': false,
            'notypeof': false,
            'proto': false,
            'scripturl': false,
            'shadow': false,
            'sub': true,
            'supernew': false,
            'validthis': false,
            'browser': true,
            'browserify': false,
            'couch': false,
            'devel': false,
            'dojo': false,
            'jasmine': true,
            'jquery': true,
            'mocha': true,
            'mootools': false,
            'node': true,
            'nonstandard': false,
            'prototypejs': false,
            'qunit': false,
            'rhino': false,
            'shelljs': false,
            'worker': false,
            'wsh': false,
            'yui': false,
            'globals': {
                'angular': false,
                'beforeEach': false,
                'browser': false,
                'by': false,
                'expect': false,
                'inject': false,
                'protractor': false
            }
        }
    }

})();
<commit_msg>fixed rules<commit_after>module.exports = (function jsHintOptions() {

    return {
        'globalOptions': {
            'maxerr': 50,
            'bitwise': true,
            'camelcase': true,
            'curly': true,
            'eqeqeq': true,
            'forin': true,
            'freeze': true,
            'immed': true,
            'indent': 4,
            'latedef': true,
            'newcap': true,
            'noarg': true,
            'noempty': true,
            'nonbsp': true,
            'nonew': false,
            'plusplus': false,
            'quotmark': 'single',
            'undef': true,
            'unused': true,
            'strict': true,
            'maxdepth': false,
            'maxstatements': false,
            'maxcomplexity': false,
            'maxlen': 240,
            'asi': false,
            'boss': true,
            'debug': false,
            'eqnull': false,
            'es5': false,
            'esnext': false,
            'moz': false,
            'evil': false,
            'expr': false,
            'funcscope': false,
            'globalstrict': true,
            'iterator': false,
            'lastsemic': false,
            'laxbreak': false,
            'laxcomma': false,
            'loopfunc': false,
            'multistr': false,
            'noyield': false,
            'notypeof': false,
            'proto': false,
            'scripturl': false,
            'shadow': false,
            'sub': true,
            'supernew': false,
            'validthis': false,
            'browser': true,
            'browserify': false,
            'couch': false,
            'devel': false,
            'dojo': false,
            'jasmine': true,
            'jquery': true,
            'mocha': true,
            'mootools': false,
            'node': true,
            'nonstandard': false,
            'prototypejs': false,
            'qunit': false,
            'rhino': false,
            'shelljs': false,
            'worker': false,
            'wsh': false,
            'yui': false,
            'globals': {
                'X2JS': true,
                'angular': false,
                'beforeEach': false,
                'browser': false,
                'by': false,
                'expect': false,
                'inject': false,
                'protractor': false
            }
        }
    }

})();
<|endoftext|>


<commit_before>
/*global assert, sinon*/ // chai

define(['BlinkForms', 'testUtils'], function (Forms, testUtils) {

  window.MSApp = {};

  if (testUtils.isPhantom()) {
    return;
  }

  testUtils.defineFormLoadSuite('TestForm', 'add');

  suite('23_1: Location Native field', function () {

    test('Render form with data', function (done) {
      var form = Forms.current;

      $.ajax({
        type: "GET",
        url: "getformrecord.xml",
        dataType: "xml"}).then(
        function (data) {
          var record = {}, node, nodes;
          nodes = data.evaluate('//' + form.attributes.name, data);
          node = nodes.iterateNext();
          _.each(node.children, function (key) {
            record[key.nodeName] = key.innerHTML;
          });
          form.setRecord(record).then(function () {
            form.data().then(function (formdata) {
              var keys = ['id', 'location1', 'location2', '_action'];
              _.each(keys, function (k) {
                assert.ok(formdata[k], k + " does not exist");
              });
              done();
            }, function () {
              assert(false, "failed to set record");
              done();
            });
          });
        }
     );
    });

    test('LOCATE button - success callback + no location', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      window.navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(null);

          element.attributes._view.on('confirmLocation', function (loc) {
            assert.equal(loc, null);
            element.attributes._view.off('confirmLocation');
            done();
          });
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(window.navigator.map, "confirmLocation");
      spyStatic = sinon.spy(window.navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 0);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('LOCATE button - success callback + location', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      window.navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {"latitude": -33.867487, "longitude": 151.20699, "accuracy": 25000};
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);

          setTimeout(function () {
            assert.deepEqual(element.get('value'), sampleLocation);
            done();
          }, 1);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(window.navigator.map, "confirmLocation");
      spyStatic = sinon.spy(window.navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 1);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('LOCATE button - error callback', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      window.navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var spy2 = sinon.spy(window.console, "error");
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          assert(!onError("test error"));

          setTimeout(function () {
            assert.equal(spy2.callCount, 1);
            window.console.error.restore();
            done();
          }, 1);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(window.navigator.map, "confirmLocation");
      spyStatic = sinon.spy(window.navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 0);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('CLEAR button works as expected', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $clear = $view.find('.ui-btn').children('button').last(),
        value;

      $clear.trigger('click');

      setTimeout(function () {
          value = element.get('value');
          assert.notOk(value, "value still exists");
          done();
      }, 0);
    });

    test('LOCATE button - success callback + location + getStaticImage > success', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic, sampleImage;

      sampleImage = "data:image/jpeg;base64,blah";

      window.navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {
            "latitude": -33.867487,
            "longitude": 151.20699,
            "accuracy": 25000
          };
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);

          onSuccess(sampleImage);
        }
      };

      spy = sinon.spy(window.navigator.map, "confirmLocation");
      spyStatic = sinon.spy(window.navigator.map, "getStaticMap");

      element.once('change:value', function () {
        var $img;
        assert.equal(spy.callCount, 1);
        assert.equal(spyStatic.callCount, 1);
        // there will be atleast one image and src would be the content sent by onSuccess
        $img = element.get('_view').$el.find('img');
        assert.equal($img.length, 1, "image not found");
        assert.equal(element.get('_view').$el.find('img').attr('src'), sampleImage, "invalid image src");

        done();
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');
    });

    test('LOCATE button - success callback + location + getStaticImage > error', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic, spyError;

      window.navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {
            "latitude": -33.861234,
            "longitude": 151.20699,
            "accuracy": 25000
          };
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);

          onError("map cannot be displayed");
        }
      };

      spy = sinon.spy(window.navigator.map, "confirmLocation");
      spyStatic = sinon.spy(window.navigator.map, "getStaticMap");
      spyError = sinon.spy(window.console, "error");

      element.once('change:value', function () {
        var $img;
        assert.equal(spy.callCount, 1);
        assert.equal(spyStatic.callCount, 1);
        assert.equal(spyError.callCount, 1);
        // there won't be any image, because of error call
        $img = element.get('_view').$el.find('img');
        assert.equal($img.length, 0, "image not found");
        window.console.error.restore();

        done();
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');
    });

  }); // END: suite('Form', ...)

});
<commit_msg>(chore) tests need to explicitly depend on sinon<commit_after>
/*global assert, sinon*/ // chai

define(['BlinkForms', 'testUtils', 'sinon'], function (Forms, testUtils, sinon) {

  window.MSApp = {};

  if (testUtils.isPhantom()) {
    return;
  }

  testUtils.defineFormLoadSuite('TestForm', 'add');

  suite('23_1: Location Native field', function () {

    test('Render form with data', function (done) {
      var form = Forms.current;

      $.ajax({
        type: "GET",
        url: "getformrecord.xml",
        dataType: "xml"}).then(
        function (data) {
          var record = {}, node, nodes;
          nodes = data.evaluate('//' + form.attributes.name, data);
          node = nodes.iterateNext();
          _.each(node.children, function (key) {
            record[key.nodeName] = key.innerHTML;
          });
          form.setRecord(record).then(function () {
            form.data().then(function (formdata) {
              var keys = ['id', 'location1', 'location2', '_action'];
              _.each(keys, function (k) {
                assert.ok(formdata[k], k + " does not exist");
              });
              done();
            }, function () {
              assert(false, "failed to set record");
              done();
            });
          });
        }
     );
    });

    test('LOCATE button - success callback + no location', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(null);

          element.attributes._view.on('confirmLocation', function (loc) {
            assert.equal(loc, null);
            element.attributes._view.off('confirmLocation');
            done();
          });
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(navigator.map, "confirmLocation");
      spyStatic = sinon.spy(navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 0);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('LOCATE button - success callback + location', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {"latitude": -33.867487, "longitude": 151.20699, "accuracy": 25000};
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);

          setTimeout(function () {
            assert.deepEqual(element.get('value'), sampleLocation);
            done();
          }, 1);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(navigator.map, "confirmLocation");
      spyStatic = sinon.spy(navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 1);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('LOCATE button - error callback', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic;

      navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var spy2 = sinon.spy(window.console, "error");
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          assert(!onError("test error"));

          setTimeout(function () {
            assert.equal(spy2.callCount, 1);
            window.console.error.restore();
            done();
          }, 1);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
        }
      };

      spy = sinon.spy(navigator.map, "confirmLocation");
      spyStatic = sinon.spy(navigator.map, "getStaticMap");

      element.once('change:value', function () {
        assert.equal(spyStatic.callCount, 0);
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');

      assert.equal(spy.callCount, 1);

    });

    test('CLEAR button works as expected', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $clear = $view.find('.ui-btn').children('button').last(),
        value;

      $clear.trigger('click');

      setTimeout(function () {
          value = element.get('value');
          assert.notOk(value, "value still exists");
          done();
      }, 0);
    });

    test('LOCATE button - success callback + location + getStaticImage > success', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic, sampleImage;

      sampleImage = "data:image/jpeg;base64,blah";

      navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {
            "latitude": -33.867487,
            "longitude": 151.20699,
            "accuracy": 25000
          };
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);

          onSuccess(sampleImage);
        }
      };

      spy = sinon.spy(navigator.map, "confirmLocation");
      spyStatic = sinon.spy(navigator.map, "getStaticMap");

      element.once('change:value', function () {
        var $img;
        assert.equal(spy.callCount, 1);
        assert.equal(spyStatic.callCount, 1);
        // there will be atleast one image and src would be the content sent by onSuccess
        $img = element.get('_view').$el.find('img');
        assert.equal($img.length, 1, "image not found");
        assert.equal(element.get('_view').$el.find('img').attr('src'), sampleImage, "invalid image src");

        done();
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');
    });

    test('LOCATE button - success callback + location + getStaticImage > error', function (done) {
      var element = Forms.current.getElement('location2'),
        $view = element.attributes._view.$el,
        $locate = $view.find('.ui-btn').children('button').first(),
        spy, spyStatic, spyError;

      navigator.map = {
        confirmLocation: function (onSuccess, onError, options) {
          var sampleLocation = {
            "latitude": -33.861234,
            "longitude": 151.20699,
            "accuracy": 25000
          };
          assert.isFunction(onSuccess);
          assert.isFunction(onError);
          assert.ok(options.latitude);
          assert.ok(options.longitude);

          onSuccess(sampleLocation);
        },
        getStaticMap: function (onSuccess, onError) {
          assert.isFunction(onSuccess);
          assert.isFunction(onError);

          onError("map cannot be displayed");
        }
      };

      spy = sinon.spy(navigator.map, "confirmLocation");
      spyStatic = sinon.spy(navigator.map, "getStaticMap");
      spyError = sinon.spy(window.console, "error");

      element.once('change:value', function () {
        var $img;
        assert.equal(spy.callCount, 1);
        assert.equal(spyStatic.callCount, 1);
        assert.equal(spyError.callCount, 1);
        // there won't be any image, because of error call
        $img = element.get('_view').$el.find('img');
        assert.equal($img.length, 0, "image not found");
        window.console.error.restore();

        done();
      });

      assert.equal(spy.callCount, 0);

      $locate.trigger('click');
    });

  }); // END: suite('Form', ...)

});
<|endoftext|>


<commit_before>// NIMOY

var Env = require('./_env_N')

var DefaultUser = {
  host:'blacksea',
  connections:'',
  modules:''
}

var EnvOpts = {
  path_wilds:'./_wilds',
  path_static:'./_static',
  path_styl:'./_static/default.styl',
  path_css:'./_static/styles.css',
  path_bundle:'./_static/bundle.js',
  path_js:'./_env_B.js',
  path_data:'./data',
  port:80,
}

var Environment = new Env(EnvOpts, function serverRunning () {
  console.log('nimoy running on port '+EnvOpts.port)
  Environment.api.write(JSON.stringify(['load', null]))
  Environment.api.pipe(process.stdout)
})
<commit_msg>log api output<commit_after>// NIMOY

var Env = require('./_env_N')

var DefaultUser = {
  host:'blacksea',
  connections:'',
  modules:''
}

var EnvOpts = {
  path_wilds:'./_wilds',
  path_static:'./_static',
  path_styl:'./_static/default.styl',
  path_css:'./_static/styles.css',
  path_bundle:'./_static/bundle.js',
  path_js:'./_env_B.js',
  path_data:'./data',
  port:80,
}

var Environment = new Env(EnvOpts, function serverRunning () {
  console.log('nimoy running on port '+EnvOpts.port)
  Environment.api.write(JSON.stringify(['load',null]))
})
Environment.api.on('data', function (d) {
  console.log(d)
})

<|endoftext|>


<commit_before>var fs = require('fs')
var level = require('level')
var multiLevel = require('multilevel')
var liveStream = require('level-live-stream')
var bricoleur = require('./bricoleur')
var fileServer = require('node-static').Server
var webSocketStream = require('websocket-stream')
var webSocketServer = require('ws').Server

var server
var brico
var file

var config = process.argv[2] ? config = require(process.argv[2]) : config = require('./__conf.json')

if (config.dirModules.slice(-1) !== '/') config.dirModules += '/'

if (config.dirStatic.slice(-1) !== '/') config.dirStatic += '/'

if (config.crypto) {

  var cipher = 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:'
  + 'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:'
  + 'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'

  server = require('https').createServer({
    key : fs.readfilesync(config.crypto.key)
    cert : fs.readfilesync(config.crypto.cert)
    honorcipherorder : true
    ciphers : cipher
  }, HandleRequests)

  file = fileServer(config.dirStatic, {'Strict-Transport-Security':'max-age=31536000'})

} else {
  server = require('http').createServer(HandleRequests)
  file = new fileServer(config.dirStatic)
}

function HandleRequests (req, res) {
  file.serve(req, res, function ifThereIsNoFile (e, result) {
    if (e) file.serveFile('/index.html',404,{},req,res)
  })
}

server.listen(config.port, config.host, function setupWebSocket () {
  var ws = new webSocketServer({server:server})

  ws.on('connection', function handleSoc (soc) {
    var levelServer = multiLevel.server(db)
    var wss = webSocketStream(soc)

    wss.pipe(levelServer).pipe(wss)

    wss.on('error', function (e) {
      console.error('webSocStreamErr: '+e)
    })

    brico.installMuxDemux(levelServer)
  })
})

var db = level('./'+config.host)
liveStream.install(db)
multiLevel.writeManifest(db, config.dirStatic+'manifest.json')

brico = bricoleur(db)
brico.on('error', console.error)

generateStaticFiles (function mapAndBrowserify () {
  var map = require('./_map')({
    wilds : config.dirModules,
    bundle : config.dirStatic+'bundle.js',
    browserify: config.dirStatic+'boot.js',
    min : config.minify
  })
  map.on('error', console.error)
  map.on('data', function (d) {
    db.put('^',d)
  })
  map.on('end', function () {
    // console.log(log('wrote bundle ('+(stat.size/1024).toFixed(2)+'/kb) to '+config.dirStatic+'bundle.js'))
    console.log('nimoy running on host: "'+config.host+'" port: "'+config.port+'"')
    if (config.cli === true) process.stdin.pipe(require('./_cli')()).pipe(brico).pipe(process.stdout)
  })
}

function generateStaticFiles (end) {

  var indexHtml = '<!doctype html>'
    + '<meta charset="utf-8">'
    + ''
    + ''

  fs.writeFileSync(config.dirStatic+'index.html', indexHtml)

  fs.writeFileSync(config.dirStatic+'boot.js', functionToString(function () {
  // Start Browser Boot
  var websocStream = require('websocket-stream')
  var host = window.document.location.host.replace(/:.*/, '')
  if (window.location.port) host += (':'+window.location.port)
  if (window.location.protocol === 'https:') var ws = websocStream('wss://' + host)
  if (window.location.protocol === 'http:') var ws = websocStream('ws://' + host)

  var ml = require('multilevel')
  var manifest = require('./manifest.json')
  var multiLevel = ml.client(manifest)
  var rpc = multiLevel.createRpcStream()
  ws.pipe(rpc).pipe(ws)
  ws.on('error', function (e) {
    console.error(e)
  })

  var bricoleur = require('../bricoleur')
  var brico = bricoleur(multiLevel)
  brico.installMuxDemux(rpc)
  brico.on('error', function (e) {
    console.error(e)
  })
  // End Browser Boot
  }))

  end()
}

// Utils
function functionToString (fn) {// takes fn as input, unwraps and returns string
  var s = fn.toString()
  return s.substring(0,s.lastIndexOf('\n')).substring(s.indexOf('\n'),s.length)
}
<commit_msg>tidy & use createWriteStream to write map<commit_after>var fs = require('fs')
var level = require('level')
var multiLevel = require('multilevel')
var liveStream = require('level-live-stream')
var fileServer = require('node-static').Server
var webSocketStream = require('websocket-stream')
var webSocketServer = require('ws').Server
var bricoleur = require('./bricoleur')
var mappify = require('./_map')

var server
var brico
var file
var db

var config = process.argv[2] ? config = require(process.argv[2]) : config = require('./__conf.json')

if (config.modules.slice(-1) !== '/') config.modules += '/'
if (config.static.slice(-1) !== '/') config.static += '/'

if (config.crypto) {
  var cipher = 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:'
  + 'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:'
  + 'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'

  server = require('https').createServer({
    key : fs.readfilesync(config.crypto.key)
    cert : fs.readfilesync(config.crypto.cert)
    honorcipherorder : true
    ciphers : cipher
  }, doHttp)

  file = new fileServer(config.static, {'Strict-Transport-Security':'max-age=31536000'})
}

if (!config.crypto) {
  server = require('http').createServer(doHttp)
  file = new fileServer(config.static)
}

function doHttp (req, res) {
  file.serve(req, res, function thereIsNoFile (e, result) {
    if (e) file.serveFile('/index.html',404,{},req,res)
    // also pass to brico
  })
}

server.listen(config.port, config.host, function setupWebSocket () {
  var ws = new webSocketServer({server:server})

  ws.on('connection', function newSocketConnection (soc) {
    var levelServer = multiLevel.server(db)
    var wss = webSocketStream(soc)

    wss.pipe(levelServer).pipe(wss)

    wss.on('error', function (e) {
      console.error('webSocStreamErr: '+e)
    })

    brico.installMuxDemux(levelServer)
  })
})

db = level('./'+config.host)
liveStream.install(db)
multiLevel.writeManifest(db, config.static+'manifest.json')

brico = bricoleur(db)
brico.on('error', console.error)

var browserBootScript = config.static+'boot.js'

writeBrowserFiles(function thenMappify () {
  var dbWriteStream = db.createWriteStream({valueEncoding:'json'})

  mappify({
    wilds : config.modules,
    bundle : config.static+'bundle.js',
    browserify : browserBootScript,
    min : config.minify
  }).pipe(dbWriteStream)

  mappify.on('error', console.error)

  dbWriteStream.on('end', function () {
    // console.log(log('wrote bundle ('+(stat.size/1024).toFixed(2)+'/kb) to '+config.static+'bundle.js'))
    console.log('nimoy running on host: "'+config.host+'" port: "'+config.port+'"')
    if (config.cli === true) process.stdin.pipe(require('./_cli')()).pipe(brico).pipe(process.stdout)
  })
}

function writeBrowserFiles (written) {

  var indexHtml = '<!doctype html>'
    + '<meta charset="utf-8">'
    + ''
    + ''

  fs.writeFileSync(config.static+'index.html', indexHtml)

  fs.writeFileSync(browserBootScript, thisFnBodyToString(function () {
  // Start Browser Boot
  var websocStream = require('websocket-stream')
  var host = window.document.location.host.replace(/:.*/, '')
  if (window.location.port) host += (':'+window.location.port)
  if (window.location.protocol === 'https:') var ws = websocStream('wss://' + host)
  if (window.location.protocol === 'http:') var ws = websocStream('ws://' + host)

  var ml = require('multilevel')
  var manifest = require('./manifest.json')
  var multiLevel = ml.client(manifest)
  var rpc = multiLevel.createRpcStream()
  ws.pipe(rpc).pipe(ws)
  ws.on('error', function (e) {
    console.error(e)
  })

  var bricoleur = require('../bricoleur')
  var brico = bricoleur(multiLevel)
  brico.installMuxDemux(rpc)
  brico.on('error', function (e) {
    console.error(e)
  })
  // End Browser Boot
  }))

  written()
}

// Utils
function thisFnBodyToString (fn) {// takes fn as input, unwraps and returns string
  var s = fn.toString()
  return s.substring(0,s.lastIndexOf('\n')).substring(s.indexOf('\n'),s.length)
}
<|endoftext|>


<commit_before>// ========================================================================
// Copyright (c) 2008-2009, Metaweb Technologies, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB
// TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ========================================================================

/*
**  Rendering the spreadsheet back to the user
*/

function onDisplayOutputScreen() {
    setTimeout(checkLogin,0);
    setTimeout(renderSpreadsheet,0);
    setTimeout(prepareTriples,0);
}
function onHideOutputScreen() {
    if (spreadsheetRendererYielder)
        spreadsheetRendererYielder.cancel();
    if (tripleGetterYielder)
        tripleGetterYielder.cancel();
    $("#outputSpreadSheet")[0].value = "";
}

function encodeLine(arr) {
    var values = [];
    for(var i = 0; i < headers.length; i++){
        var val = arr[i];
        if (typeof val == "undefined")
            values.push("");
        else if (!val.match(/(\t|\"|\n)/))
            values.push(arr[i])
        else {
            val = val.replace(/"/g, '""');
            values.push('"' + val + '"');
        }
    }
    return values.join("\t");
}

//Like getChainedProperty, only it preserves array placement
function getChainedPropertyPreservingPlace(entity, prop) {
    var slots = [entity];
    $.each(prop.split(":"), function(_,part) {
        var newSlots = [];
        $.each(slots, function(_,slot) {
            if (!slot || !slot[part])
                newSlots.push(undefined);
            else
                newSlots = newSlots.concat($.makeArray(slot && slot[part]))
        })
        slots = newSlots;
    });
    if (slots === []) return undefined;
    return slots;
}

function encodeRow(row) {
    var lines = [[]];
    for (var i = 0; i < headers.length; i++){
        var val = getChainedPropertyPreservingPlace(row, headers[i]);
        if ($.isArray(val)) {
            for (var j = 0; j < val.length; j++) {
                if (lines[j] == undefined) lines[j] = [];
                lines[j][i] = textValue(val[j]);
            }
        }
        else
            lines[0][i] = textValue(val);
    }
    return $.map(lines,encodeLine);
}

var spreadsheetRendererYielder;
function renderSpreadsheet() {
    spreadsheetRendererYielder = new Yielder();
    var lines = [];
    lines.push(encodeLine(headers));
    $("#outputSpreadSheet")[0].value = "One moment, rendering...";

    politeEach(rows, function(idx, row) {
        lines = lines.concat(encodeRow(row));
    },
    function() {
        $("#outputSpreadSheet")[0].value = lines.join("\n");
    }, spreadsheetRendererYielder);
}

function prepareTriples() {
    getTriples(rows, function(triples) {
        politeMap(triples,function(_,val){return JSON.stringify(val)},
            function(encodedTriples) {
                var tripleString = encodedTriples.join("\n");
                $(".triplesDisplay").html(tripleString);
                $(".triple_count").html(encodedTriples.length);
                $('#payload')[0].value = tripleString;
            }
        );
    });
}

var tripleGetterYielder;
function getTriples(rows, callback) {
    tripleGetterYielder = new Yielder();
    var triples = [];
    function isValidID(id) {
        if ($.isArray(id))
            id = id[0];
        return id !== undefined && $.trim(id) !== "";
    }
    function getID(entity) {
        if (entity.id === "None")
            return "$entity" + entity['/rec_ui/id'];
        return entity.id;
    }
    function cvtObject(cvt) {
        var result = {};
        var props = cvt['/rec_ui/cvt_props'];
        var empty = true;
        for (var i = 0; i < props.length; i++){
            var predicate = props[i];
            if (isValueProperty(predicate)) {
                var value = cvt[predicate];
                if (value){
                    result[predicate] = value
                    empty = false;
                }
            }
            else {
                var id = getID(cvt[predicate]);
                if (id){
                    result[predicate] = id;
                    empty = false;
                }
            }
        }
        if (empty)
            return undefined;
        return result;
    }
    politeEach(entities, function(_,subject) {
        if (!subject || !isValidID(subject.id) || subject['/rec_ui/is_cvt'])
            return;
        $.each($.makeArray(subject['/type/object/type']), function(_, type){
            triples.push({s:getID(subject), p:"/type/object/type",o:type});
        });
        if (subject.id === "None"){
            $.each($.makeArray(subject["/type/object/name"]), function(_, name) {
                if (name)
                    triples.push({s:getID(subject),p:"/type/object/name",o:name});
            });
        }

        var mqlProps = unique($.map(subject['/rec_ui/mql_props'], function(val){return val.split(":")[0]}));
        $.each(mqlProps, function(_, predicate) {

            $.each($.makeArray(subject[predicate]), function(_, object) {
                if (isValueProperty(predicate)) {
                    triples.push({s:getID(subject), p:predicate, o:object});
                    return;
                }

                if (object['/rec_ui/is_cvt']){
                    if (!object['/rec_ui/parent'] === subject)
                        return; //only create cvt once, from the 'root' of the parent
                    var cvtTripleObject = cvtObject(object);
                    if (cvtTripleObject)
                        triples.push({s:getID(subject),p:predicate,o:cvtTripleObject});
                }

                if  (!isValidID(object.id))
                    return;

                triples.push({s:getID(subject),p:predicate,o:getID(object)});
            })
        });
    }, function() {callback(triples)}, tripleGetterYielder);
}

function checkLogin() {
    $(".uploadLogin").hide();
    $(".uploadForm").hide();
    var response = $.get("http://data.labs.freebase.com/freeq/spreadsheet/");
    $.ajax({
        url:"http://data.labs.freebase.com/freeq/spreadsheet/",
        type:"GET",
        complete:function(response){
            if (!response || !response.status){
                error(response);
                return;
            }
            if (response.status === 200){
                $(".uploadLogin").hide();
                $(".uploadForm").show();
            }
            else if (response.status === 401){
                $(".uploadLogin").show();
                $(".uploadForm").hide();
            }
            else
                error(response);
        }})
}
<commit_msg>Unqualified property names in CVTs<commit_after>// ========================================================================
// Copyright (c) 2008-2009, Metaweb Technologies, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB
// TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// ========================================================================

/*
**  Rendering the spreadsheet back to the user
*/

function onDisplayOutputScreen() {
    setTimeout(checkLogin,0);
    setTimeout(renderSpreadsheet,0);
    setTimeout(prepareTriples,0);
}
function onHideOutputScreen() {
    if (spreadsheetRendererYielder)
        spreadsheetRendererYielder.cancel();
    if (tripleGetterYielder)
        tripleGetterYielder.cancel();
    $("#outputSpreadSheet")[0].value = "";
}

function encodeLine(arr) {
    var values = [];
    for(var i = 0; i < headers.length; i++){
        var val = arr[i];
        if (typeof val == "undefined")
            values.push("");
        else if (!val.match(/(\t|\"|\n)/))
            values.push(arr[i])
        else {
            val = val.replace(/"/g, '""');
            values.push('"' + val + '"');
        }
    }
    return values.join("\t");
}

//Like getChainedProperty, only it preserves array placement
function getChainedPropertyPreservingPlace(entity, prop) {
    var slots = [entity];
    $.each(prop.split(":"), function(_,part) {
        var newSlots = [];
        $.each(slots, function(_,slot) {
            if (!slot || !slot[part])
                newSlots.push(undefined);
            else
                newSlots = newSlots.concat($.makeArray(slot && slot[part]))
        })
        slots = newSlots;
    });
    if (slots === []) return undefined;
    return slots;
}

function encodeRow(row) {
    var lines = [[]];
    for (var i = 0; i < headers.length; i++){
        var val = getChainedPropertyPreservingPlace(row, headers[i]);
        if ($.isArray(val)) {
            for (var j = 0; j < val.length; j++) {
                if (lines[j] == undefined) lines[j] = [];
                lines[j][i] = textValue(val[j]);
            }
        }
        else
            lines[0][i] = textValue(val);
    }
    return $.map(lines,encodeLine);
}

var spreadsheetRendererYielder;
function renderSpreadsheet() {
    spreadsheetRendererYielder = new Yielder();
    var lines = [];
    lines.push(encodeLine(headers));
    $("#outputSpreadSheet")[0].value = "One moment, rendering...";

    politeEach(rows, function(idx, row) {
        lines = lines.concat(encodeRow(row));
    },
    function() {
        $("#outputSpreadSheet")[0].value = lines.join("\n");
    }, spreadsheetRendererYielder);
}

function prepareTriples() {
    getTriples(rows, function(triples) {
        politeMap(triples,function(_,val){return JSON.stringify(val)},
            function(encodedTriples) {
                var tripleString = encodedTriples.join("\n");
                $(".triplesDisplay").html(tripleString);
                $(".triple_count").html(encodedTriples.length);
                $('#payload')[0].value = tripleString;
            }
        );
    });
}

var tripleGetterYielder;
function getTriples(rows, callback) {
    tripleGetterYielder = new Yielder();
    var triples = [];
    function isValidID(id) {
        if ($.isArray(id))
            id = id[0];
        return id !== undefined && $.trim(id) !== "";
    }
    function getID(entity) {
        if (entity.id === "None")
            return "$entity" + entity['/rec_ui/id'];
        return entity.id;
    }
    function cvtObject(cvt) {
        var result = {};
        var props = cvt['/rec_ui/cvt_props'];
        var empty = true;
        var type = $.makeArray(cvt['/type/object/type'])[0];
        for (var i = 0; i < props.length; i++){
            var predicate = props[i];
            if (predicate.indexOf(type) != 0){
                warn("bad predicate " + predicate + " in CVT with type" + type);
                continue;
            }
            var value = cvt[predicate];
            var outputPredicate = predicate.replace(type + "/","");
            if (isValueProperty(predicate)) {
                if (value){
                    result[outputPredicate] = value
                    empty = false;
                }
            }
            else {
                var id = getID(value);
                if (id){
                    result[outputPredicate] = id;
                    empty = false;
                }
            }
        }
        if (empty)
            return undefined;
        return result;
    }
    politeEach(entities, function(_,subject) {
        if (!subject || !isValidID(subject.id) || subject['/rec_ui/is_cvt'])
            return;
        $.each($.makeArray(subject['/type/object/type']), function(_, type){
            triples.push({s:getID(subject), p:"/type/object/type",o:type});
        });
        if (subject.id === "None"){
            $.each($.makeArray(subject["/type/object/name"]), function(_, name) {
                if (name)
                    triples.push({s:getID(subject),p:"/type/object/name",o:name});
            });
        }

        var mqlProps = unique($.map(subject['/rec_ui/mql_props'], function(val){return val.split(":")[0]}));
        $.each(mqlProps, function(_, predicate) {

            $.each($.makeArray(subject[predicate]), function(_, object) {
                if (isValueProperty(predicate)) {
                    triples.push({s:getID(subject), p:predicate, o:object});
                    return;
                }

                if (object['/rec_ui/is_cvt']){
                    if (!object['/rec_ui/parent'] === subject)
                        return; //only create cvt once, from the 'root' of the parent
                    var cvtTripleObject = cvtObject(object);
                    if (cvtTripleObject)
                        triples.push({s:getID(subject),p:predicate,o:cvtTripleObject});
                }

                if  (!isValidID(object.id))
                    return;

                triples.push({s:getID(subject),p:predicate,o:getID(object)});
            })
        });
    }, function() {callback(triples)}, tripleGetterYielder);
}

function checkLogin() {
    $(".uploadLogin").hide();
    $(".uploadForm").hide();
    var response = $.get("http://data.labs.freebase.com/freeq/spreadsheet/");
    $.ajax({
        url:"http://data.labs.freebase.com/freeq/spreadsheet/",
        type:"GET",
        complete:function(response){
            if (!response || !response.status){
                error(response);
                return;
            }
            if (response.status === 200){
                $(".uploadLogin").hide();
                $(".uploadForm").show();
            }
            else if (response.status === 401){
                $(".uploadLogin").show();
                $(".uploadForm").hide();
            }
            else
                error(response);
        }})
}
<|endoftext|>


<commit_before>/*
 * node-pandoc
 *
 * This is the main, and currently only, file. It wraps the `pandoc` command
 * using node's child_process module. Since we still have to support node 0.4.x
 * (latest stable) we have to use spawn instead of fork().
 */

var spawn = require('child_process').spawn;

// The global command line args for pandocs.
var globalArgs = {
  //what the user provided
  provided: null,

  //whether to persist between convert() calls
  persist: false,

  //resets back to defaults
  reset: function() {
    this.provided = null;
    this.persist = false;
  }
};

/*
 * type is the input markup's type
 *
 * input is the input markup
 *
 * types is an array of markup types to convert to or a single type as a string
 *
 * callback will be passed an object mapping markup type to markup, unless
 * there was an error in which case it gets passed (null, statusCode)
 */
exports.convert = function(type, input, types, callback) {
  if(!type || typeof type !== 'string') {
    throw 'Invalid source markup type: must be a string.';
  }

  if(!input || typeof input !== 'string') {
    throw 'Invalid markup type: must be a string.';
  }

  if(typeof types !== 'string' && !Array.isArray(types)) {
    throw 'Invalid destination types: must be a string or an array of strings.';
  }

  if(types.length <= 0) {
    throw 'No destination types provided (empty array).';
  }

  if(typeof callback !== 'function') {
    if(callback) {
      throw 'Invalid callback provided: must be a function.';
    }

    console.log('Warning: no callback function passed to pandoc.convert().');
  }

  //what we're going to send to the callback if there are no pandoc errors
  var res = {};
  res[type] = input;

  var targetResponses = types.length;
  var numResponses = 0;

  if(typeof types === 'string') {
    types = [ types ];
  }

  for(var i in types) {
    if(typeof types[i] !== 'string') {
      throw 'Invalid destination type provided: non-string value found in array.';
    }

    /*
     * This if-block filters out the target markup type because we already set
     * it on the res object.
     */
    if(!res[types[i]]) {
      var args = globalArgs.provided || [];
      args.push('-f', type, '-t', types[i]);

      var pandoc = spawn('pandoc', args);

      //so that we have the target type in scope on('data') - love ya some asynch
      pandoc.stdout.targetType = types[i];

      pandoc.stdout.on('data', function(data) {
        //data will be a binary stream if you don't cast it to a string
        res[this.targetType] = data + '';
      });

      pandoc.on('exit', function(code, signal) {
        console.log('pandoc just exited with code ' + code + ' and signal ' + signal);

        numResponses++;

        if(typeof callback === 'function') {
          if(code !== 0) {
            callback(null, code);
          }
          else if(numResponses === targetResponses) {
            callback(res);
          }
        }
      });

      //pipe them the input
      pandoc.stdin.write(input, 'utf8');
      pandoc.stdin.end();

      if(!globalArgs.persist) {
        globalArgs.reset();
      }
    }
  }
};

/*
 * args is an array of command line arguments that should be passed to pandoc
 * on the next call. If set to a non-array value, then default args will be
 * used. The default behavior is that they will be thrown away before the next
 * call.
 *
 * persist is a boolean that when set to true will persist the provided args
 * for future calls.
 *
 * Returns this module so you can chain this funciton with convert().
 */
exports.args = function(args, persist) {
  if(Array.isArray(args)) {
    globalArgs.provided = args;
    globalArgs.persist = persist;
  }
  else {
    globalArgs.reset();
  }

  return exports;
};
<commit_msg>Requiring a callback.<commit_after>/*
 * node-pandoc
 *
 * This is the main, and currently only, file. It wraps the `pandoc` command
 * using node's child_process module. Since we still have to support node 0.4.x
 * (latest stable) we have to use spawn instead of fork().
 */

var spawn = require('child_process').spawn;

// The global command line args for pandocs.
var globalArgs = {
  //what the user provided
  provided: null,

  //whether to persist between convert() calls
  persist: false,

  //resets back to defaults
  reset: function() {
    this.provided = null;
    this.persist = false;
  }
};

/*
 * type is the input markup's type
 *
 * input is the input markup
 *
 * types is an array of markup types to convert to or a single type as a string
 *
 * callback will be passed an object mapping markup type to markup, unless
 * there was an error in which case it gets passed (null, statusCode)
 */
exports.convert = function(type, input, types, callback) {
  if(!type || typeof type !== 'string') {
    throw 'Invalid source markup type: must be a string.';
  }

  if(!input || typeof input !== 'string') {
    throw 'Invalid markup type: must be a string.';
  }

  if(typeof types !== 'string' && !Array.isArray(types)) {
    throw 'Invalid destination types: must be a string or an array of strings.';
  }

  if(types.length <= 0) {
    throw 'No destination types provided (empty array).';
  }

  if(typeof callback !== 'function') {
    if(callback) {
      throw 'Invalid callback provided: must be a function.';
    }
    else {
      throw 'No callback provided: must be a function.';
    }
  }

  //what we're going to send to the callback if there are no pandoc errors
  var res = {};
  res[type] = input;

  var targetResponses = types.length;
  var numResponses = 0;

  if(typeof types === 'string') {
    types = [ types ];
  }

  for(var i in types) {
    if(typeof types[i] !== 'string') {
      throw 'Invalid destination type provided: non-string value found in array.';
    }

    /*
     * This if-block filters out the target markup type because we already set
     * it on the res object.
     */
    if(!res[types[i]]) {
      var args = globalArgs.provided || [];
      args.push('-f', type, '-t', types[i]);

      var pandoc = spawn('pandoc', args);

      //so that we have the target type in scope on('data') - love ya some asynch
      pandoc.stdout.targetType = types[i];

      pandoc.stdout.on('data', function(data) {
        //data will be a binary stream if you don't cast it to a string
        res[this.targetType] = data + '';
      });

      pandoc.on('exit', function(code, signal) {
        numResponses++;

        if(code !== 0) {
          callback(null, code);
        }
        else if(numResponses === targetResponses) {
          callback(res);
        }
      });

      //pipe them the input
      pandoc.stdin.write(input, 'utf8');
      pandoc.stdin.end();

      if(!globalArgs.persist) {
        globalArgs.reset();
      }
    }
  }
};

/*
 * args is an array of command line arguments that should be passed to pandoc
 * on the next call. If set to a non-array value, then default args will be
 * used. The default behavior is that they will be thrown away before the next
 * call.
 *
 * persist is a boolean that when set to true will persist the provided args
 * for future calls.
 *
 * Returns this module so you can chain this funciton with convert().
 */
exports.args = function(args, persist) {
  if(Array.isArray(args)) {
    globalArgs.provided = args;
    globalArgs.persist = persist;
  }
  else {
    globalArgs.reset();
  }

  return exports;
};
<|endoftext|>


<commit_before>'use strict';

var uuid  = require('node-uuid'),
    log   = require('winston'),
    db    = require('larvitdb'),
    async = require('async');

class Order {
  constructor(rows) {
    this.uuid = uuid.v4();
    this.created = new Date();
    this.rows = rows;

    log.info('OrderModel: New Order - Creating Order with uuid: ' + this.uuid);
    let i = 0;
    while(this.rows[i] !== undefined) {
      this.rows[i].set('uuid', uuid.v4());
      i++;
    }
  }

  // Gets all order fields.
  getOrderFields(cb) {
    var order = this;
    log.info('OrderModel: getOrderFields() - Getting existing order fields');
    db.query('SELECT * FROM orders_orderFields', function(err, fields) {
      let result = new Set();
      let i = 0;
      while(fields[i] !== undefined) {
        result.add(fields[i].name);
        i++;
      }
      cb(err, result);
    });
  }

  // Adds order field to the order object.
  addOrderField(key, value) {
    this[key] = value;
  }

  // Creates order fields if not already exists in the "orders_orderFields" table.
  createOrderField(fieldname, fieldvalue, cb) {
    var order = this;
    log.info('OrderModel: createOrderField() - Creating order field: ' + fieldname);
    db.query('INSERT IGNORE INTO orders_orderFields (name) VALUE(?)', [fieldname], function(err, data) {
      if (err) {
        throw err;
      } else {
        order.insertOrderFieldValue(fieldname, fieldvalue);
        cb(data);
      }
    });
  }

  // Inserts order field values to the "orders_orders_fields" table.
  insertOrderFieldValue(fieldname, fieldvalue) {
    var order = this;
    db.query('SELECT * FROM orders_orderFields WHERE name = ?', [fieldname], function(err, result) {
      log.info('OrderModel: insertOrderFieldValue() - Writing order field value: ' + fieldname + ' => ' + fieldvalue);
      db.query('INSERT INTO orders_orders_fields (orderUuid, fieldId, fieldValue) VALUE(?, ?, ?)', [order.uuid, result[0].id, fieldvalue], function(err, data) {
        if (err) {
          throw err;
        }
      });
    });
  }

  // Creates the order i the "orders" table.
  insertOrder(cb) {
    var order = this;

    log.info('OrderModel: insertOrder() - Writing order: ' + order.uuid);
    db.query('INSERT INTO orders (uuid, created) VALUE(?, ?)', [order.uuid, order.created], function(err, data) {
      if (err) {
        throw err;
      }
      cb(data);
    });

  };

  // Saving the order object to the database.
  save(cb) {
    var order = this,
        tasks = new Array();

    tasks.push(function(cb) {
      order.insertOrder(function(result) {
        cb(null, result);
      });
    });

    tasks.push(function(cb) {
      order.getOrderFields(function(err, fields) {
        var subtasks = new Array();

        var createSubtask = function(key, value) {
          subtasks.push(function(cb) {
            order.createOrderField(key, value, function(result) {
              cb(null, result);
            });
          });
        };

        for (var key in order) {
          if (
            key !== 'uuid' &&
            key !== 'rows' &&
            key !== 'created'
          ) {
            createSubtask(key, order[key]);
          }
        }

        async.series(subtasks, function(err, result) {
          cb(result);
        });

      });
    });

    async.series(tasks, function(err,result) {
      console.log(result);
    });
  }
}

exports = module.exports = Order;
<commit_msg>started on row-adding<commit_after>'use strict';

var uuid  = require('node-uuid'),
    log   = require('winston'),
    db    = require('larvitdb'),
    async = require('async');

class Order {
  constructor(rows) {
    this.uuid = uuid.v4();
    this.created = new Date();
    this.rows = rows;

    log.info('OrderModel: New Order - Creating Order with uuid: ' + this.uuid);
    let i = 0;
    while(this.rows[i] !== undefined) {
      this.rows[i].set('uuid', uuid.v4());
      i++;
    }
  }

  // Gets all order fields.
  getOrderFields(cb) {
    var order = this;
    log.info('OrderModel: getOrderFields() - Getting existing order fields');
    db.query('SELECT * FROM orders_orderFields', function(err, fields) {
      let result = new Set();
      let i = 0;
      while(fields[i] !== undefined) {
        result.add(fields[i].name);
        i++;
      }
      cb(err, result);
    });
  }

  // Adds order field to the order object.
  addOrderField(key, value) {
    this[key] = value;
  }

  // Creates order fields if not already exists in the "orders_orderFields" table.
  createOrderField(fieldname, fieldvalue, cb) {
    var order = this;
    log.info('OrderModel: createOrderField() - Creating order field: ' + fieldname);
    db.query('INSERT IGNORE INTO orders_orderFields (name) VALUE(?)', [fieldname], function(err, data) {
      if (err) {
        throw err;
      } else {
        order.insertOrderFieldValue(fieldname, fieldvalue);
        cb(data);
      }
    });
  }

  // Inserts order field values to the "orders_orders_fields" table.
  insertOrderFieldValue(fieldname, fieldvalue) {
    var order = this;
    db.query('SELECT * FROM orders_orderFields WHERE name = ?', [fieldname], function(err, result) {
      log.info('OrderModel: insertOrderFieldValue() - Writing order field value: ' + fieldname + ' => ' + fieldvalue);
      db.query('INSERT INTO orders_orders_fields (orderUuid, fieldId, fieldValue) VALUE(?, ?, ?)', [order.uuid, result[0].id, fieldvalue], function(err, data) {
        if (err) {
          throw err;
        }
      });
    });
  }

  // Creates row fields if not already exists in the "orders_rowFields" table.
  createRowField(fieldname, fieldvalue, cb) {
    var order = this;
    log.info('OrderModel: createRowField() - Creating row field: ' + fieldname);
    db.query('INSERT IGNORE INTO orders_rowFields (name) VALUE(?)', [fieldname], function(err, data) {
      if (err) {
        throw err;
      } else {
        order.insertRowFieldValue(fieldname, fieldvalue);
        cb(data);
      }
    });
  }

  // Inserts row field values to the "orders_rows_fields" table.
  insertRowFieldValue(fieldname, fieldvalue) {
    var order = this;
    db.query('SELECT * FROM orders_rowFields WHERE name = ?', [fieldname], function(err, result) {
      log.info('OrderModel: insertRowFieldValue() - Writing row field value: ' + fieldname + ' => ' + fieldvalue);
      db.query('INSERT INTO orders_rows_fields (rowUuid, rowFieldUuid, rowIntValue, rowStrValue) VALUE(?, ?, ?)', [order.uuid, result[0].id, null, fieldvalue], function(err, data) {
        if (err) {
          throw err;
        }
      });
    });
  }

  // Creates the order i the "orders" table.
  insertOrder(cb) {
    var order = this;

    log.info('OrderModel: insertOrder() - Writing order: ' + order.uuid);
    db.query('INSERT INTO orders (uuid, created) VALUE(?, ?)', [order.uuid, order.created], function(err, data) {
      if (err) {
        throw err;
      }
      cb(data);
    });
  }

  // Saving the order object to the database.
  save(cb) {
    var order = this,
        tasks = new Array();

    tasks.push(function(cb) {
      order.insertOrder(function(result) {
        cb(null, result);
      });
    });

    tasks.push(function(cb) {
      order.getOrderFields(function(err, fields) {
        var subtasks = new Array();

        var createSubtask = function(key, value) {
          subtasks.push(function(cb) {
            order.createOrderField(key, value, function(result) {
              cb(null, result);
            });
          });
        };

        for (var key in order) {
          if (
            key !== 'uuid' &&
            key !== 'rows' &&
            key !== 'created'
          ) {
            createSubtask(key, order[key]);
          }
        }

        async.series(subtasks, function(err, result) {
          cb(result);
        });

      });
    });

    async.series(tasks, function(err,result) {
      console.log(result);
    });
  }
}

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


<commit_before>"use strict";

var clone = require('clone');
var compile = require('es6-templates').compile;
var extend = require('extend');
var fs = require('fs');
var isarray = require('isarray');
var join = require('path').join;
var dirname = require('path').dirname;

// -----------------------------------------------------------------------------
// Configuration.
var defaults = {
  base: '/',
  target: 'es6',
  indent: 2,
  useRelativePaths: false,
  removeLineBreaks: false,
  templateExtension: '.html',
  templateFunction: false,
  templateProcessor: defaultProcessor,
  styleProcessor: defaultProcessor
};

function defaultProcessor(path, file) {
  return file;
}

var htmlOptions = function (opts) {
  return {
    type: 'html',
    prop_url: 'templateUrl',
    prop: 'template',
    start_pattern: /templateUrl.*/,
    end_pattern: new RegExp('.*\\' + opts.templateExtension + '\s*(\'\\)|\')|.*\\' + opts.templateExtension + '\s*("\\)|")'),
    oneliner_pattern: new RegExp('templateUrl.*(\\' + opts.templateExtension + '\s*(\'\\)|\')|\\' + opts.templateExtension + 's*("\\)|"))')
  };
};

var cssOptions = function () {
  return {
    type: 'css',
    prop_url: 'styleUrls',
    prop: 'styles',
    start_pattern: /styleUrls.*/,
    end_pattern: /.*]/,
    oneliner_pattern: /styleUrls(.*?)]/
  };
};

module.exports = function parser(file, options) {
  var opts = extend({}, defaults, (options || {}));
  var lines = file.contents.toString().replace(/\r/g, '').split('\n');
  var start_line_idx, end_line_idx, frag;
  var HTML = false;
  var CSS = false;

  if (opts.templateProcessor) {
    HTML = true;
    extend(opts, htmlOptions(opts));
    execute();
    reset();
  }
  if (opts.styleProcessor) {
    CSS = true;
    extend(opts, cssOptions());
    execute();
    reset();
  }

  return lines.join('\n');

  function execute() {
    for(var i = 0; i < lines.length; i++) {
      var line = lines[i];
      getIndexes(line, i);
      if (i === end_line_idx && start_line_idx) {
        getFragment();
        replaceFrag();
      }
    }
  }

  function getIndexes(line, i) {
      if (opts.start_pattern.test(line)) {
        start_line_idx = i;
      }
      if (opts.end_pattern.test(line)) {
        // Match end pattern without start.
        // end_line_idx is till equal to previous loop turn value.
        if (start_line_idx <= end_line_idx) return;
        end_line_idx = i;
      }
  }

  function getFragment() {
    var fragStart, fragEnd;
    if (start_line_idx < 0 || end_line_idx < 0) return;
    // One liner.
    if (start_line_idx === end_line_idx) {
      frag = opts.oneliner_pattern.exec(lines[start_line_idx])[0];
    }
    // One or more lines.
    if (start_line_idx < end_line_idx) {
      fragStart = opts.start_pattern.exec(lines[start_line_idx])[0];
      fragEnd   = opts.end_pattern.exec(lines[end_line_idx])[0];
      frag      = concatLines();
    }

    console.log(frag);

    function concatLines() {
      var _lines = clone(lines);
      _lines[start_line_idx] = fragStart;
      _lines[end_line_idx]   = fragEnd;
      return _lines.splice(start_line_idx, end_line_idx - start_line_idx + 1).join('');
    }
  }

  function replaceFrag() {
    var _urls;
    var fnIndex = frag.indexOf('(');
    if (fnIndex > -1 && opts.templateFunction) {
      // Using template function.
      _urls = opts.templateFunction(/'(.*)'/.exec(frag)[1]);
    } else {
      _urls = eval('({' + frag + '})')[opts.prop_url];
    }

    console.log(_urls);

    var urls  = isarray(_urls) ? _urls : [_urls];
    var line  = lines[start_line_idx];
    var indentation = /^\s*/.exec(line)[0];
    var assetFiles  = '';
    var startOfInsertionBlock = '\n';
    var endOfInsertionBlock = '\n';

    urls.forEach(function (url) {
      var file = getFile(url);
      var ext = /\.[0-9a-z]+$/i.exec(url);
      if (HTML && opts.templateProcessor) {
        file = opts.templateProcessor(ext, file);
      }
      if (CSS && opts.styleProcessor) {
        file = opts.styleProcessor(ext, file);
      }
      assetFiles += file;
    });

    // Trim trailing line breaks.
    assetFiles = assetFiles.replace(/(\n*)$/, '');

    // We don't need indentation if we are going to insert it as one line
    if(!opts.removeLineBreaks) {
      // Indent content.
      assetFiles = indent(assetFiles);
    }

    if(opts.removeLineBreaks) {
      assetFiles = removeLineBreaks(assetFiles);
      // don't need the indentation
      indentation = '';
      startOfInsertionBlock = '';
      endOfInsertionBlock = '';
    }

    // Build the final string.
    if ('html' === opts.type)
      assetFiles = opts.prop + ': `' + startOfInsertionBlock + assetFiles + endOfInsertionBlock + indentation + '`';
    if ('css' === opts.type)
      assetFiles = opts.prop + ': [`' + startOfInsertionBlock + assetFiles + endOfInsertionBlock + indentation + '`]';
    if ('es5' === opts.target) assetFiles = compile(assetFiles).code;

    // One liner.
    if (start_line_idx === end_line_idx) {
      lines[start_line_idx] = line.replace(opts.oneliner_pattern, assetFiles);
    }
    // One or more lines.
    if (start_line_idx < end_line_idx) {
      if (/(,)$/.test(lines[end_line_idx])) assetFiles += ',';
      lines[start_line_idx] = line.replace(opts.start_pattern, assetFiles);
      lines.splice(start_line_idx + 1, end_line_idx - start_line_idx);
    }

    function getFile(filepath) {
      var absPath = opts.useRelativePaths ? join(dirname(file.path), filepath)
                                          : join(process.cwd(), opts.base, filepath);

      return fs.readFileSync(absPath)
        .toString()
        .replace(/\r/g, '')
        .replace(/[\u200B-\u200D\uFEFF]/g, '');
    }

    function indent(str) {
      var lines = [];
      var spaces = '';
      for (var i = 0; i < indentation.length + opts.indent; i++) { spaces += ' '; }
      str.split('\n').forEach(function (line) {
        // Add indentation spaces only to non-empty lines.
        lines.push((/^(\s*)$/.test(line) ? '' : spaces) + line);
      });
      return lines.join('\n');
    }

    function removeLineBreaks(str) {
      return str.replace(/(\r\n|\n|\r)/gm," ");
    }
  }

  function reset() {
    start_line_idx = undefined;
    end_line_idx = undefined;
    frag = undefined;
    HTML = false;
    CSS = false;
  }
};
<commit_msg>chore: clean up<commit_after>"use strict";

var clone = require('clone');
var compile = require('es6-templates').compile;
var extend = require('extend');
var fs = require('fs');
var isarray = require('isarray');
var join = require('path').join;
var dirname = require('path').dirname;

// -----------------------------------------------------------------------------
// Configuration.
var defaults = {
  base: '/',
  target: 'es6',
  indent: 2,
  useRelativePaths: false,
  removeLineBreaks: false,
  templateExtension: '.html',
  templateFunction: false,
  templateProcessor: defaultProcessor,
  styleProcessor: defaultProcessor
};

function defaultProcessor(path, file) {
  return file;
}

var htmlOptions = function (opts) {
  return {
    type: 'html',
    prop_url: 'templateUrl',
    prop: 'template',
    start_pattern: /templateUrl.*/,
    end_pattern: new RegExp('.*\\' + opts.templateExtension + '\s*(\'\\)|\')|.*\\' + opts.templateExtension + '\s*("\\)|")'),
    oneliner_pattern: new RegExp('templateUrl.*(\\' + opts.templateExtension + '\s*(\'\\)|\')|\\' + opts.templateExtension + 's*("\\)|"))')
  };
};

var cssOptions = function () {
  return {
    type: 'css',
    prop_url: 'styleUrls',
    prop: 'styles',
    start_pattern: /styleUrls.*/,
    end_pattern: /.*]/,
    oneliner_pattern: /styleUrls(.*?)]/
  };
};

module.exports = function parser(file, options) {
  var opts = extend({}, defaults, (options || {}));
  var lines = file.contents.toString().replace(/\r/g, '').split('\n');
  var start_line_idx, end_line_idx, frag;
  var HTML = false;
  var CSS = false;

  if (opts.templateProcessor) {
    HTML = true;
    extend(opts, htmlOptions(opts));
    execute();
    reset();
  }
  if (opts.styleProcessor) {
    CSS = true;
    extend(opts, cssOptions());
    execute();
    reset();
  }

  return lines.join('\n');

  function execute() {
    for(var i = 0; i < lines.length; i++) {
      var line = lines[i];
      getIndexes(line, i);
      if (i === end_line_idx && start_line_idx) {
        getFragment();
        replaceFrag();
      }
    }
  }

  function getIndexes(line, i) {
      if (opts.start_pattern.test(line)) {
        start_line_idx = i;
      }
      if (opts.end_pattern.test(line)) {
        // Match end pattern without start.
        // end_line_idx is till equal to previous loop turn value.
        if (start_line_idx <= end_line_idx) return;
        end_line_idx = i;
      }
  }

  function getFragment() {
    var fragStart, fragEnd;
    if (start_line_idx < 0 || end_line_idx < 0) return;
    // One liner.
    if (start_line_idx === end_line_idx) {
      frag = opts.oneliner_pattern.exec(lines[start_line_idx])[0];
    }
    // One or more lines.
    if (start_line_idx < end_line_idx) {
      fragStart = opts.start_pattern.exec(lines[start_line_idx])[0];
      fragEnd   = opts.end_pattern.exec(lines[end_line_idx])[0];
      frag      = concatLines();
    }

    function concatLines() {
      var _lines = clone(lines);
      _lines[start_line_idx] = fragStart;
      _lines[end_line_idx]   = fragEnd;
      return _lines.splice(start_line_idx, end_line_idx - start_line_idx + 1).join('');
    }
  }

  function replaceFrag() {
    var _urls;
    var fnIndex = frag.indexOf('(');
    if (fnIndex > -1 && opts.templateFunction) {
      // Using template function.
      _urls = opts.templateFunction(/'(.*)'/.exec(frag)[1]);
    } else {
      _urls = eval('({' + frag + '})')[opts.prop_url];
    }

    var urls  = isarray(_urls) ? _urls : [_urls];
    var line  = lines[start_line_idx];
    var indentation = /^\s*/.exec(line)[0];
    var assetFiles  = '';
    var startOfInsertionBlock = '\n';
    var endOfInsertionBlock = '\n';

    urls.forEach(function (url) {
      var file = getFile(url);
      var ext = /\.[0-9a-z]+$/i.exec(url);
      if (HTML && opts.templateProcessor) {
        file = opts.templateProcessor(ext, file);
      }
      if (CSS && opts.styleProcessor) {
        file = opts.styleProcessor(ext, file);
      }
      assetFiles += file;
    });

    // Trim trailing line breaks.
    assetFiles = assetFiles.replace(/(\n*)$/, '');

    // We don't need indentation if we are going to insert it as one line
    if(!opts.removeLineBreaks) {
      // Indent content.
      assetFiles = indent(assetFiles);
    }

    if(opts.removeLineBreaks) {
      assetFiles = removeLineBreaks(assetFiles);
      // don't need the indentation
      indentation = '';
      startOfInsertionBlock = '';
      endOfInsertionBlock = '';
    }

    // Build the final string.
    if ('html' === opts.type)
      assetFiles = opts.prop + ': `' + startOfInsertionBlock + assetFiles + endOfInsertionBlock + indentation + '`';
    if ('css' === opts.type)
      assetFiles = opts.prop + ': [`' + startOfInsertionBlock + assetFiles + endOfInsertionBlock + indentation + '`]';
    if ('es5' === opts.target) assetFiles = compile(assetFiles).code;

    // One liner.
    if (start_line_idx === end_line_idx) {
      lines[start_line_idx] = line.replace(opts.oneliner_pattern, assetFiles);
    }
    // One or more lines.
    if (start_line_idx < end_line_idx) {
      if (/(,)$/.test(lines[end_line_idx])) assetFiles += ',';
      lines[start_line_idx] = line.replace(opts.start_pattern, assetFiles);
      lines.splice(start_line_idx + 1, end_line_idx - start_line_idx);
    }

    function getFile(filepath) {
      var absPath = opts.useRelativePaths ? join(dirname(file.path), filepath)
                                          : join(process.cwd(), opts.base, filepath);

      return fs.readFileSync(absPath)
        .toString()
        .replace(/\r/g, '')
        .replace(/[\u200B-\u200D\uFEFF]/g, '');
    }

    function indent(str) {
      var lines = [];
      var spaces = '';
      for (var i = 0; i < indentation.length + opts.indent; i++) { spaces += ' '; }
      str.split('\n').forEach(function (line) {
        // Add indentation spaces only to non-empty lines.
        lines.push((/^(\s*)$/.test(line) ? '' : spaces) + line);
      });
      return lines.join('\n');
    }

    function removeLineBreaks(str) {
      return str.replace(/(\r\n|\n|\r)/gm," ");
    }
  }

  function reset() {
    start_line_idx = undefined;
    end_line_idx = undefined;
    frag = undefined;
    HTML = false;
    CSS = false;
  }
};
<|endoftext|>