<commit_before>/* jshint node: true */
/* global describe, beforeEach, afterEach, afterAll, it, jasmine, expect */
'use strict';

var participants = require('../service/participants');
var pg = require('pg');

describe('payment validation journey', function () {
    var client;
    var loggedInClient;
    var paceUrl = process.env.PACE_URL || 'http://localhost:3000/';
    var paymentValidationUrl = paceUrl + 'payment_validation';
    var originalTimeout;

    var setupDbConnection = function(done) {
        var connectionString = process.env.SNAP_DB_PG_URL || process.env.DATABASE_URL || 'tcp://vagrant@localhost/pace';
        var jasmineDone = done;

        pg.connect(connectionString, function (err, client, done) {
                if (err) {
                    console.error('DB connection problem: ', err);
                    done();
                    jasmineDone();
                } else {
                    var query = client.query('delete from participants');
                    query.on('end', function () {
                        done();
                        jasmineDone();
                    });
                    query.on('error', function (error) {
                        console.error('DB statement problem: ', error);
                        done();
                        jasmineDone();
                    });
                }
            }
        );
    };

    beforeEach(function (done) {
        var webdriverio = require('webdriverio');
        var options = {
            desiredCapabilities: {
                browserName: 'phantomjs'
            }
        };

        client = webdriverio
            .remote(options);
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

        setupDbConnection(done);

        loggedInClient = client.init()
            .url(paceUrl + 'login')
            .setValue('input#username', 'admin')
            .setValue('input#password', 'admin')
            .click('button#submit');
    });

    afterEach(function() {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });

    afterAll(function (done) {
        pg.end();
        done();
    });

    it('redirects to the login page for unauthenticated users', function () {
        client.init()
            .url(paymentValidationUrl)
            .isVisible('form#loginForm')
            .then(function (isVisible) {
                expect(isVisible).toBe(true);
            })
            .end();
    });

    it('displays an error message for an invalid token', function (done) {
        var invalidToken = 'invalid';
        loggedInClient.url(paymentValidationUrl)
            .setValue('input#payment-token', invalidToken)
            .click('button#submit-token')
            .isVisible('form#payment-details')
            .then(function (isVisible) {
                expect(isVisible).toBe(false);
            })
            .getText('div.error')
            .then(function (errorMessage) {
                expect(errorMessage).toBe('Es konnte keine Registrierung mit Token ' + invalidToken + ' gefunden werden.');
                done();
            })
            .end();
    });

    it('allows to confirm a participant once she has payed', function (done) {
        var aParticipant = {
            firstname: 'Friedrich',
            lastname: 'Schiller',
            email: 'f.schiller@example.com',
        };
        var aToken = '23eF67i';

        participants.save(aParticipant, aToken)
            .then(function() {
                loggedInClient.url(paymentValidationUrl)
                    .setValue('input#payment-token', aToken)
                    .click('button#submit-token')
                    .isVisible('form#payment-details')
                    .then(function (isVisible) {
                        expect(isVisible).toBe(true);
                    })
                    .getText('p#details')
                    .then(function(text) {
                        expect(text).toContain('Betrag für Token ' + aToken + ':');
                    })
                    .click('button#confirm-registration')
                    .getText('div.success')
                    .then(function (text) {
                        expect(text).toBe('Der Teilnehmer wurde bestätigt');
                        done();
                    })
                    .end();
            });
    });

    it('should show pending payments', function (done) {
        var aParticipant = {
            firstname: 'Friedrich',
            lastname: 'Schiller',
            email: 'f.schiller@example.com',
        };
        var aToken = '23eF67i';

        participants.save(aParticipant, aToken)
            .then(function() {
              loggedInClient.url(paymentValidationUrl)
                .then(function (isVisible) {
                    expect(isVisible).toBe(true);
                })
                .getText('ul#pending')
                .then(function(text) {
                    expect(text).toContain('Token: ' + aToken + ':');
                })
                .end();
            });
    });

});
<commit_msg>Fixing the test<commit_after>/* jshint node: true */
/* global describe, beforeEach, afterEach, afterAll, it, jasmine, expect */
'use strict';

var participants = require('../service/participants');
var pg = require('pg');

describe('payment validation journey', function () {
    var client;
    var loggedInClient;
    var paceUrl = process.env.PACE_URL || 'http://localhost:3000/';
    var paymentValidationUrl = paceUrl + 'payment_validation';
    var originalTimeout;

    var setupDbConnection = function(done) {
        var connectionString = process.env.SNAP_DB_PG_URL || process.env.DATABASE_URL || 'tcp://vagrant@localhost/pace';
        var jasmineDone = done;

        pg.connect(connectionString, function (err, client, done) {
                if (err) {
                    console.error('DB connection problem: ', err);
                    done();
                    jasmineDone();
                } else {
                    var query = client.query('delete from participants');
                    query.on('end', function () {
                        done();
                        jasmineDone();
                    });
                    query.on('error', function (error) {
                        console.error('DB statement problem: ', error);
                        done();
                        jasmineDone();
                    });
                }
            }
        );
    };

    beforeEach(function (done) {
        var webdriverio = require('webdriverio');
        var options = {
            desiredCapabilities: {
                browserName: 'phantomjs'
            }
        };

        client = webdriverio
            .remote(options);
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

        setupDbConnection(done);

        loggedInClient = client.init()
            .url(paceUrl + 'login')
            .setValue('input#username', 'admin')
            .setValue('input#password', 'admin')
            .click('button#submit');
    });

    afterEach(function() {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });

    afterAll(function (done) {
        pg.end();
        done();
    });

    it('redirects to the login page for unauthenticated users', function () {
        client.init()
            .url(paymentValidationUrl)
            .isVisible('form#loginForm')
            .then(function (isVisible) {
                expect(isVisible).toBe(true);
            })
            .end();
    });

    it('displays an error message for an invalid token', function (done) {
        var invalidToken = 'invalid';
        loggedInClient.url(paymentValidationUrl)
            .setValue('input#payment-token', invalidToken)
            .click('button#submit-token')
            .isVisible('form#payment-details')
            .then(function (isVisible) {
                expect(isVisible).toBe(false);
            })
            .getText('div.error')
            .then(function (errorMessage) {
                expect(errorMessage).toBe('Es konnte keine Registrierung mit Token ' + invalidToken + ' gefunden werden.');
                done();
            })
            .end();
    });

    it('allows to confirm a participant once she has payed', function (done) {
        var aParticipant = {
            firstname: 'Friedrich',
            lastname: 'Schiller',
            email: 'f.schiller@example.com'
        };
        var aToken = '23eF67i';

        participants.save(aParticipant, aToken)
            .then(function() {
                loggedInClient.url(paymentValidationUrl)
                    .setValue('input#payment-token', aToken)
                    .click('button#submit-token')
                    .isVisible('form#payment-details')
                    .then(function (isVisible) {
                        expect(isVisible).toBe(true);
                    })
                    .getText('p#details')
                    .then(function(text) {
                        expect(text).toContain('Betrag für Token ' + aToken + ':');
                    })
                    .click('button#confirm-registration')
                    .getText('div.success')
                    .then(function (text) {
                        expect(text).toBe('Der Teilnehmer wurde bestätigt');
                        done();
                    })
                    .end();
            });
    });

    it('should show pending payments', function (done) {
        var aParticipant = {
            firstname: 'Friedrich',
            lastname: 'Schiller',
            email: 'f.schiller@example.com'
        };
        var aToken = '23eF67i';

        participants.save(aParticipant, aToken)
            .then(function() {
              loggedInClient.url(paymentValidationUrl)
                .isVisible('ul#pending')
                .then(function (isVisible) {
                    expect(isVisible).toBe(true);
                })
                .getText('ul#pending')
                .then(function(text) {
                    expect(text).toMatch(/.*Token: 23eF67i$/);
                    done();
                })
                .end();
            });
    });

});
<|endoftext|>


<commit_before>var pictureSource; // picture source
var destinationType; // sets the format of returned value
var pictureFiles = [];

// device APIs are available
//
window.onload = function(){
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
}

// get Photo from Album
//
function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source
    });
}

function onPhotoURISuccess(imageURI) {
    jQuery("p#pics").prepend("");
    pictureFiles.push(imageURI);
}

function captureSuccess(mediaFiles) {
    var i, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        pPath = mediaFiles[i].fullPath;

        pictureFiles.push(mediaFiles[i]);
        jQuery("p#pics").prepend("");
    }
}

function uploadFiles() {
    var j, leng;

    mesLen = pictureFiles.length;

    for (j = 0, leng = pictureFiles.length; j < leng; j += 1) {
        uploadFile(pictureFiles[j]);
        jQuery("p#pics img:first-child").remove();
    }
    pictureFiles = [];

    if(mesLen>0) {
        setTimeout("alert(\"Es werden "+mesLen+" Bilder hochgeladen\")", 500);
    }
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture up to 2 images
    navigator.device.capture.captureImage(captureSuccess, captureError,{limit: 1});
    alert(pictureSource);
    alert(destinationType);
}

// Upload files to server
function uploadFile(mediaFile) {

    var ft = new FileTransfer(),
    path = mediaFile.fullPath,
    name = mediaFile.name;

    ft.upload(path,
        "http://ids-services.at/ma-test/upload.php",
        function(result) {
            console.log('Upload success: ' + result.responseCode);
            console.log(result.bytesSent + ' bytes sent');
        },
        function(error) {
            console.log('Error uploading file ' + path + ': ' + error.code);
        },
        {
            fileName: name
        });
}

function deleteImage(){
    jQuery("p#pics img:first-child").remove();
    pictureFiles.pop();
}

function onFail(message) {
  alert('Fehlgeschlagen: ' + message);
}<commit_msg>Capture Image<commit_after>var pictureSource; // picture source
var destinationType; // sets the format of returned value
var pictureFiles = [];

// device APIs are available
//
/*
window.onload = function(){
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
}
*/

// get Photo from Album
//
function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source
    });
}

function onPhotoURISuccess(imageURI) {
    jQuery("p#pics").prepend("");
    pictureFiles.push(imageURI);
}

function captureSuccess(mediaFiles) {
    var i, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        pPath = mediaFiles[i].fullPath;

        pictureFiles.push(mediaFiles[i]);
        jQuery("p#pics").prepend("");
    }
}

function uploadFiles() {
    var j, leng;

    mesLen = pictureFiles.length;

    for (j = 0, leng = pictureFiles.length; j < leng; j += 1) {
        uploadFile(pictureFiles[j]);
        jQuery("p#pics img:first-child").remove();
    }
    pictureFiles = [];

    if(mesLen>0) {
        setTimeout("alert(\"Es werden "+mesLen+" Bilder hochgeladen\")", 500);
    }
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture up to 2 images
    navigator.device.capture.captureImage(captureSuccess, captureError,{limit: 1});
}

// Upload files to server
function uploadFile(mediaFile) {

    var ft = new FileTransfer(),
    path = mediaFile.fullPath,
    name = mediaFile.name;

    ft.upload(path,
        "http://ids-services.at/ma-test/upload.php",
        function(result) {
            console.log('Upload success: ' + result.responseCode);
            console.log(result.bytesSent + ' bytes sent');
        },
        function(error) {
            console.log('Error uploading file ' + path + ': ' + error.code);
        },
        {
            fileName: name
        });
}

function deleteImage(){
    jQuery("p#pics img:first-child").remove();
    pictureFiles.pop();
}

function onFail(message) {
  alert('Fehlgeschlagen: ' + message);
}<|endoftext|>


<commit_before>db.node.createIndex( { nodeId: 1, siteId: 1, language: 1, version: 1 }, { unique: true } )
db.system.js.save(
    {
        _id : 'duplicateNode' ,
        value : function (data){
            var node = null
            var statusCursor = db.status.find( { _id: ObjectId(data.statusId) });
            if (statusCursor.hasNext()) {
	            var status = statusCursor.next()
	            while (1) {
	                var nodeCursor = db.node.find( { nodeId: data.nodeId, siteId: data.siteId, language: data.language }).sort( { version: -1 } ).limit(1);
	                node = nodeCursor.next()
	                delete node._id;
	                node.version = node.version + 1;
	                node.status = status;
	                var results = db.node.insert(node);
	                if( results.hasWriteError() ) {
	                    if( results.getWriteError().code == 11000)
	                        continue;
	                    else
	                        print( 'unexpected error inserting data: ' + tojson( results ) );
	                }
	                break;
	            }
            }
            return node;
        }
    }
);<commit_msg>suppress while (1)<commit_after>db.node.createIndex( { nodeId: 1, siteId: 1, language: 1, version: 1 }, { unique: true } )
db.system.js.save(
    {
        _id : 'duplicateNode' ,
        value : function (data){
            var node = null
            var statusCursor = db.status.find( { _id: ObjectId(data.statusId) });
            if (statusCursor.hasNext()) {
	            var status = statusCursor.next();
	            var count = 0;
	            while (count < 10) {
	                var nodeCursor = db.node.find( { nodeId: data.nodeId, siteId: data.siteId, language: data.language }).sort( { version: -1 } ).limit(1);
	                node = nodeCursor.next()
	                delete node._id;
	                node.version = node.version + 1;
	                node.status = status;
	                var results = db.node.insert(node);
	                if( results.hasWriteError() ) {
	                    if( results.getWriteError().code == 11000) {
	                        count++;
	                        continue;
	                    }
	                    else
	                        print( 'unexpected error inserting data: ' + tojson( results ) );
	                }
	                break;
	            }
            }
            return node;
        }
    }
);<|endoftext|>


<commit_before>jQuery(document).ready(function($){

	//	Module handling
	//---------------------------------------------------------------------
	const animationSpeed = 200;
	var modules = $('.module');
	var module = modules.first();

	modules.hide();
	module.fadeIn(animationSpeed);

	$('.module-trigger').click(function() {
		doModuleSwap($(this).data('target'));
	});

	function doModuleSwap(target) {
		module.fadeOut(animationSpeed, function() {
			if (target) {
				module = $('.' + target);
				module.fadeIn(animationSpeed);
			}
			else {
				module = module.next(); //TODO what if no next?
				module.fadeIn(animationSpeed);
			}
		});
	}

	//	Quiz data structure
	//---------------------------------------------------------------------
	var quizzes = {};

	chrome.storage.local.get('quizzes', function (result) {
		if (Object.keys(result['quizzes']).length > 0) {
			quizzes = result['quizzes'];
			updateQuizList();
		}
	});

	function storeData() {
		chrome.storage.local.set({'quizzes': quizzes}, function() {});
	}

	function Quiz(id, name) {
		this.id = id;
		this.name = name;
		this.questions = [new Question()];
	}

	function Question() {
		this.title = 'Title';
		this.content = 'Content goes here';
		this.answers = ['Answer A', 'Answer B'];
	}

	var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	function generateQuizId() { //TODO need to check if exists
		var id = '';
		for (var i=0; i < 4; i++)
			 id += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
		return id;
	}

	//	Intro
	//---------------------------------------------------------------------
	function swapToModule_intro() { //wrapper function
		updateQuizList();
	}

	function updateQuizList() {
		$('.quiz-list div:not(:last-child)').remove();
		for (quizID in quizzes) {
			$('.create-quiz').before('
'
				+ quizzes[quizID].name + '
');
		}
		bindQuizListClick();
	}

	function bindQuizListClick() { //because DOM elements does not exists yet
		$('.white-box:not(:last-child)').click(function () { //TODO change name to something more fitting
			doModuleSwap('microbit-connect'); //TODO rename to moduleSwap()
			currentQuiz = quizzes[$(this).data('quiz')];
			log($(this).data('quiz'));
			log(quizzes);
			currentQuestionIndex = 0;
			attemptConnection();
		});
		$('.edit-quiz').click(function () {
			prepareModule_Edit(quizzes[$(this).parent().data('quiz')]);
		});
	}

	$('.create-quiz-button').click(function () {
		var newQuiz = new Quiz(generateQuizId(), $('#quiz-title').text());
		quizzes[generateQuizId()] = newQuiz;
		prepareModule_Edit(newQuiz);
	});

	//	Edit mode //TODO change names of edit mode to just 'edit'
	//---------------------------------------------------------------------
	var currentQuiz;
	var currentQuestionIndex = 0;

	function prepareModule_Edit(quiz) { //TODO use one function instead with a function as a parameter, called specifically for every module's needs
		currentQuiz = quiz;
		$('.edit-mode .name').text(currentQuiz.name);
		loadQuestion(0);
		doModuleSwap('edit-mode'); //TODO create jquery variables of modules instead of string identifier
	}

	function loadQuestion(q) {
		currentQuestionIndex = q;
		q = currentQuiz.questions[q];
		$('.edit-mode .title').text(q.title);
		$('.edit-mode .content').text(q.content);
		$('.question li:not(:last-child)').remove();
		for (var i = 0; i < q.answers.length; i++) { //TODO jquery for each?
			$('.question ul').prepend('
' + alphabet.charAt(i)
				+''
				+q.answers[i]+'
');
		}
	}

	function storeQuestion() { //TODO maybe saveQuestion instead?
		var q = currentQuiz.questions[currentQuestionIndex];
		q.title = $('.edit-mode .title').text();
		q.content = $('.edit-mode .content').text();
		var answers = [];
		$('.answer').each(function () {
			answers.push($(this).text());
		});
		q.answers = answers;
	}

	$('.exit-edit').click(function () {
		storeQuestion();
		storeData();
		updateQuizList(); // this will be called 'swap module intro'
	});

	var startOpacity = 0; //TODO get rid of drag and drop behavior
	$('.answers :not(:last-child)').draggable({
		start : function (event, ui) {
			startOpacity = $(this).css('opacity');
			log(startOpacity);
			$(this).css({opacity:0.4});
		},
		stop : function (event, ui) {
			$(this).css({opacity:startOpacity});
		},
		cursor : 'move',
		revert : true,
		revertDuration : 200,
		zIndex : 98
	});

	$('.delete').droppable({
		drop : function (event, ui) {
			ui.draggable.fadeTo(200, 0.01, function () {
				$(this).remove();
			});
		}
	});

	//TODO split into appropriate files
	//	Microbit connect
	//---------------------------------------------------------------------

	function ab2str(buf) {
		return String.fromCharCode.apply(null, new Uint8Array(buf));
	}

	function str2ab(str) {
	  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
	  var bufView = new Uint8Array(buf);
	  for (var i=0, strLen=str.length; i<strLen; i++) {
	    bufView[i] = str.charCodeAt(i);
	  }
	  return buf;
	}

	function attemptConnection() { //check if connection already has been made
		if (!connectionId)
			chrome.serial.getDevices(getDevices);
	}

	var connectionId;
	var getDevices = function(ports) {
		for (var i = 0; i < ports.length; i++) {
			var pathName = ports[i].path;
			var portName = ports[i].displayName;
			if ((portName == 'mbed Serial Port') || (portName == 'MBED CMSIS_DAP' && pathName.indexOf("tty") >= 0)) { //for windows and os x
				chrome.serial.connect(pathName, {bitrate: 115200}, onConnect);
				return;
			}
		}
		log("didn't find microbit :'( ");
	};

	function getCode(i) {
		return 'set:'+currentQuiz.id+':1:'+currentQuiz.questions[currentQuestionIndex].answers.length+';';

	}

	var onConnect = function(connectionInfo) { //TODO need to do disconnect on app exit
		connectionId = connectionInfo.connectionId;
		send(getCode(1), function() {}); //response from microbit will trigger loading of quiz
	}

	function send(str, callback) { //wrapper function

		chrome.serial.send(connectionId, str2ab(str), callback);
	}

	var stringReceived = '';
	var onReceiveCallback = function(info) { //receives data from serial in chunks
	    if (info.connectionId == connectionId && info.data) {
	      var str = ab2str(info.data);

	      if (str.charAt(str.length-1) === '\n') {
	        stringReceived += str.substring(0, str.length-1);
	        onLineReceived(stringReceived);
	        stringReceived = '';
	      }

	      else {
	        stringReceived += str;
	        if (str.indexOf(';')) //end of message
	        	parseMessage(stringReceived);
	        	stringReceived = '';
	      }
	    }
	};

	chrome.serial.onReceive.addListener(onReceiveCallback);

	function parseMessage(msg) { //or controller
		log('msg');
		log(msg);
		if (msg.substring(0,3) == 'ans') { //received answer from micro:bit
			var str = msg.split(':');
			if (str[1] == currentQuiz.id && str[2] == currentQuestionIndex) {
				if (!str[3] in responses) {
					responses[str[3]] = str[4];
					send('ack'+msg.substring(2,msg.length+1));
				}
			}
		}
		else if (msg.substring(0,3) == 'nxt') { //micro:bit controller asking for previous
			advanceQuiz();
		}
		else if (msg.substring(0,3) == 'ack') { //micro:bit start verification received
			prepareQuiz();
		}
	}

	var responses = {};

	//	Quiz!
	//---------------------------------------------------------------------
	function prepareQuiz() {
		var q = currentQuiz.questions[currentQuestionIndex];
		$('.quiz .title').text(q.title); //todo have a template and store jquery vars in the beginning of script
											// so that there are only one reference to the same object (instead of having
											// to look it up every single time)
		$('.quiz .content').text(q.content); //todo this could be the same html and so as the edit-mode thing
		$('.quiz ul li').remove();

		for (var i = 0; i < q.answers.length; i++) { //TODO jquery for each?
			$('.quiz ul').append('
' + alphabet.charAt(i)
				+''
				+q.answers[i]+'
');
		}

		doModuleSwap('quiz');
	}

	function advanceQuiz() {
		//increase current question index OR display results
	}

});

function log(message) {
	console.log(message);
}
<commit_msg>Cleared out old jQuery based interface code<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Defines the DATA message type used in the OTR protocol.
 *
 * @author rcc@google.com (Ryan Chan)
 */

goog.provide('e2e.otr.message.Data');

goog.require('e2e');
goog.require('e2e.cipher.DiffieHellman');
goog.require('e2e.hash.Sha1');
goog.require('e2e.otr');
goog.require('e2e.otr.Data');
goog.require('e2e.otr.Mpi');
goog.require('e2e.otr.constants');
goog.require('e2e.otr.constants.MessageType');
goog.require('e2e.otr.error.InvalidArgumentsError');
goog.require('e2e.otr.error.NotImplementedError');
goog.require('e2e.otr.message.Encoded');
goog.require('e2e.otr.message.handler');
goog.require('e2e.otr.util.Iterator');
goog.require('e2e.otr.util.Tee');
goog.require('e2e.otr.util.aes128ctr');
goog.require('goog.array');
goog.require('goog.crypt.Hmac');

goog.scope(function() {

var constants = e2e.otr.constants;
var MSGSTATE = constants.MSGSTATE;

/**
 * An OTRv3 DATA message.
 * @constructor
 * @extends {e2e.otr.message.Encoded}
 * @param {!e2e.otr.Session} session The enclosing session.
 * @param {string} plaintext The plaintext portion of the message.
 * @param {!Array.<e2e.otr.message.Tlv>=} opt_tlvs 0+ TLV records to include.
 * @param {number=} opt_flags The flags to set on the message.
 */
e2e.otr.message.Data = function(session, plaintext, opt_tlvs, opt_flags) {
  goog.base(this, session);

  if (plaintext.indexOf('\0') > -1) {
    throw new e2e.otr.error.InvalidArgumentsError(
        'Plaintext may not contain \\0');
  }

  this.plaintext_ = plaintext;
  this.tlvs_ = opt_tlvs || [];
  this.flags_ = new Uint8Array([0x00 | opt_flags]);
};
goog.inherits(e2e.otr.message.Data, e2e.otr.message.Encoded);

/**
 * Specifies the type of the message.
 * @type {!e2e.otr.Byte}
 */
e2e.otr.message.Data.MESSAGE_TYPE = constants.MessageType.DATA;

/**
 * Generates the keys used for AES and SHA1-HMAC of data messages.
 * @param {!e2e.cipher.DiffieHellman} localDh The DH of the local key component.
 * @param {!e2e.ByteArray} remoteKey The remote key component.
 * @return {!{sendingAes: !e2e.ByteArray, receivingAes: !e2e.ByteArray,
 *     sendingMac: !e2e.ByteArray, receivingMac: !e2e.ByteArray}}
 */
e2e.otr.message.Data.computeKeys = function(localDh, remoteKey) {
  var highEnd = e2e.otr.compareByteArray(localDh.generate(), remoteKey) > 0;
  var sendbyte = highEnd ? 0x01 : 0x02;
  var recvbyte = highEnd ? 0x02 : 0x01;
  var secret = localDh.generate(remoteKey);
  var secbytes = new e2e.otr.Mpi(new Uint8Array(secret)).serialize();

  /**
   * h1 function as defined in OTR spec.
   * @param {number} b The input byte.
   * @return {!e2e.ByteArray} The 160-bit output of the SHA-1 hash of the
   *     (5+len) bytes consisting of the byte b, followed by secbytes.
   */
  var h1 = function(b) {
    return new e2e.hash.Sha1().hash([b].concat(secbytes));
  };

  var sendingAes = h1(sendbyte).slice(0, 16);
  var receivingAes = h1(recvbyte).slice(0, 16);

  return {
    sendingAes: sendingAes,
    sendingMac: new e2e.hash.Sha1().hash(sendingAes),
    receivingAes: receivingAes,
    receivingMac: new e2e.hash.Sha1().hash(receivingAes)
  };
};

/**
 * Serialize the DATA message into a Uint8Array.
 * @return {!Uint8Array} The serialized DATA message.
 */
e2e.otr.message.Data.prototype.serializeMessageContent = function() {
  var ctrTop = e2e.incrementByteArray(this.session_.sendCtr);
  var remoteKey = this.session_.keymanager.getRemoteKey();
  var dh = this.session_.keymanager.getKey();

  var message = e2e.otr.serializeBytes([
    e2e.stringToByteArray(this.plaintext_),
    [0x00] // NULL BYTE
  ].concat(this.tlvs_));

  var keys = e2e.otr.message.Data.computeKeys(dh.key, remoteKey.key);

  var encryptedMessage = e2e.otr.util.aes128ctr.encrypt(keys.sendingAes,
      message, ctrTop.concat(goog.array.repeat(0, 8)));

  var nextDh = new e2e.cipher.DiffieHellman(constants.DH_MODULUS,
      [constants.DH_GENERATOR]);
  this.session_.keymanager.storeKey(nextDh);

  var partialData = e2e.otr.serializeBytes([
    this.flags_,
    dh.keyid,
    remoteKey.keyid,
    nextDh.generate(),
    ctrTop,
    new e2e.otr.Data(new Uint8Array(encryptedMessage))
  ]);

  var mac = new goog.crypt.Hmac(new e2e.hash.Sha1(), keys.sendingMac).getHmac(
      this.addHeader(partialData));

  // TODO(rcc): old MAC keys to be revealed.
  var oldMacKeys = [];

  return e2e.otr.serializeBytes([partialData, mac, oldMacKeys]);
};

/**
 * Processes a DATA message message.
 * @param {!e2e.otr.Session} session The enclosing session.
 * @param {!Uint8Array} data The data to be processed.
 */
e2e.otr.message.Data.process = function(session, data) {
  switch (session.getMsgState()) {
    case MSGSTATE.ENCRYPTED:
      var tee = new e2e.otr.util.Tee();
      var iter = new e2e.otr.util.Iterator(data);

      var flags = e2e.otr.byteToNum(tee.tee(iter.next()));
      var ignoreUnreadable = flags & 0x01;
      var remoteKeyid = tee.tee(iter.next(4));
      var keyid = tee.tee(iter.next(4));
      var nextDh = e2e.otr.Mpi.parse(tee.tee(iter.nextEncoded())).serialize();
      var ctrTop = Array.apply([], tee.tee(iter.next(8)));
      var encryptedMessage = e2e.otr.Data.parse(tee.tee(iter.nextEncoded()))
          .deconstruct();
      var mac = iter.next(20);

      var key = session.keymanager.getKey(keyid);
      var remoteKey = session.keymanager.getRemoteKey(remoteKeyid);
      var keys = e2e.otr.message.Data.computeKeys(key.key, remoteKey.key);

      var macData = e2e.otr.message.Encoded.addHeader(session,
          constants.MessageType.DATA, tee.dump(), true);
      var calculatedMac = new goog.crypt.Hmac(new e2e.hash.Sha1(),
          keys.receivingMac).getHmac(macData);

      if (e2e.otr.compareByteArray(mac, calculatedMac)) {
        if (!ignoreUnreadable) {
          // TODO(rcc): Log the error and/or warn the user. Remove extra return.
          return;
        }
        return;
      }

      session.keymanager.storeRemoteKey(e2e.incrementByteArray(Array.apply([],
          remoteKeyid)));

      var message = e2e.otr.util.aes128ctr.decrypt(keys.receivingAes,
          encryptedMessage, ctrTop.concat(goog.array.repeat(0, 8)));

      var split = Array.prototype.indexOf.call(message, '\0');
      session.display(e2e.byteArrayToString(message.subarray(0, split)));
      // TODO(rcc): Process TLVs.
      break;

    case MSGSTATE.PLAINTEXT:
    case MSGSTATE.FINISHED:
      // TODO(rcc): Inform the user that an unreadable encrypted message was
      // received, and reply with an Error Message.
      throw new e2e.otr.error.NotImplementedError('Not yet implemented.');
      break;

    default:
      e2e.otr.assertState(false, 'Invalid message state.');
  }
};

e2e.otr.message.handler.add(e2e.otr.message.Data);
});  // goog.scope
<commit_msg>OTR data message wrap DH parameter in MPI before serialization<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Defines the DATA message type used in the OTR protocol.
 *
 * @author rcc@google.com (Ryan Chan)
 */

goog.provide('e2e.otr.message.Data');

goog.require('e2e');
goog.require('e2e.cipher.DiffieHellman');
goog.require('e2e.hash.Sha1');
goog.require('e2e.otr');
goog.require('e2e.otr.Data');
goog.require('e2e.otr.Mpi');
goog.require('e2e.otr.constants');
goog.require('e2e.otr.constants.MessageType');
goog.require('e2e.otr.error.InvalidArgumentsError');
goog.require('e2e.otr.error.NotImplementedError');
goog.require('e2e.otr.message.Encoded');
goog.require('e2e.otr.message.handler');
goog.require('e2e.otr.util.Iterator');
goog.require('e2e.otr.util.Tee');
goog.require('e2e.otr.util.aes128ctr');
goog.require('goog.array');
goog.require('goog.crypt.Hmac');

goog.scope(function() {

var constants = e2e.otr.constants;
var MSGSTATE = constants.MSGSTATE;

/**
 * An OTRv3 DATA message.
 * @constructor
 * @extends {e2e.otr.message.Encoded}
 * @param {!e2e.otr.Session} session The enclosing session.
 * @param {string} plaintext The plaintext portion of the message.
 * @param {!Array.<e2e.otr.message.Tlv>=} opt_tlvs 0+ TLV records to include.
 * @param {number=} opt_flags The flags to set on the message.
 */
e2e.otr.message.Data = function(session, plaintext, opt_tlvs, opt_flags) {
  goog.base(this, session);

  if (plaintext.indexOf('\0') > -1) {
    throw new e2e.otr.error.InvalidArgumentsError(
        'Plaintext may not contain \\0');
  }

  this.plaintext_ = plaintext;
  this.tlvs_ = opt_tlvs || [];
  this.flags_ = new Uint8Array([0x00 | opt_flags]);
};
goog.inherits(e2e.otr.message.Data, e2e.otr.message.Encoded);

/**
 * Specifies the type of the message.
 * @type {!e2e.otr.Byte}
 */
e2e.otr.message.Data.MESSAGE_TYPE = constants.MessageType.DATA;

/**
 * Generates the keys used for AES and SHA1-HMAC of data messages.
 * @param {!e2e.cipher.DiffieHellman} localDh The DH of the local key component.
 * @param {!e2e.ByteArray} remoteKey The remote key component.
 * @return {!{sendingAes: !e2e.ByteArray, receivingAes: !e2e.ByteArray,
 *     sendingMac: !e2e.ByteArray, receivingMac: !e2e.ByteArray}}
 */
e2e.otr.message.Data.computeKeys = function(localDh, remoteKey) {
  var highEnd = e2e.otr.compareByteArray(localDh.generate(), remoteKey) > 0;
  var sendbyte = highEnd ? 0x01 : 0x02;
  var recvbyte = highEnd ? 0x02 : 0x01;
  var secret = localDh.generate(remoteKey);
  var secbytes = new e2e.otr.Mpi(new Uint8Array(secret)).serialize();

  /**
   * h1 function as defined in OTR spec.
   * @param {number} b The input byte.
   * @return {!e2e.ByteArray} The 160-bit output of the SHA-1 hash of the
   *     (5+len) bytes consisting of the byte b, followed by secbytes.
   */
  var h1 = function(b) {
    return new e2e.hash.Sha1().hash([b].concat(secbytes));
  };

  var sendingAes = h1(sendbyte).slice(0, 16);
  var receivingAes = h1(recvbyte).slice(0, 16);

  return {
    sendingAes: sendingAes,
    sendingMac: new e2e.hash.Sha1().hash(sendingAes),
    receivingAes: receivingAes,
    receivingMac: new e2e.hash.Sha1().hash(receivingAes)
  };
};

/**
 * Serialize the DATA message into a Uint8Array.
 * @return {!Uint8Array} The serialized DATA message.
 */
e2e.otr.message.Data.prototype.serializeMessageContent = function() {
  var ctrTop = e2e.incrementByteArray(this.session_.sendCtr);
  var remoteKey = this.session_.keymanager.getRemoteKey();
  var dh = this.session_.keymanager.getKey();

  var message = e2e.otr.serializeBytes([
    e2e.stringToByteArray(this.plaintext_),
    [0x00] // NULL BYTE
  ].concat(this.tlvs_));

  var keys = e2e.otr.message.Data.computeKeys(dh.key, remoteKey.key);

  var encryptedMessage = e2e.otr.util.aes128ctr.encrypt(keys.sendingAes,
      message, ctrTop.concat(goog.array.repeat(0, 8)));

  var nextDh = new e2e.cipher.DiffieHellman(constants.DH_MODULUS,
      [constants.DH_GENERATOR]);
  this.session_.keymanager.storeKey(nextDh);

  var partialData = e2e.otr.serializeBytes([
    this.flags_,
    dh.keyid,
    remoteKey.keyid,
    new e2e.otr.Mpi(new Uint8Array(nextDh.generate())),
    ctrTop,
    new e2e.otr.Data(new Uint8Array(encryptedMessage))
  ]);

  var mac = new goog.crypt.Hmac(new e2e.hash.Sha1(), keys.sendingMac).getHmac(
      this.addHeader(partialData));

  // TODO(rcc): old MAC keys to be revealed.
  var oldMacKeys = [];

  return e2e.otr.serializeBytes([partialData, mac, oldMacKeys]);
};

/**
 * Processes a DATA message message.
 * @param {!e2e.otr.Session} session The enclosing session.
 * @param {!Uint8Array} data The data to be processed.
 */
e2e.otr.message.Data.process = function(session, data) {
  switch (session.getMsgState()) {
    case MSGSTATE.ENCRYPTED:
      var tee = new e2e.otr.util.Tee();
      var iter = new e2e.otr.util.Iterator(data);

      var flags = e2e.otr.byteToNum(tee.tee(iter.next()));
      var ignoreUnreadable = flags & 0x01;
      var remoteKeyid = tee.tee(iter.next(4));
      var keyid = tee.tee(iter.next(4));
      var nextDh = e2e.otr.Mpi.parse(tee.tee(iter.nextEncoded())).serialize();
      var ctrTop = Array.apply([], tee.tee(iter.next(8)));
      var encryptedMessage = e2e.otr.Data.parse(tee.tee(iter.nextEncoded()))
          .deconstruct();
      var mac = iter.next(20);

      var key = session.keymanager.getKey(keyid);
      var remoteKey = session.keymanager.getRemoteKey(remoteKeyid);
      var keys = e2e.otr.message.Data.computeKeys(key.key, remoteKey.key);

      var macData = e2e.otr.message.Encoded.addHeader(session,
          constants.MessageType.DATA, tee.dump(), true);
      var calculatedMac = new goog.crypt.Hmac(new e2e.hash.Sha1(),
          keys.receivingMac).getHmac(macData);

      if (e2e.otr.compareByteArray(mac, calculatedMac)) {
        if (!ignoreUnreadable) {
          // TODO(rcc): Log the error and/or warn the user. Remove extra return.
          return;
        }
        return;
      }

      session.keymanager.storeRemoteKey(e2e.incrementByteArray(Array.apply([],
          remoteKeyid)));

      var message = e2e.otr.util.aes128ctr.decrypt(keys.receivingAes,
          encryptedMessage, ctrTop.concat(goog.array.repeat(0, 8)));

      var split = Array.prototype.indexOf.call(message, '\0');
      session.display(e2e.byteArrayToString(message.subarray(0, split)));
      // TODO(rcc): Process TLVs.
      break;

    case MSGSTATE.PLAINTEXT:
    case MSGSTATE.FINISHED:
      // TODO(rcc): Inform the user that an unreadable encrypted message was
      // received, and reply with an Error Message.
      throw new e2e.otr.error.NotImplementedError('Not yet implemented.');
      break;

    default:
      e2e.otr.assertState(false, 'Invalid message state.');
  }
};

e2e.otr.message.handler.add(e2e.otr.message.Data);
});  // goog.scope
<|endoftext|>


<commit_before>/*
 * c_cpp_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Gastón Kleiman <gaston.kleiman AT gmail DOT com>
 *
 * Based on Bespin's C/C++ Syntax Plugin by Marc McIntyre.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

define("mode/c_cpp_highlight_rules", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var DocCommentHighlightRules = require("mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var TexHighlightRules = require("mode/tex_highlight_rules").TexHighlightRules;
var RHighlightRules = require("mode/r_highlight_rules").RHighlightRules;

var c_cppHighlightRules = function() {

   function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
   }

   var keywords = lang.arrayToMap([
      "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand",
       "bitor", "bool", "break", "case", "catch", "char", "char16_t",
       "char32_t", "class", "compl", "const", "constexpr",
       "const_cast", "continue", "decltype", "default", "delete",
       "do", "double", "dynamic_cast", "else", "enum", "explicit",
       "export", "extern", "false", "float", "for", "friend", "goto",
       "if", "inline", "int", "in", "long", "mutable", "namespace",
       "new", "noexcept", "not", "not_eq", "nullptr", "or", "or_eq",
       "private", "protected", "public", "register",
       "reinterpret_cast", "return", "short", "signed", "sizeof",
       "static", "static_assert", "static_cast", "struct", "switch",
       "template", "this", "thread_local", "throw", "true", "try",
       "typedef", "typeid", "typeof", "typename", "union", "unsigned",
       "using", "virtual", "void", "volatile", "wchar_t", "while",
       "xor", "xor_eq"
   ]);

   var preProcTokens = [
      "include", "pragma", "line", "define", "undef", "ifdef", "ifndef",
      "if", "else", "elif", "endif", "warning", "error"
   ];

   var buildinConstants = lang.arrayToMap(
      ("NULL").split("|")
   );

   var operatorTokens = [

      ">>=", "<<=", "new", "delete",

      "<<", ">>", "&&", "||", "==", "!=", "<=", ">=", "::",
      "*=", "+=", "-=", "/=", "++", "--", "<>", "&=", "^=",
      "%=", "->",

      "!", "$", "&", "|", "*", "-", "+", "~", "=", ">", "<"

   ];

   var reOperatorTokens = operatorTokens.map(function(x) {
      return escapeRegExp(x);
   }).join("|");

   var reOperator =
      [",", "()", "[]", "->*", "->"]
      .concat(operatorTokens)
      .map(function(x) {
         return escapeRegExp(x);
      });

   reOperator = ["new\\s*\\[\\]", "delete\\s*\\[\\]"].concat(reOperator);
   reOperator = "operator\\s*(?:" + reOperator.join("|") + ")|operator\\s+[\\w_]+";

   // regexp must not have capturing parentheses. Use (?:) instead.
   // regexps are ordered -> the first match is used

   this.$rules = {
      "start" : [
         {
            // Attributes
            token: "comment.doc.tag",
            regex: "\\/\\/\\s*\\[\\[.*\\]\\].*$"
         }, {
            // Roxygen
            token : "comment",
            regex : "\\/\\/'",
            next : "rd-start"
         }, {
            // Standard comment
            token : "comment",
            regex : "\\/\\/.*$"
         },
         DocCommentHighlightRules.getStartRule("doc-start"),
         {
            token : "comment", // multi line comment
            merge : true,
            regex : "\\/\\*",
            next : "comment"
         }, {
            token : "string", // single line
            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
         }, {
            token : "string", // multi line string start
            merge : true,
            regex : '["].*\\\\$',
            next : "qqstring"
         }, {
            token : "string", // single line
            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
         }, {
            token : "string", // multi line string start
            merge : true,
            regex : "['].*\\\\$",
            next : "qstring"
         }, {
            token : "constant.numeric", // hex
            regex : "0[xX][0-9a-fA-F]+\\b"
         }, {
            token : "constant.numeric", // binary literal
            regex : "0[bB][01']+\\b"
         }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(?:(?:[fF])|(?:(?:[uU]?(?:(?:l?l?)|(?:L?L?))?)|(?:(?:(?:l?l?)|(?:L?L?))[uU]?))|(?:_\\w+))?\\b"
         }, {
            token : "keyword.preproc",
            regex : "#\\s*include\\b",
            next : "include"
         }, {
            token : "keyword.preproc", // pre-compiler directives
            regex : "(?:" + preProcTokens.map(function(x) { return "#\\s*" + x + "\\b"; }).join("|") + ")"
         }, {
            token : "variable.language", // compiler-specific constructs
            regex : "\\b__\\S+__\\b"
         }, {
            token: "keyword",
            regex: reOperator
         }, {
            token : function(value) {
               if (value == "this")
                  return "variable.language";
               else if (keywords.hasOwnProperty(value))
                  return "keyword";
               else if (buildinConstants.hasOwnProperty(value))
                  return "constant.language";
               else
                  return "identifier";
            },
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
         }, {
            token : "keyword.operator",
            merge : false,
            regex : reOperatorTokens
         }, {
            token : "punctuation.operator",
            merge : false,
            regex : "\\?|\\:|\\,|\\;|\\.|\\\\"
         }, {
            // Obviously these are neither keywords nor operators, but
            // labelling them as such was the easiest way to get them
            // to be colored distinctly from regular text
            token : "paren.keyword.operator",
            merge : false,
            regex : "[[({<]"
         }, {
            // Obviously these are neither keywords nor operators, but
            // labelling them as such was the easiest way to get them
            // to be colored distinctly from regular text
            token : "paren.keyword.operator",
            merge : false,
            regex : "[\\])}>]"
         }, {
            token : "text",
            regex : "\\s+"
         }
      ],
      "comment" : [
         {
            token : "comment", // closing comment
            regex : ".*?\\*\\/",
            next : "start"
         }, {
            token : "comment", // comment spanning whole line
            merge : true,
            regex : ".+"
         }
      ],
      "qqstring" : [
         {
            token : "string",
            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
            next : "start"
         }, {
            token : "string",
            merge : true,
            regex : '.+'
         }
      ],
      "qstring" : [
         {
            token : "string",
            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
            next : "start"
         }, {
            token : "string",
            merge : true,
            regex : '.+'
         }
      ],
      "include" : [
         {
            token : "string", // <CONSTANT>
            regex : /<.+>/,
            next : "start"
         },
         {
            token : "string",
            regex : /\".+\"/,
            next : "start"
         }
      ]

   };

   var rdRules = new TexHighlightRules("comment").getRules();

   // Make all embedded TeX virtual-comment so they don't interfere with
   // auto-indent.
   for (var i = 0; i < rdRules["start"].length; i++) {
      rdRules["start"][i].token += ".virtual-comment";
   }

   this.addRules(rdRules, "rd-");
   this.$rules["rd-start"].unshift({
      token: "text",
      regex: "^",
      next: "start"
   });
   this.$rules["rd-start"].unshift({
      token : "keyword",
      regex : "@(?!@)[^ ]*"
   });
   this.$rules["rd-start"].unshift({
      token : "comment",
      regex : "@@"
   });
   this.$rules["rd-start"].push({
      token : "comment",
      regex : "[^%\\\\[({\\])}]+"
   });

   this.embedRules(DocCommentHighlightRules, "doc-",
                   [ DocCommentHighlightRules.getEndRule("start") ]);

   // Embed R syntax highlighting
   this.$rules["start"].unshift({
      token: "support.function.codebegin",
      regex: "^\\s*\\/\\*{3,}\\s*[Rr]\\s*$",
      next: "r-start"
   });

   var rRules = new RHighlightRules().getRules();
   this.addRules(rRules, "r-");
   this.$rules["r-start"].unshift({
      token: "support.function.codeend",
      regex: "\\*\\/",
      next: "start"
   });

};

oop.inherits(c_cppHighlightRules, TextHighlightRules);

exports.c_cppHighlightRules = c_cppHighlightRules;
});
<commit_msg>more highlighting of C++ operators<commit_after>/*
 * c_cpp_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Gastón Kleiman <gaston.kleiman AT gmail DOT com>
 *
 * Based on Bespin's C/C++ Syntax Plugin by Marc McIntyre.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

define("mode/c_cpp_highlight_rules", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var DocCommentHighlightRules = require("mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var TexHighlightRules = require("mode/tex_highlight_rules").TexHighlightRules;
var RHighlightRules = require("mode/r_highlight_rules").RHighlightRules;

var c_cppHighlightRules = function() {

   function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
   }

   var keywords = lang.arrayToMap([
      "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand",
       "bitor", "bool", "break", "case", "catch", "char", "char16_t",
       "char32_t", "class", "compl", "const", "constexpr",
       "const_cast", "continue", "decltype", "default", "delete",
       "do", "double", "dynamic_cast", "else", "enum", "explicit",
       "export", "extern", "false", "float", "for", "friend", "goto",
       "if", "inline", "int", "in", "long", "mutable", "namespace",
       "new", "noexcept", "not", "not_eq", "nullptr", "or", "or_eq",
       "private", "protected", "public", "register",
       "reinterpret_cast", "return", "short", "signed", "sizeof",
       "static", "static_assert", "static_cast", "struct", "switch",
       "template", "this", "thread_local", "throw", "true", "try",
       "typedef", "typeid", "typeof", "typename", "union", "unsigned",
       "using", "virtual", "void", "volatile", "wchar_t", "while",
       "xor", "xor_eq"
   ]);

   var preProcTokens = [
      "include", "pragma", "line", "define", "undef", "ifdef", "ifndef",
      "if", "else", "elif", "endif", "warning", "error"
   ];

   var buildinConstants = lang.arrayToMap(
      ("NULL").split("|")
   );

   var operatorTokens = [

      ">>=", "<<=", "new", "delete",

      "<<", ">>", "&&", "||", "==", "!=", "<=", ">=", "::",
      "*=", "+=", "-=", "/=", "++", "--", "<>", "&=", "^=",
      "%=", "->",

      "!", "$", "&", "|", "*", "-", "+", "~", "=", ">", "<",
      ";", ",", "?", ":", "."

   ];

   var reOperatorTokens = operatorTokens.map(function(x) {
      return escapeRegExp(x);
   }).join("|");

   var reOperator =
      [",", "()", "[]", "->*", "->"]
      .concat(operatorTokens)
      .map(function(x) {
         return escapeRegExp(x);
      });

   reOperator = ["new\\s*\\[\\]", "delete\\s*\\[\\]"].concat(reOperator);
   reOperator = "operator\\s*(?:" + reOperator.join("|") + ")|operator\\s+[\\w_]+";

   // regexp must not have capturing parentheses. Use (?:) instead.
   // regexps are ordered -> the first match is used

   this.$rules = {
      "start" : [
         {
            // Attributes
            token: "comment.doc.tag",
            regex: "\\/\\/\\s*\\[\\[.*\\]\\].*$"
         }, {
            // Roxygen
            token : "comment",
            regex : "\\/\\/'",
            next : "rd-start"
         }, {
            // Standard comment
            token : "comment",
            regex : "\\/\\/.*$"
         },
         DocCommentHighlightRules.getStartRule("doc-start"),
         {
            token : "comment", // multi line comment
            merge : true,
            regex : "\\/\\*",
            next : "comment"
         }, {
            token : "string", // single line
            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
         }, {
            token : "string", // multi line string start
            merge : true,
            regex : '["].*\\\\$',
            next : "qqstring"
         }, {
            token : "string", // single line
            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
         }, {
            token : "string", // multi line string start
            merge : true,
            regex : "['].*\\\\$",
            next : "qstring"
         }, {
            token : "constant.numeric", // hex
            regex : "0[xX][0-9a-fA-F]+\\b"
         }, {
            token : "constant.numeric", // binary literal
            regex : "0[bB][01']+\\b"
         }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(?:(?:[fF])|(?:(?:[uU]?(?:(?:l?l?)|(?:L?L?))?)|(?:(?:(?:l?l?)|(?:L?L?))[uU]?))|(?:_\\w+))?\\b"
         }, {
            token : "keyword.preproc",
            regex : "#\\s*include\\b",
            next : "include"
         }, {
            token : "keyword.preproc", // pre-compiler directives
            regex : "(?:" + preProcTokens.map(function(x) { return "#\\s*" + x + "\\b"; }).join("|") + ")"
         }, {
            token : "variable.language", // compiler-specific constructs
            regex : "\\b__\\S+__\\b"
         }, {
            token: "keyword",
            regex: reOperator
         }, {
            token : function(value) {
               if (value == "this")
                  return "variable.language";
               else if (keywords.hasOwnProperty(value))
                  return "keyword";
               else if (buildinConstants.hasOwnProperty(value))
                  return "constant.language";
               else
                  return "identifier";
            },
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
         }, {
            token : "keyword.operator",
            merge : false,
            regex : reOperatorTokens
         }, {
            token : "punctuation.operator",
            merge : false,
            regex : "\\?|\\:|\\,|\\;|\\.|\\\\"
         }, {
            // Obviously these are neither keywords nor operators, but
            // labelling them as such was the easiest way to get them
            // to be colored distinctly from regular text
            token : "paren.keyword.operator",
            merge : false,
            regex : "[[({<]"
         }, {
            // Obviously these are neither keywords nor operators, but
            // labelling them as such was the easiest way to get them
            // to be colored distinctly from regular text
            token : "paren.keyword.operator",
            merge : false,
            regex : "[\\])}>]"
         }, {
            token : "text",
            regex : "\\s+"
         }
      ],
      "comment" : [
         {
            token : "comment", // closing comment
            regex : ".*?\\*\\/",
            next : "start"
         }, {
            token : "comment", // comment spanning whole line
            merge : true,
            regex : ".+"
         }
      ],
      "qqstring" : [
         {
            token : "string",
            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
            next : "start"
         }, {
            token : "string",
            merge : true,
            regex : '.+'
         }
      ],
      "qstring" : [
         {
            token : "string",
            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
            next : "start"
         }, {
            token : "string",
            merge : true,
            regex : '.+'
         }
      ],
      "include" : [
         {
            token : "string", // <CONSTANT>
            regex : /<.+>/,
            next : "start"
         },
         {
            token : "string",
            regex : /\".+\"/,
            next : "start"
         }
      ]

   };

   var rdRules = new TexHighlightRules("comment").getRules();

   // Make all embedded TeX virtual-comment so they don't interfere with
   // auto-indent.
   for (var i = 0; i < rdRules["start"].length; i++) {
      rdRules["start"][i].token += ".virtual-comment";
   }

   this.addRules(rdRules, "rd-");
   this.$rules["rd-start"].unshift({
      token: "text",
      regex: "^",
      next: "start"
   });
   this.$rules["rd-start"].unshift({
      token : "keyword",
      regex : "@(?!@)[^ ]*"
   });
   this.$rules["rd-start"].unshift({
      token : "comment",
      regex : "@@"
   });
   this.$rules["rd-start"].push({
      token : "comment",
      regex : "[^%\\\\[({\\])}]+"
   });

   this.embedRules(DocCommentHighlightRules, "doc-",
                   [ DocCommentHighlightRules.getEndRule("start") ]);

   // Embed R syntax highlighting
   this.$rules["start"].unshift({
      token: "support.function.codebegin",
      regex: "^\\s*\\/\\*{3,}\\s*[Rr]\\s*$",
      next: "r-start"
   });

   var rRules = new RHighlightRules().getRules();
   this.addRules(rRules, "r-");
   this.$rules["r-start"].unshift({
      token: "support.function.codeend",
      regex: "\\*\\/",
      next: "start"
   });

};

oop.inherits(c_cppHighlightRules, TextHighlightRules);

exports.c_cppHighlightRules = c_cppHighlightRules;
});
<|endoftext|>


<commit_before>import formInputMixin from "./FormInputMixin";

export default {

    mixins: [formInputMixin],

    props: {

        // The predefined value of the checkbox that gets submitted when the checkbox is checked. Overrides the mixin's prop.
        value: {
            type: Boolean|Number|String,
            default: true
        },

        // States if the checkbox is initially checked. If checked this input will submit the component's `value` prop,
        // otherwise `false` will be submitted.
        checked: {
            type: Boolean,
            default: false
        }
    },

    data() {
        return {

            // States if the checkbox is currently checked. If checked this input will submit the component's `value` prop,
            // otherwise `false` will be submitted.
            isChecked: this.checked
        }
    },

    computed: {

        // The element that activates the help tooltip on hover
        tooltipActivator: function () {
            return null;
        }
    },

    watch: {
        isChecked: function (checked) {
            if (checked) {
                this.submitValue = this.value;
            } else {
                this.submitValue = false;
            }
        }
    },

    mounted() {
        this.$nextTick(function () {
            if (this.isChecked) {
                this.submitValue = this.value;
            } else {
                this.submitValue = false;
            }
        });
    },

    methods: {

        /**
         * Toggles the submit value.
         */
        toggleValue: function () {
            this.isChecked = !this.isChecked;
        },
    }

};

<commit_msg>Fixed wrong initial checkbox input value<commit_after>import formInputMixin from "./FormInputMixin";

export default {

    mixins: [formInputMixin],

    props: {

        // The predefined value of the checkbox that gets submitted when the checkbox is checked. Overrides the mixin's prop.
        value: {
            type: Boolean|Number|String,
            default: true
        },

        // States if the checkbox is initially checked. If checked this input will submit the component's `value` prop,
        // otherwise `false` will be submitted.
        checked: {
            type: Boolean,
            default: false
        }
    },

    data() {
        return {

            // The real value that gets submitted.
            submitValue: this.checked ? this.value : false,

            // States if the checkbox is currently checked. If checked this input will submit the component's `value` prop,
            // otherwise `false` will be submitted.
            isChecked: this.checked
        }
    },

    computed: {

        // The element that activates the help tooltip on hover
        tooltipActivator: function () {
            return null;
        }
    },

    watch: {
        isChecked: function (checked) {
            if (checked) {
                this.submitValue = this.value;
            } else {
                this.submitValue = false;
            }
        }
    },

    methods: {

        /**
         * Toggles the submit value.
         */
        toggleValue: function () {
            this.isChecked = !this.isChecked;
        },
    }

};

<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 */

'use strict';

import NativeEventEmitter from '../EventEmitter/NativeEventEmitter';
import NativeNetworkingIOS from './NativeNetworkingIOS';
import type {NativeResponseType} from './XMLHttpRequest';
import convertRequestBody from './convertRequestBody';
import type {RequestBody} from './convertRequestBody';

class RCTNetworking extends NativeEventEmitter {
  constructor() {
    super(NativeNetworkingIOS, {
      __SECRET_DISABLE_CALLS_INTO_MODULE_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: true,
    });
  }

  sendRequest(
    method: string,
    trackingName: string,
    url: string,
    headers: {...},
    data: RequestBody,
    responseType: NativeResponseType,
    incrementalUpdates: boolean,
    timeout: number,
    callback: (requestId: number) => void,
    withCredentials: boolean,
  ) {
    const body = convertRequestBody(data);
    NativeNetworkingIOS.sendRequest(
      {
        method,
        url,
        data: {...body, trackingName},
        headers,
        responseType,
        incrementalUpdates,
        timeout,
        withCredentials,
      },
      callback,
    );
  }

  abortRequest(requestId: number) {
    NativeNetworkingIOS.abortRequest(requestId);
  }

  clearCookies(callback: (result: boolean) => void) {
    NativeNetworkingIOS.clearCookies(callback);
  }
}

module.exports = (new RCTNetworking(): RCTNetworking);
<commit_msg>Back out "Roll out RCTNetworking extraneous NativeModule call removal"<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 */

'use strict';

import NativeEventEmitter from '../EventEmitter/NativeEventEmitter';
import NativeNetworkingIOS from './NativeNetworkingIOS';
import type {NativeResponseType} from './XMLHttpRequest';
import convertRequestBody from './convertRequestBody';
import type {RequestBody} from './convertRequestBody';

class RCTNetworking extends NativeEventEmitter {
  constructor() {
    const disableCallsIntoModule =
      typeof global.__disableRCTNetworkingExtraneousModuleCalls === 'function'
        ? global.__disableRCTNetworkingExtraneousModuleCalls()
        : false;

    super(NativeNetworkingIOS, {
      __SECRET_DISABLE_CALLS_INTO_MODULE_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: disableCallsIntoModule,
    });
  }

  sendRequest(
    method: string,
    trackingName: string,
    url: string,
    headers: {...},
    data: RequestBody,
    responseType: NativeResponseType,
    incrementalUpdates: boolean,
    timeout: number,
    callback: (requestId: number) => void,
    withCredentials: boolean,
  ) {
    const body = convertRequestBody(data);
    NativeNetworkingIOS.sendRequest(
      {
        method,
        url,
        data: {...body, trackingName},
        headers,
        responseType,
        incrementalUpdates,
        timeout,
        withCredentials,
      },
      callback,
    );
  }

  abortRequest(requestId: number) {
    NativeNetworkingIOS.abortRequest(requestId);
  }

  clearCookies(callback: (result: boolean) => void) {
    NativeNetworkingIOS.clearCookies(callback);
  }
}

module.exports = (new RCTNetworking(): RCTNetworking);
<|endoftext|>


<commit_before>(function(){

	JsBarcode = function(image, content, options) {

		var merge = function(m1, m2) {
			var newMerge = {};
			for (var k in m1) {
				newMerge[k] = m1[k];
			}
			for (var k in m2) {
				newMerge[k] = m2[k];
			}
			return newMerge;
		};

		//Merge the user options with the default
		options = merge(JsBarcode.defaults, options);

		//Create the canvas where the barcode will be drawn on
		// Check if the given image is already a canvas
		var canvas = image;

		// check if it is a jQuery selection
		if (image instanceof jQuery) {
			// get the DOM element of the selection
			canvas = image.get(0);
			// check if DOM element is a canvas, otherwise it will be probably an image so create a canvas
			if (!(canvas instanceof HTMLCanvasElement)) {
				canvas = document.createElement('canvas');
			}
		} else if (!(image instanceof HTMLCanvasElement)) {
			// there is no jQuery selection so just check if DOM element is a canvas, otherwise it will be probably
			// an image so create a canvas
			canvas = document.createElement('canvas');
		}

		//Abort if the browser does not support HTML5canvas
		if (!canvas.getContext) {
			return image;
		}

		var encoder = new window[options.format](content);

		//Abort if the barcode format does not support the content
		if(!encoder.valid()){
			return this;
		}

		//Encode the content
		var binary = encoder.encoded();

		var _drawBarcodeText = function (text) {
					var x, y;

					y = options.height;

					ctx.font = options.fontSize + "px "+options.font;
					ctx.textBaseline = "bottom";
					ctx.textBaseline = 'top';

					if(options.textAlign == "left"){
						x = options.quite;
						ctx.textAlign = 'left';
					}
					else if(options.textAlign == "right"){
						x = canvas.width - options.quite;
						ctx.textAlign = 'right';
					}
					else{ //All other center
						x = canvas.width / 2;
						ctx.textAlign = 'center';
					}

					ctx.fillText(text, x, y);
				}

		//Get the canvas context
		var ctx	= canvas.getContext("2d");

		//Set the width and height of the barcode
		canvas.width = binary.length*options.width+2*options.quite;
		canvas.height = options.height + (options.displayValue ? options.fontSize : 0);

		//Paint the canvas
		ctx.clearRect(0,0,canvas.width,canvas.height);
		if(options.backgroundColor){
			ctx.fillStyle = options.backgroundColor;
			ctx.fillRect(0,0,canvas.width,canvas.height);
		}

		//Creates the barcode out of the encoded binary
		ctx.fillStyle = options.lineColor;
		for(var i=0;i<binary.length;i++){
			var x = i*options.width+options.quite;
			if(binary[i] == "1"){
				ctx.fillRect(x,0,options.width,options.height);
			}
		}

		if(options.displayValue){
			_drawBarcodeText(content);
		}

		//Grab the dataUri from the canvas
		uri = canvas.toDataURL('image/png');

		// check if given image is a jQuery selection
		if (image instanceof jQuery) {
			// check if the given image was a canvas, if not set the source attribute of the image
			if (!(image.get(0) instanceof HTMLCanvasElement)) {
				//Put the data uri into the image
				return image.attr("src", uri);
			}
		} else if (!(image instanceof HTMLCanvasElement)) {
			// There is no jQuery selection so just check if the given image was a canvas, if not set the source attr
			image.setAttribute("src", uri);
		}

	};

	JsBarcode.defaults = {
		width:	2,
		height:	100,
		quite: 10,
		format:	"CODE128",
		displayValue: false,
		font:"Monospaced",
		textAlign:"center",
		fontSize: 12,
		backgroundColor:"",
		lineColor:"#000"
	};

	$.fn.JsBarcode = function(content, options){
		JsBarcode(this, content, options);
		return this;
	};

})(jQuery);<commit_msg>improved checking if given image is a canvas<commit_after>(function(){

	JsBarcode = function(image, content, options) {

		var merge = function(m1, m2) {
			var newMerge = {};
			for (var k in m1) {
				newMerge[k] = m1[k];
			}
			for (var k in m2) {
				newMerge[k] = m2[k];
			}
			return newMerge;
		};

		//Merge the user options with the default
		options = merge(JsBarcode.defaults, options);

		//Create the canvas where the barcode will be drawn on
		// Check if the given image is already a canvas
		var canvas = image;

		// check if it is a jQuery object
		if (canvas instanceof jQuery) {
			// get the DOM element of the object
			canvas = image.get(0);
		}

		// check if DOM element is a canvas, otherwise it will be probably an image so create a canvas
		if (!(canvas instanceof HTMLCanvasElement)) {
			canvas = document.createElement('canvas');
		}

		//Abort if the browser does not support HTML5canvas
		if (!canvas.getContext) {
			return image;
		}

		var encoder = new window[options.format](content);

		//Abort if the barcode format does not support the content
		if(!encoder.valid()){
			return this;
		}

		//Encode the content
		var binary = encoder.encoded();

		var _drawBarcodeText = function (text) {
					var x, y;

					y = options.height;

					ctx.font = options.fontSize + "px "+options.font;
					ctx.textBaseline = "bottom";
					ctx.textBaseline = 'top';

					if(options.textAlign == "left"){
						x = options.quite;
						ctx.textAlign = 'left';
					}
					else if(options.textAlign == "right"){
						x = canvas.width - options.quite;
						ctx.textAlign = 'right';
					}
					else{ //All other center
						x = canvas.width / 2;
						ctx.textAlign = 'center';
					}

					ctx.fillText(text, x, y);
				}

		//Get the canvas context
		var ctx	= canvas.getContext("2d");

		//Set the width and height of the barcode
		canvas.width = binary.length*options.width+2*options.quite;
		canvas.height = options.height + (options.displayValue ? options.fontSize : 0);

		//Paint the canvas
		ctx.clearRect(0,0,canvas.width,canvas.height);
		if(options.backgroundColor){
			ctx.fillStyle = options.backgroundColor;
			ctx.fillRect(0,0,canvas.width,canvas.height);
		}

		//Creates the barcode out of the encoded binary
		ctx.fillStyle = options.lineColor;
		for(var i=0;i<binary.length;i++){
			var x = i*options.width+options.quite;
			if(binary[i] == "1"){
				ctx.fillRect(x,0,options.width,options.height);
			}
		}

		if(options.displayValue){
			_drawBarcodeText(content);
		}

		//Grab the dataUri from the canvas
		uri = canvas.toDataURL('image/png');

		// check if given image is a jQuery object
		if (image instanceof jQuery) {
			// check if DOM element of jQuery selection is not a canvas, so assume that it is an image
			if (!(image.get(0) instanceof HTMLCanvasElement)) {
				 //Put the data uri into the image
			 	return image.attr("src", uri);
			}
		} else if (!(image instanceof HTMLCanvasElement)) {
			// There is no jQuery object so just check if the given image was a canvas, if not set the source attr
			image.setAttribute("src", uri);
		}

	};

	JsBarcode.defaults = {
		width:	2,
		height:	100,
		quite: 10,
		format:	"CODE128",
		displayValue: false,
		font:"Monospaced",
		textAlign:"center",
		fontSize: 12,
		backgroundColor:"",
		lineColor:"#000"
	};

	$.fn.JsBarcode = function(content, options){
		JsBarcode(this, content, options);
		return this;
	};

})(jQuery);<|endoftext|>


<commit_before>'use strict';

import DeepFramework from 'deep-framework';

export default class extends DeepFramework.Core.AWS.Lambda.Runtime {
  /**
   * @param {*} args
   */
  constructor(...args) {
    super(...args);
  }

  /**
   * @param {Object} nameData
   */
  handle(nameData) {
    this.persistPayloadInFs(nameData, (error, createdFile) => {
      if (error) {
        return this.createError(error).send();
      }

      this.persistPayloadInDb(nameData, (error, NameModel) => {
        if (error) {
          return this.createError(error).send();
        }

        this.createResponse({
          msg: `Hello ${nameData.Name}!`,
          db: NameModel.get(),
          fs: createdFile,
        }).send();
      });
    });
  }

  /**
   * Saves request payload into system fs (it can be also saved into public and temp fs)
   *
   * @param {Object} payload
   * @param {Function} callback
   */
  persistPayloadInFs(payload, callback) {
    let fs = this.kernel.get('fs');

    let fileName = `request_payload_${(new Date()).toISOString()}`;

    fs.system.writeFile(fileName, JSON.stringify(payload), (error) => {
      error ? callback(error, null) : callback(null, fileName);
    });
  }

  /**
   * Saves request payload into DB
   *
   * @param {Object} payload
   * @param {Function} callback
   */
  persistPayloadInDb(payload, callback) {
    let db = this.kernel.get('db');

    db.get('Name').createItem(payload, (error, NameModel) => {
      error ? callback(error, null) : callback(null, NameModel);
    });
  }
}
<commit_msg>Fix to support windows filenames<commit_after>'use strict';

import DeepFramework from 'deep-framework';

export default class extends DeepFramework.Core.AWS.Lambda.Runtime {
  /**
   * @param {*} args
   */
  constructor(...args) {
    super(...args);
  }

  /**
   * @param {Object} nameData
   */
  handle(nameData) {
    this.persistPayloadInFs(nameData, (error, createdFile) => {
      if (error) {
        return this.createError(error).send();
      }

      this.persistPayloadInDb(nameData, (error, NameModel) => {
        if (error) {
          return this.createError(error).send();
        }

        this.createResponse({
          msg: `Hello ${nameData.Name}!`,
          db: NameModel.get(),
          fs: createdFile,
        }).send();
      });
    });
  }

  /**
   * Saves request payload into system fs (it can be also saved into public and temp fs)
   *
   * @param {Object} payload
   * @param {Function} callback
   */
  persistPayloadInFs(payload, callback) {
    let fs = this.kernel.get('fs');

    //replace to be able to use in Windows filenames
    let timestamp = (new Date()).toISOString().(/[\<\>\:\"\/\\\|\?\*]/g, '_');

    let fileName = `request_payload_${timestamp}`;

    fs.system.writeFile(fileName, JSON.stringify(payload), (error) => {
      error ? callback(error, null) : callback(null, fileName);
    });
  }

  /**
   * Saves request payload into DB
   *
   * @param {Object} payload
   * @param {Function} callback
   */
  persistPayloadInDb(payload, callback) {
    let db = this.kernel.get('db');

    db.get('Name').createItem(payload, (error, NameModel) => {
      error ? callback(error, null) : callback(null, NameModel);
    });
  }
}
<|endoftext|>


<commit_before>define('nav_view', ['app'], function (app) {

	var BaseNavView = Backbone.View.extend({
			initialize: function (options) {

				this.broker = options.broker;
				this.parent = options.parent;
				this.status = options.status;
			},

			statusChange: function (status) {
				// ['showing', 'hiding', 'toShow', 'toHide']
				if (status === 'toShow') {
					this.$el.show();
					this.status = 'showing';
				} else if (status === 'toHide') {
					this.$el.hide();
					this.status = 'hiding';
				}
			}
		}),

		AddSearchNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'addTask', 'searchTasks');

				// Binding events fromt the user.
				this.$el.find('.add a').bind('click', this.addTask);
				this.$el.find('.search input').bind('keyup', this.searchTasks);

				// Binding show/hide events for AddSearch navigation
				this.broker.on('addSearch:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('addSearch:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			addTask: function () {
				this.broker.trigger('addSearch:hide');
				this.broker.trigger('createForm:show');
				// Display form nav (with title and description)
			},

			searchTasks: function () {
				// Triggering search event to tasks_view module.
				this.broker.trigger('task:search', this.$el.find('.search input').val());
			}
		}),

		CreateFormNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'submitTask', 'cancelTask');

				// Binding events from the user.
				this.$el.find('.save input').bind('click', this.submitTask);
				this.$el.find('.cancel a').bind('click', this.cancelTask);

				// Binding show/hide events for CreateForm navigation
				this.broker.on('createForm:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('createForm:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			submitTask: function () {
				this.broker.trigger('createForm:hide');
				this.broker.trigger('addSearch:show');

				// Collect all datas to create a task.
				var datas = this._collectDatas();
				this.broker.trigger('task:create', datas);
			},

			cancelTask: function () {
				this.broker.trigger('createForm:hide');
				this.broker.trigger('addSearch:show');

				this._cleanForm();
			},

			_collectDatas: function () {},
			_cleanForm: function() {}
		}),

		EditRemoveNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'editTasks', 'removeTasks', 'changeStatus');

				// Binding events from the user.
				this.$el.find('.edit a').bind('click', this.editTasks);
				this.$el.find('.remove a').bind('click', this.removeTasks);
				this.$el.find('.status a').bind('click', this.changeStatus);

				// Binding show/hide events for EditRemove navigation
				this.broker.on('editRemove:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('editRemove:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			editTasks: function () {
				this.broker.trigger('editRemove:hide');
				this.broker.trigger('saveCancel:show', 'editing');

				// Get a list of all tasks selected (ID).
				var selectedTasks = [];
				// Change mode from read-only to form in each task.
				this.broker.trigger('tasks:edit:view', selectedTasks);
			},

			removeTasks: function () {
				this.broker.trigger('editRemove:hide');
				this.broker.trigger('saveCancel:show', 'removing');

				// Those tasks will be removed on the "save" action.
				// var selectedTasks = [];
				// this.broker.trigger('tasks:remove', selectedTasks);
			},

			changeStatus: function () {
				// Show dropdow and apply the new status to all items selected
			}
		}),

		SaveCancelNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'saveTasks', 'cancelTasks', '_checkedItems');

				// Binding events from the user.
				this.$el.find('.save input').bind('click', this.saveTasks);
				this.$el.find('.cancel a').bind('click', this.cancelTasks);

				// Binding show/hide events for SaveCancel navigation
				this.broker.on('saveCancel:show', function (action) {
					this.statusChange('toShow');
					this.action = action;
				}, this);
				this.broker.on('saveCancel:hide', function () {
					this.statusChange('toHide');
				}, this);

				this.broker.on('task:select', this._checkedItems);
			},

			saveTasks: function () {
				this.broker.trigger('saveCancel:hide');
				this.broker.trigger('addSearch:show');

				var selectedList = [];
				if (this.action === 'editing') {
					// Collect all datas: id, title and description.
					this.broker.trigger('task:edit:save', selectedList);
				} else {
					// collect a list of ID only
					this.broker.trigger('task:remove', selectedList);
				}
			},

			cancelTasks: function () {
				// Come back each task to read-only mode
				this.broker.trigger('task:edit:save', []);

				this.broker.trigger('saveCancel:hide');

				if (this.itemsSelected === 'checked') {
					this.broker.trigger('editRemove:show');
				} else {
					this.broker.trigger('addSearch:show');
				}
			},

			_checkedItems: function (mode) {
				this.itemsSelected = mode;
			}

		});

	return Backbone.View.extend({

		initialize: function (options) {

			this.parent = options.parent;
			this.broker = options.broker;

			this.statusNavList = ['showing', 'hiding', 'toShow', 'toHide'];

			_.bindAll(this, 'selectedItem');

			this.addSearch = new AddSearchNav({
				parent: this,
				el: this.$el.find('.default'),
				broker: this.broker,
				status: this.statusNavList[0]
			});

			this.createForm = new CreateFormNav({
				parent: this,
				el: this.$el.find('.form'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.editRemove = new EditRemoveNav({
				parent: this,
				el: this.$el.find('.item_selected'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.saveCancel = new SaveCancelNav({
				parent: this,
				el: this.$el.find('.action_required'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.createForm.$el.hide();
			this.editRemove.$el.hide();
			this.saveCancel.$el.hide();

			this.broker.on('task:select', this.selectedItem);
		},

		selectedItem: function (mode) {
			if (mode === 'checked') {
				this.broker.trigger('addSearch:hide');
				this.broker.trigger('createForm:hide');
				this.broker.trigger('saveCancel:hide');

				this.broker.trigger('editRemove:show');
			} else if (mode === 'unchecked') {
				this.broker.trigger('editRemove:hide');
				this.broker.trigger('createForm:hide');
				this.broker.trigger('saveCancel:hide');

				this.broker.trigger('addSearch:show');
			}
		}

	});
});<commit_msg>Prevent function event on each function and adding _collectData functionality for creating a task<commit_after>define('nav_view', ['app'], function (app) {

	var BaseNavView = Backbone.View.extend({
			initialize: function (options) {

				this.broker = options.broker;
				this.parent = options.parent;
				this.status = options.status;
			},

			statusChange: function (status) {
				// ['showing', 'hiding', 'toShow', 'toHide']
				if (status === 'toShow') {
					this.$el.show();
					this.status = 'showing';
				} else if (status === 'toHide') {
					this.$el.hide();
					this.status = 'hiding';
				}
			}
		}),

		AddSearchNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'addTask', 'searchTasks');

				// Binding events fromt the user.
				this.$el.find('.add a').bind('click', this.addTask);
				this.$el.find('.search input').bind('keyup', this.searchTasks);

				// Binding show/hide events for AddSearch navigation
				this.broker.on('addSearch:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('addSearch:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			addTask: function (e) {
				e.preventDefault();

				this.broker.trigger('addSearch:hide');
				this.broker.trigger('createForm:show');
				// Display form nav (with title and description)
			},

			searchTasks: function (e) {
				e.preventDefault();

				// Triggering search event to tasks_view module.
				this.broker.trigger('task:search', this.$el.find('.search input').val());
			}
		}),

		CreateFormNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'submitTask', 'cancelTask');

				// Binding events from the user.
				this.$el.find('.save input').bind('click', this.submitTask);
				this.$el.find('.cancel a').bind('click', this.cancelTask);

				// Binding show/hide events for CreateForm navigation
				this.broker.on('createForm:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('createForm:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			submitTask: function (e) {
				e.preventDefault();

				this.broker.trigger('createForm:hide');
				this.broker.trigger('addSearch:show');

				// Collect all datas to create a task.
				var datas = this._collectDatas();
				this.broker.trigger('task:create', datas);
			},

			cancelTask: function (e) {
				e.preventDefault();

				this.broker.trigger('createForm:hide');
				this.broker.trigger('addSearch:show');

				this._cleanForm();
			},

			_collectDatas: function () {
				var datas = {};

				datas.title = this.$el.find('[name=title]').val();
				datas.description = this.$el.find('[name=desc]').val();
				datas.status = 'waiting';

				return datas;
			},

			_cleanForm: function() {
				this.$el.find('[name=title], [name=desc]').val('');
			}
		}),

		EditRemoveNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'editTasks', 'removeTasks', 'changeStatus');

				// Binding events from the user.
				this.$el.find('.edit a').bind('click', this.editTasks);
				this.$el.find('.remove a').bind('click', this.removeTasks);
				this.$el.find('.status a').bind('click', this.changeStatus);

				// Binding show/hide events for EditRemove navigation
				this.broker.on('editRemove:show', function () {
					this.statusChange('toShow');
				}, this);
				this.broker.on('editRemove:hide', function () {
					this.statusChange('toHide');
				}, this);
			},

			editTasks: function (e) {
				e.preventDefault();

				this.broker.trigger('editRemove:hide');
				this.broker.trigger('saveCancel:show', 'editing');

				// Get a list of all tasks selected (ID).
				var selectedTasks = [];
				// Change mode from read-only to form in each task.
				this.broker.trigger('tasks:edit:view', selectedTasks);
			},

			removeTasks: function (e) {
				e.preventDefault();

				this.broker.trigger('editRemove:hide');
				this.broker.trigger('saveCancel:show', 'removing');

				// Those tasks will be removed on the "save" action.
				// var selectedTasks = [];
				// this.broker.trigger('tasks:remove', selectedTasks);
			},

			changeStatus: function (e) {
				e.preventDefault();
				// Show dropdow and apply the new status to all items selected
			}
		}),

		SaveCancelNav = BaseNavView.extend({

			initialize: function (options) {
				BaseNavView.prototype.initialize.call(this, options);
				_.bindAll(this, 'saveTasks', 'cancelTasks', '_checkedItems');

				// Binding events from the user.
				this.$el.find('.save input').bind('click', this.saveTasks);
				this.$el.find('.cancel a').bind('click', this.cancelTasks);

				// Binding show/hide events for SaveCancel navigation
				this.broker.on('saveCancel:show', function (action) {
					this.statusChange('toShow');
					this.action = action;
				}, this);
				this.broker.on('saveCancel:hide', function () {
					this.statusChange('toHide');
				}, this);

				this.broker.on('task:select', this._checkedItems);
			},

			saveTasks: function (e) {
				e.preventDefault();

				this.broker.trigger('saveCancel:hide');
				this.broker.trigger('addSearch:show');

				var selectedList = [];
				if (this.action === 'editing') {
					// Collect all datas: id, title and description.
					this.broker.trigger('task:edit:save', selectedList);
				} else {
					// collect a list of ID only
					this.broker.trigger('task:remove', selectedList);
				}
			},

			cancelTasks: function (e) {
				e.preventDefault();

				// Come back each task to read-only mode
				this.broker.trigger('task:edit:save', []);

				this.broker.trigger('saveCancel:hide');

				if (this.itemsSelected === 'checked') {
					this.broker.trigger('editRemove:show');
				} else {
					this.broker.trigger('addSearch:show');
				}
			},

			_checkedItems: function (mode) {
				this.itemsSelected = mode;
			}

		});

	return Backbone.View.extend({

		initialize: function (options) {

			this.parent = options.parent;
			this.broker = options.broker;

			this.statusNavList = ['showing', 'hiding', 'toShow', 'toHide'];

			_.bindAll(this, 'selectedItem');

			this.addSearch = new AddSearchNav({
				parent: this,
				el: this.$el.find('.default'),
				broker: this.broker,
				status: this.statusNavList[0]
			});

			this.createForm = new CreateFormNav({
				parent: this,
				el: this.$el.find('.form'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.editRemove = new EditRemoveNav({
				parent: this,
				el: this.$el.find('.item_selected'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.saveCancel = new SaveCancelNav({
				parent: this,
				el: this.$el.find('.action_required'),
				broker: this.broker,
				status: this.statusNavList[1]
			});

			this.createForm.$el.hide();
			this.editRemove.$el.hide();
			this.saveCancel.$el.hide();

			this.broker.on('task:select', this.selectedItem);
		},

		selectedItem: function (mode) {
			if (mode === 'checked') {
				this.broker.trigger('addSearch:hide');
				this.broker.trigger('createForm:hide');
				this.broker.trigger('saveCancel:hide');

				this.broker.trigger('editRemove:show');
			} else if (mode === 'unchecked') {
				this.broker.trigger('editRemove:hide');
				this.broker.trigger('createForm:hide');
				this.broker.trigger('saveCancel:hide');

				this.broker.trigger('addSearch:show');
			}
		}

	});
});<|endoftext|>