<commit_before>var menu = function(game){
	this.menuSpace = 160;
	maxPlayers = 7;
	  keys = [
    Phaser.Keyboard.W,
    Phaser.Keyboard.P,
    Phaser.Keyboard.B,
    Phaser.Keyboard.Z,
    Phaser.Keyboard.M,
    Phaser.Keyboard.C,
    Phaser.Keyboard.R,
    Phaser.Keyboard.U,]
  numberPlayers = 0;
  bestScore = 0;
  ballsScore = 0;
  deathScore = 0;
  this.scoreLabel = null;
  this.scoreText = null;
  menuMusic = null;

}

menu.prototype = {
  create: function(){
    if (mobile) {
      Cocoon.App.exitCallback(function() {
          this.game.state.states[this.game.state.current].backPressed();
        }.bind(this)
      );
    }

    if (changeColor) {
      chosenColor = this.game.rnd.integerInRange(0, 3);
      colorHex = bgColors[chosenColor];
      colorHexDark = bgColorsDark[chosenColor];
      document.body.style.background = colorHex;
      this.game.stage.backgroundColor = colorHex;
      changeColor = false;
    }

    bgColor = Phaser.Color.hexToColor(colorHex);
  	this.game.stage.backgroundColor = colorHex;
    document.body.style.background = colorHex;
  	w2 = this.game.world.width/2;
		h2 = this.game.world.height/2;

  	this.game.world.scale.set(1);

    if (numberPlayers == 0) {
      if (!menuMusic && !mute) {
        menuMusic = this.game.add.audio('dream');
        menuMusic.loop = true;
        menuMusic.play();
      } else if (!menuMusic.isPlaying && !mute){
        menuMusic.loop = true;
        menuMusic.play();
        menuMusic.volume = 1;
      }
    }

  	bestScore = parseInt(localStorage.getItem("highScore"));
  	if(isNaN(bestScore)) {
  		bestScore = 0;
  	}

    ballsScore = parseInt(localStorage.getItem("ballsScore"));
    if(isNaN(ballsScore)) {
      ballsScore = 0;
    }

    deathScore = parseInt(localStorage.getItem("deathScore"));
    if(isNaN(deathScore)) {
      deathScore = 0;
    }

		//Game Title
		var text = this.game.add.text(w2,120, "curvatron", {
      font: "200px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
  	});
  	text.anchor.setTo(0.5,0.5);

    var text = this.game.add.text(w2+360,210, "BETA", {
      font: "50px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
    });
    text.anchor.setTo(0.5,0.5);

    var text = this.game.add.text(w2,120, "curvatron", {
      font: "200px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
    });
    text.anchor.setTo(0.5,0.5);

    //Single Player
		var spButton = this.game.add.button(w2-w2/4,h2,"singleplayer_button",this.playTheGame,this);
		spButton.anchor.setTo(0.5,0.5);
		spButton.onInputOver.add(this.spOver, this);
		spButton.onInputOut.add(this.spOut, this);
    spButton.input.useHandCursor=true;

		//Score label that shows on hove
    if(bestScore != 0){
  		this.scoreLabel = this.game.add.sprite(w2-275,h2,"sp_score");
  		this.scoreLabel.anchor.setTo(0.5,0.5);
  		this.scoreLabel.alpha = 0;
  		this.scoreText = this.game.add.text(w2-300,h2+10, bestScore, {
          font: "120px Dosis Extrabold",
          fill: colorHex,
          align: "center"
    	});
    	this.scoreText.anchor.setTo(0.5,0.5);
    	this.scoreText.alpha = 0;
    }

    //Multiplayer
		var mpButton = this.game.add.button(w2+w2/4,h2,"multiplayer_button",this.multiplayer,this);
		mpButton.anchor.setTo(0.5,0.5);
    if (mobile) {
      mpButton.alpha = 0.2;
    }
    mpButton.input.useHandCursor=true;

    //FullScreen
    /*var fullScreenButton = this.game.add.button(w2+w2/2,h2+230,"fullscreen_button",this.fullScreen,this);
    fullScreenButton.anchor.setTo(0.5,0.5);
    fullScreenButton.input.useHandCursor=true;*/
    //SetKeys
    if(!mobile){
      var keysButton = this.game.add.button(w2+w2/2,h2+230,"setkeys_button",this.setKeys,this);
      keysButton.anchor.setTo(0.5,0.5);
      keysButton.input.useHandCursor=true;
    }

  	//Stats
  	var statsButton = this.game.add.button(w2,h2+230,"stats_button",this.stats,this);
		statsButton.anchor.setTo(0.5,0.5);
    statsButton.input.useHandCursor=true;
    if (mobile) {
      statsButton.x = w2+w2/6;
    }

  	//Audio
    if(mute){
    	audioButton = this.game.add.button(w2/2,h2+230,"audiooff_button",this.muteSound,this);
  		audioButton.anchor.setTo(0.5,0.5);
      audioButton.input.useHandCursor=true;
    }
    else{
      audioButton = this.game.add.button(w2/2,h2+230,"audio_button",this.muteSound,this);
      audioButton.anchor.setTo(0.5,0.5);
      audioButton.input.useHandCursor=true;
    }
    if (mobile) {
      audioButton.x = w2-w2/6;
    }
	},

	playTheGame: function(){
		numberPlayers = 0;
    menuMusic.fadeOut(2000);
		this.game.state.start("PreloadGame",true,false);
	},

	multiplayer: function(){
    if (!mobile) {
      this.game.state.start("Multiplayer");
    }
	},

	setKeys: function() {
    if (!mobile) {
      this.game.state.start("SetKeys");
    }
	},

  stats: function() {
    this.game.state.start("Stats");
  },

	spOver: function() {
		this.game.add.tween(this.scoreLabel).to( { alpha: 1 }, 200, Phaser.Easing.Linear.None, true);
		this.game.add.tween(this.scoreText).to( { alpha: 1 }, 200, Phaser.Easing.Linear.None, true);

	},

	spOut: function() {
		this.game.add.tween(this.scoreLabel).to( { alpha: 0 }, 200, Phaser.Easing.Linear.None, true);
		this.game.add.tween(this.scoreText).to( { alpha: 0 }, 200, Phaser.Easing.Linear.None, true);
	},

  muteSound: function(){
    if(mute){
      audioButton.loadTexture('audio_button');
      //this.game.sound.mute = false;
      mute = false;
      if (!menuMusic) {
        menuMusic = this.game.add.audio('dream');
      }
      menuMusic.loop = true;
      menuMusic.play();
      menuMusic.volume = 1;
    }
    else{
      audioButton.loadTexture('audiooff_button');
      //this.game.sound.mute = true;
      mute = true;
      if (menuMusic && menuMusic.isPlaying) {
        menuMusic.stop();
      }
    }
  },

  fullScreen: function(){
    if (this.game.scale.isFullScreen){
      this.game.scale.stopFullScreen();
    }
    else{
      this.game.scale.startFullScreen(false);
    }
  },

  backPressed: function() {
    //exit game?
  }
}<commit_msg>everything seems ok, gonna test on actual app<commit_after>var menu = function(game){
	this.menuSpace = 160;
	maxPlayers = 7;
	  keys = [
    Phaser.Keyboard.W,
    Phaser.Keyboard.P,
    Phaser.Keyboard.B,
    Phaser.Keyboard.Z,
    Phaser.Keyboard.M,
    Phaser.Keyboard.C,
    Phaser.Keyboard.R,
    Phaser.Keyboard.U,]
  numberPlayers = 0;
  bestScore = 0;
  ballsScore = 0;
  deathScore = 0;
  this.scoreLabel = null;
  this.scoreText = null;
  menuMusic = null;

}

menu.prototype = {
  create: function(){
    /*if (mobile) {
      Cocoon.App.exitCallback(function() {
          this.game.state.states[this.game.state.current].backPressed();
        }.bind(this)
      );
    }*/

    if (changeColor) {
      chosenColor = this.game.rnd.integerInRange(0, 3);
      colorHex = bgColors[chosenColor];
      colorHexDark = bgColorsDark[chosenColor];
      document.body.style.background = colorHex;
      this.game.stage.backgroundColor = colorHex;
      changeColor = false;
    }

    bgColor = Phaser.Color.hexToColor(colorHex);
  	this.game.stage.backgroundColor = colorHex;
    document.body.style.background = colorHex;
  	w2 = this.game.world.width/2;
		h2 = this.game.world.height/2;

  	this.game.world.scale.set(1);

    if (numberPlayers == 0) {
      if (!menuMusic && !mute) {
        menuMusic = this.game.add.audio('dream');
        menuMusic.loop = true;
        menuMusic.play();
      } else if (!menuMusic.isPlaying && !mute){
        menuMusic.loop = true;
        menuMusic.play();
        menuMusic.volume = 1;
      }
    }

  	bestScore = parseInt(localStorage.getItem("highScore"));
  	if(isNaN(bestScore)) {
  		bestScore = 0;
  	}

    ballsScore = parseInt(localStorage.getItem("ballsScore"));
    if(isNaN(ballsScore)) {
      ballsScore = 0;
    }

    deathScore = parseInt(localStorage.getItem("deathScore"));
    if(isNaN(deathScore)) {
      deathScore = 0;
    }

		//Game Title
		var text = this.game.add.text(w2,120, "curvatron", {
      font: "200px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
  	});
  	text.anchor.setTo(0.5,0.5);

    var text = this.game.add.text(w2+360,210, "BETA", {
      font: "50px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
    });
    text.anchor.setTo(0.5,0.5);

    var text = this.game.add.text(w2,120, "curvatron", {
      font: "200px Dosis Extrabold",
      fill: "#ffffff",
      align: "center"
    });
    text.anchor.setTo(0.5,0.5);

    //Single Player
		var spButton = this.game.add.button(w2-w2/4,h2,"singleplayer_button",this.playTheGame,this);
		spButton.anchor.setTo(0.5,0.5);
		spButton.onInputOver.add(this.spOver, this);
		spButton.onInputOut.add(this.spOut, this);
    spButton.input.useHandCursor=true;

		//Score label that shows on hove
    if(bestScore != 0){
  		this.scoreLabel = this.game.add.sprite(w2-275,h2,"sp_score");
  		this.scoreLabel.anchor.setTo(0.5,0.5);
  		this.scoreLabel.alpha = 0;
  		this.scoreText = this.game.add.text(w2-300,h2+10, bestScore, {
          font: "120px Dosis Extrabold",
          fill: colorHex,
          align: "center"
    	});
    	this.scoreText.anchor.setTo(0.5,0.5);
    	this.scoreText.alpha = 0;
    }

    //Multiplayer
		var mpButton = this.game.add.button(w2+w2/4,h2,"multiplayer_button",this.multiplayer,this);
		mpButton.anchor.setTo(0.5,0.5);
    if (mobile) {
      mpButton.alpha = 0.2;
    }
    mpButton.input.useHandCursor=true;

    //FullScreen
    /*var fullScreenButton = this.game.add.button(w2+w2/2,h2+230,"fullscreen_button",this.fullScreen,this);
    fullScreenButton.anchor.setTo(0.5,0.5);
    fullScreenButton.input.useHandCursor=true;*/
    //SetKeys
    if(!mobile){
      var keysButton = this.game.add.button(w2+w2/2,h2+230,"setkeys_button",this.setKeys,this);
      keysButton.anchor.setTo(0.5,0.5);
      keysButton.input.useHandCursor=true;
    }

  	//Stats
  	var statsButton = this.game.add.button(w2,h2+230,"stats_button",this.stats,this);
		statsButton.anchor.setTo(0.5,0.5);
    statsButton.input.useHandCursor=true;
    if (mobile) {
      statsButton.x = w2+w2/6;
    }

  	//Audio
    if(mute){
    	audioButton = this.game.add.button(w2/2,h2+230,"audiooff_button",this.muteSound,this);
  		audioButton.anchor.setTo(0.5,0.5);
      audioButton.input.useHandCursor=true;
    }
    else{
      audioButton = this.game.add.button(w2/2,h2+230,"audio_button",this.muteSound,this);
      audioButton.anchor.setTo(0.5,0.5);
      audioButton.input.useHandCursor=true;
    }
    if (mobile) {
      audioButton.x = w2-w2/6;
    }
	},

	playTheGame: function(){
		numberPlayers = 0;
    menuMusic.fadeOut(2000);
		this.game.state.start("PreloadGame",true,false);
	},

	multiplayer: function(){
    if (!mobile) {
      this.game.state.start("Multiplayer");
    }
	},

	setKeys: function() {
    if (!mobile) {
      this.game.state.start("SetKeys");
    }
	},

  stats: function() {
    this.game.state.start("Stats");
  },

	spOver: function() {
		this.game.add.tween(this.scoreLabel).to( { alpha: 1 }, 200, Phaser.Easing.Linear.None, true);
		this.game.add.tween(this.scoreText).to( { alpha: 1 }, 200, Phaser.Easing.Linear.None, true);

	},

	spOut: function() {
		this.game.add.tween(this.scoreLabel).to( { alpha: 0 }, 200, Phaser.Easing.Linear.None, true);
		this.game.add.tween(this.scoreText).to( { alpha: 0 }, 200, Phaser.Easing.Linear.None, true);
	},

  muteSound: function(){
    if(mute){
      audioButton.loadTexture('audio_button');
      //this.game.sound.mute = false;
      mute = false;
      if (!menuMusic) {
        menuMusic = this.game.add.audio('dream');
      }
      menuMusic.loop = true;
      menuMusic.play();
      menuMusic.volume = 1;
    }
    else{
      audioButton.loadTexture('audiooff_button');
      //this.game.sound.mute = true;
      mute = true;
      if (menuMusic && menuMusic.isPlaying) {
        menuMusic.stop();
      }
    }
  },

  fullScreen: function(){
    if (this.game.scale.isFullScreen){
      this.game.scale.stopFullScreen();
    }
    else{
      this.game.scale.startFullScreen(false);
    }
  },

  backPressed: function() {
    //exit game?
  }
}<|endoftext|>


<commit_before>var page = require('webpage').create(),
	system = require('system'),
	fs = require('fs'),
    content='',
	address  = system.args[1],
    standard = system.args[2],
	userName = system.args[3],
    scanDir = system.args[4],
    scrshot = system.args[5],
    eLevel = system.args[6],
    screenshot_url ;

	if(userName !== "") {
        var cookieFile = 'cookies/' + userName + ".txt";
	}
	phantom.silent = true;
    page.onConsoleMessage = function (msg) {
        // console.log(msg);
    };
    page.onError = function (msg) {
        // console.log(msg);
   };

/***************** H E L P E R   F U N C T I O N S *******************/
    function restoreCookies(cookieFile) {
     	var fs = require("fs");
    	if (fs.exists(cookieFile)) {
    		var cookies = fs.read(cookieFile);
    		cookies = JSON.parse(cookies);
    		//console.log("Restored cookies: " + JSON.stringify(cookies));
        	if (cookies.length > 0) {
        			for(var i=0; i<cookies.length; ++i)  {
        				var item = cookies[i];
        				if (item.expires) item.expires = Date.parse(item.expires);
        				if (item.expiry)    item.expiry = Date.parse(item.expiry);
        				phantom.addCookie(item);
        			}
        	}
    	}
    }

    function formRows(msg){

                var  msgParts   = msg.code.split('.')
                    , principles = {
                        'Principle1': 'Perceivable',
                        'Principle2': 'Operable',
                        'Principle3': 'Understandable',
                        'Principle4': 'Robust'
                    }
                    , typeName = {
                          '1' : 'Error',
                          '2' : 'Warning',
                          '3' : 'Notice'
                    }
                    , principle  = msgParts[1]
                    , sc         = msgParts[3].split('_').slice(0, 3).join('_')
                    , techniques = msgParts[4].split(',')
                    , outerHTML = ''
                    , priority
                    , screenshot_url =''

                content += '
';
                content += '' + typeName[msg.type] + '	';
                content += '';
                content += '' + principles[principle] + '';
                content += '	';

                // content += '' + priority + '	';
                content += ' ' + msg.msg + '	';
                content += '' + msg.element  + '	';
                content += '
';
                for (var j = 0; j < techniques.length; j++) {
                    content += '
' + techniques[j] + '
';
                }
                content += '
	';

                var rect = eval("(" + msg.rect + ')');

                if(rect.width!== 0 && rect.height!== 0){

                    if(scrshot =='false'){
                        content += ' 	';
                    }else {
                        var screenshot =Math.floor((Math.random()*1000)+1) +'.png';
                        screenshot_url=  scanDir + '/' + screenshot ;
                        // page.clipRect = rect;
                        page.clipRect = { left: rect.left, top: rect.top, width: rect.width + 100 , height: rect.height + 100 };
                        page.render(screenshot_url);
                        content += '	';
                    }
                }else{
                    content += '  No scr	';
                }

                content += '
';
    }

    function outputToHtml(msgs){
        var heading =''
            , msg
            , errors   = 0
            , warnings = 0
            , notices  = 0
            , count=1

        if (msgs.length === 0) {
            content += 'No violations found';
            content += '
';
            return;
        }

        content += '
';
        content += '

Error Level	Principle	Message	Code snippet	Techniques	Screenshot

';

        // console.log('Debug eLevel -> ', eLevel);

         for (var key in msgs) {
            msg = msgs[key];

            if(eLevel.indexOf(msg.type) !=-1 ) {
                if(msg.type==1) errors++;
                if(msg.type==2) warnings++;
                if(msg.type==3) notices++;

                formRows(msg);
            }   //if loop
        }   //for loop

        heading += '
' + msgs['title'] +'
';

        if(address.indexOf("file:") === -1){
            heading += '
' + msgs['address'] + '
';
        }
        count = errors + warnings + notices;
        heading += '

';
        heading += '' + errors + 'errors
';
        heading += '' + warnings + 'warnings
';
        heading += '' + notices + 'notices
';

        heading += '
';

        if(address.indexOf("file:") === -1){
            heading +='Export as CSV';
        }
        if(errors === 0) {
            content += '
 ----  No Errors ---
';
        }

        content += '

';

        content  ='
' + heading + content +'
';

        return content;
    }

/***************** E N D   H E L P E R   F U N C T I O N S *******************/

    if(userName != "") {
        restoreCookies(cookieFile);
    }

    page.open(address, function (status) {
    // F O R   T E S T I N G
    // page.open('about:blank', function (status) {
    // page.content = '<input type="text" id="1"> <input type="text" id="2">PLAIN TEXT';

        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            window.setTimeout(function () {
                page.onConsoleMessage = function (msg) {
                    if (msg === 'done') phantom.exit();
                    console.log(msg);
                };

                var fs = require('fs');
                page.injectJs('./src/htmlcs/HTMLCS.js');

                var data = {
                    standard : standard
                };

                switch (standard) {
                    case 'WCAG2A':
                    case 'WCAG2AA':
                    case 'WCAG2AAA':
                        var results = page.evaluate(function(data) {
                            var standard = data.standard
                                , messages, msgJson ={}
                                , splitLine = function (s, n) {           //Break the code snippet into multiple lines
                                    var b = '';
                                    while (s.length > n) {
                                        var c = s.substring(0,n);
                                        var d = c.lastIndexOf(' ');
                                        var e =c.lastIndexOf('\n');
                                        if (e != -1)    d = e;
                                        if (d == -1)    d = n;
                                        b += c.substring(0,d) + '\n';
                                        s = s.substring(d+1);
                                    }
                                    return b+s;
                                 }

                            HTMLCS.process(standard, document, function() {
                                messages = HTMLCS.getMessages();
                                for (var i = 0 ,l = messages.length ; i < l ; i++) {
                                    var msg = messages[i]
                                        , outerHTML;

                                    if (msg.element.innerHTML.length > 50)  outerHTML = msg.element.outerHTML.replace(msg.element.innerHTML, msg.element.innerHTML.substr(0, 50) + '...');
                                    else outerHTML = msg.element.outerHTML;

                                    msgJson[i] = {
                                                      "type"    : msg.type
                                                    , "element" : splitLine(outerHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'), 30)
                                                    , "msg"     : msg.msg
                                                    , "code"    : msg.code
                                                    , "rect"    : JSON.stringify( msg.element.getBoundingClientRect() )
                                                }
                                }   //End for loop

                                msgJson['title'] = document.title;
                                msgJson['address'] = document.location.href

                            })          //End HTMLCS.process

                            //console.log(msgJson);
                            return  msgJson;

                        }, data);       //End evaluate

                    break;
                    default:
                        console.log('Unknown standard.');
                        phantom.exit();
                    break;
                }

                // console.log(JSON.stringify(results));
                var htmlStr = outputToHtml(results);
                console.log(htmlStr);
                phantom.exit();
            }, 200);
        }//end if
    });//end
<commit_msg>Change path in Paet.js<commit_after>var page = require('webpage').create(),
	system = require('system'),
	fs = require('fs'),
    content='',
	address  = system.args[1],
    standard = system.args[2],
	userName = system.args[3],
    scanDir = system.args[4],
    scrshot = system.args[5],
    eLevel = system.args[6],
    screenshot_url ;

	if(userName !== "") {
        var cookieFile = 'cookies/' + userName + ".txt";
	}
	phantom.silent = true;
    page.onConsoleMessage = function (msg) {
        // console.log(msg);
    };
    page.onError = function (msg) {
        // console.log(msg);
        phantom.exit();
    };

/***************** H E L P E R   F U N C T I O N S *******************/
    function restoreCookies(cookieFile) {
     	var fs = require("fs");
    	if (fs.exists(cookieFile)) {
    		var cookies = fs.read(cookieFile);
    		cookies = JSON.parse(cookies);
    		//console.log("Restored cookies: " + JSON.stringify(cookies));
        	if (cookies.length > 0) {
        			for(var i=0; i<cookies.length; ++i)  {
        				var item = cookies[i];
        				if (item.expires) item.expires = Date.parse(item.expires);
        				if (item.expiry)    item.expiry = Date.parse(item.expiry);
        				phantom.addCookie(item);
        			}
        	}
    	}
    }

    function formRows(msg){

                var  msgParts   = msg.code.split('.')
                    , principles = {
                        'Principle1': 'Perceivable',
                        'Principle2': 'Operable',
                        'Principle3': 'Understandable',
                        'Principle4': 'Robust'
                    }
                    , typeName = {
                          '1' : 'Error',
                          '2' : 'Warning',
                          '3' : 'Notice'
                    }
                    , principle  = msgParts[1]
                    , sc         = msgParts[3].split('_').slice(0, 3).join('_')
                    , techniques = msgParts[4].split(',')
                    , outerHTML = ''
                    , priority
                    , screenshot_url =''

                content += '
';
                content += '' + typeName[msg.type] + '	';
                content += '';
                content += '' + principles[principle] + '';
                content += '	';

                // content += '' + priority + '	';
                content += ' ' + msg.msg + '	';
                content += '' + msg.element  + '	';
                content += '
';
                for (var j = 0; j < techniques.length; j++) {
                    content += '
' + techniques[j] + '
';
                }
                content += '
	';

                var rect = eval("(" + msg.rect + ')');

                if(rect.width!== 0 && rect.height!== 0){

                    if(scrshot =='false'){
                        content += ' 	';
                    }else {
                        var screenshot =Math.floor((Math.random()*1000)+1) +'.png';
                        screenshot_url=  scanDir + '/' + screenshot ;
                        // page.clipRect = rect;
                        page.clipRect = { left: rect.left, top: rect.top, width: rect.width + 100 , height: rect.height + 100 };
                        page.render(screenshot_url);
                        content += '	';
                    }
                }else{
                    content += '  No scr	';
                }

                content += '
';
    }

    function outputToHtml(msgs){
        var heading =''
            , msg
            , errors   = 0
            , warnings = 0
            , notices  = 0
            , count=1

        if (msgs.length === 0) {
            content += 'No violations found';
            content += '
';
            return;
        }

        content += '
';
        content += '

Error Level	Principle	Message	Code snippet	Techniques	Screenshot

';

        // console.log('Debug eLevel -> ', eLevel);

         for (var key in msgs) {
            msg = msgs[key];

            if(eLevel.indexOf(msg.type) !=-1 ) {
                if(msg.type==1) errors++;
                if(msg.type==2) warnings++;
                if(msg.type==3) notices++;

                formRows(msg);
            }   //if loop
        }   //for loop

        heading += '
' + msgs['title'] +'
';

        if(address.indexOf("file:") === -1){
            heading += '
' + msgs['address'] + '
';
        }
        count = errors + warnings + notices;
        heading += '

';
        heading += '' + errors + 'errors
';
        heading += '' + warnings + 'warnings
';
        heading += '' + notices + 'notices
';

        heading += '
';

        if(address.indexOf("file:") === -1){
            heading +='Export as CSV';
        }
        if(errors === 0) {
            content += '
 ----  No Errors ---
';
        }

        content += '

';

        content  ='
' + heading + content +'
';

        return content;
    }

/***************** E N D   H E L P E R   F U N C T I O N S *******************/

    if(userName != "") {
        restoreCookies(cookieFile);
    }

    page.open(address, function (status) {
    // F O R   T E S T I N G
    // page.open('about:blank', function (status) {
    // page.content = '<input type="text" id="1"> <input type="text" id="2">PLAIN TEXT';

        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            window.setTimeout(function () {
                page.onConsoleMessage = function (msg) {
                    if (msg === 'done') phantom.exit();
                    console.log(msg);
                };

                var fs = require('fs');
                page.injectJs('./src/htmlcs/build/HTMLCS.js');

                var data = {
                    standard : standard
                };

                switch (standard) {
                    case 'WCAG2A':
                    case 'WCAG2AA':
                    case 'WCAG2AAA':
                        var results = page.evaluate(function(data) {
                            var standard = data.standard
                                , messages, msgJson ={}
                                , splitLine = function (s, n) {           //Break the code snippet into multiple lines
                                    var b = '';
                                    while (s.length > n) {
                                        var c = s.substring(0,n);
                                        var d = c.lastIndexOf(' ');
                                        var e =c.lastIndexOf('\n');
                                        if (e != -1)    d = e;
                                        if (d == -1)    d = n;
                                        b += c.substring(0,d) + '\n';
                                        s = s.substring(d+1);
                                    }
                                    return b+s;
                                 }

                            HTMLCS.process(standard, document, function() {
                                messages = HTMLCS.getMessages();
                                for (var i = 0 ,l = messages.length ; i < l ; i++) {
                                    var msg = messages[i]
                                        , outerHTML;

                                    if (msg.element.innerHTML.length > 50)  outerHTML = msg.element.outerHTML.replace(msg.element.innerHTML, msg.element.innerHTML.substr(0, 50) + '...');
                                    else outerHTML = msg.element.outerHTML;

                                    msgJson[i] = {
                                                      "type"    : msg.type
                                                    , "element" : splitLine(outerHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'), 30)
                                                    , "msg"     : msg.msg
                                                    , "code"    : msg.code
                                                    , "rect"    : JSON.stringify( msg.element.getBoundingClientRect() )
                                                }
                                }   //End for loop

                                msgJson['title'] = document.title;
                                msgJson['address'] = document.location.href

                            })          //End HTMLCS.process

                            //console.log(msgJson);
                            return  msgJson;

                        }, data);       //End evaluate

                    break;
                    default:
                        console.log('Unknown standard.');
                        phantom.exit();
                    break;
                }

                // console.log(JSON.stringify(results));
                var htmlStr = outputToHtml(results);
                console.log(htmlStr);
                phantom.exit();
            }, 200);
        }//end if
    });//end
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import Router from 'react-router-dom/BrowserRouter';
import Route from 'react-router-dom/Route';
import Switch from 'react-router-dom/Switch';

import MainContainer from './components/MainContainer';
import MainNav from './components/MainNav';
import ModuleContainer from './components/ModuleContainer';
import { Front } from './components/Front';
import LoginCtrl from './components/Login';
import Settings from './components/Settings/Settings';

import getModuleRoutes from './moduleRoutes';
import initialReducers from './initialReducers';

const reducers = { ...initialReducers };

class Root extends Component {

  getChildContext() {
    return { addReducer: this.addReducer.bind(this) };
  }

  addReducer = (key, reducer) => {
    if (reducers[key] === undefined) {
      reducers[key] = reducer;
      this.props.store.replaceReducer(combineReducers({ ...reducers }));
      return true;
    }
    return false;
  }

  render() {
    const { logger, store, config, okapi, token, currentUser, currentPerms } = this.props;

    function Stripes(x) {
      Object.assign(this, x);
      this.hasPerm = (perm) => {
        if (!this.user.perms) {
          logger.log('perm', `not checking perm '${perm}': no user permissions yet`);
          return undefined;
        }
        logger.log('perm', `checking perm '${perm}': `, !!this.user.perms[perm]);
        return this.user.perms[perm] || false;
      };
    }

    const stripes = new Stripes({
      logger,
      store,
      config,
      okapi,
      user: {
        user: currentUser,
        perms: currentPerms,
      },
    });

    return (
      <Provider store={store}>
        <Router>
          { token != null ?
            <MainContainer>
              <MainNav stripes={stripes} />
              <ModuleContainer id="content">
                <Switch>
                  <Route exact path="/" component={Front} key="root" />
                  <Route exact path="/settings" render={() => <Settings stripes={stripes} />} />
                  {getModuleRoutes(stripes)}
                  <Route
                    component={() =>

Uh-oh!

This route does not exist.

}
                  />
                </Switch>
              </ModuleContainer>
            </MainContainer> :
            <LoginCtrl />
          }
        </Router>
      </Provider>
    );
  }
}

Root.childContextTypes = {
  addReducer: PropTypes.func,
};

Root.propTypes = {
  store: PropTypes.shape({
    subscribe: PropTypes.func.isRequired,
    dispatch: PropTypes.func.isRequired,
    getState: PropTypes.func.isRequired,
    replaceReducer: PropTypes.func.isRequired,
  }),
  token: PropTypes.string,
  logger: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  currentPerms: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  currentUser: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  config: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  okapi: PropTypes.shape({
    url: PropTypes.string.isRequired,
    tenant: PropTypes.string.isRequired,
  }).isRequired,
};

function mapStateToProps(state) {
  return {
    token: state.okapi.token,
    currentUser: state.okapi.currentUser,
    currentPerms: state.okapi.currentPerms,
  };
}

export default connect(mapStateToProps)(Root);
<commit_msg>TEMPORARY: always give every user the 'module.organization.enabled' permission<commit_after>import React, { Component, PropTypes } from 'react';
import { combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import Router from 'react-router-dom/BrowserRouter';
import Route from 'react-router-dom/Route';
import Switch from 'react-router-dom/Switch';

import MainContainer from './components/MainContainer';
import MainNav from './components/MainNav';
import ModuleContainer from './components/ModuleContainer';
import { Front } from './components/Front';
import LoginCtrl from './components/Login';
import Settings from './components/Settings/Settings';

import getModuleRoutes from './moduleRoutes';
import initialReducers from './initialReducers';

const reducers = { ...initialReducers };

class Root extends Component {

  getChildContext() {
    return { addReducer: this.addReducer.bind(this) };
  }

  addReducer = (key, reducer) => {
    if (reducers[key] === undefined) {
      reducers[key] = reducer;
      this.props.store.replaceReducer(combineReducers({ ...reducers }));
      return true;
    }
    return false;
  }

  render() {
    const { logger, store, config, okapi, token, currentUser, currentPerms } = this.props;

    function Stripes(x) {
      Object.assign(this, x);
      this.hasPerm = (perm) => {
        if (!this.user.perms) {
          logger.log('perm', `not checking perm '${perm}': no user permissions yet`);
          return undefined;
        }
        logger.log('perm', `checking perm '${perm}': `, !!this.user.perms[perm]);
        return this.user.perms[perm] || false;
      };
    }

    const stripes = new Stripes({
      logger,
      store,
      config,
      okapi,
      user: {
        user: currentUser,
        // ### Remove the special-case below when possible: see STRIPES-322
        perms: Object.assign({}, currentPerms, { 'module.organization.enabled': true })
      },
    });

    return (
      <Provider store={store}>
        <Router>
          { token != null ?
            <MainContainer>
              <MainNav stripes={stripes} />
              <ModuleContainer id="content">
                <Switch>
                  <Route exact path="/" component={Front} key="root" />
                  <Route exact path="/settings" render={() => <Settings stripes={stripes} />} />
                  {getModuleRoutes(stripes)}
                  <Route
                    component={() =>

Uh-oh!

This route does not exist.

}
                  />
                </Switch>
              </ModuleContainer>
            </MainContainer> :
            <LoginCtrl />
          }
        </Router>
      </Provider>
    );
  }
}

Root.childContextTypes = {
  addReducer: PropTypes.func,
};

Root.propTypes = {
  store: PropTypes.shape({
    subscribe: PropTypes.func.isRequired,
    dispatch: PropTypes.func.isRequired,
    getState: PropTypes.func.isRequired,
    replaceReducer: PropTypes.func.isRequired,
  }),
  token: PropTypes.string,
  logger: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  currentPerms: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  currentUser: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  config: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  okapi: PropTypes.shape({
    url: PropTypes.string.isRequired,
    tenant: PropTypes.string.isRequired,
  }).isRequired,
};

function mapStateToProps(state) {
  return {
    token: state.okapi.token,
    currentUser: state.okapi.currentUser,
    currentPerms: state.okapi.currentPerms,
  };
}

export default connect(mapStateToProps)(Root);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import classNames from 'classnames';
const propTypesTabs = {
  	cls:React.PropTypes.string,
  	nav:React.PropTypes.string,
  	cont:React.PropTypes.string,
  	suffix:React.PropTypes.string,
  	defaultActiveKey:React.PropTypes.string
};
const defaultPropsTabs = {
	cls:'cls',
	nav:'simple',
	cont:'simple',
	navsuffix:'-tabs-nav',
	contsuffix:'-tabs-content',
	defaultActiveKey:"1",
	count:null //记录子节点个数
};
class Tabs extends Component {
	constructor(props) {
		super(props);
		this.state = {
			content:'',
			activeKey:this.props.defaultActiveKey
		};
		this.formatChildren = this.formatChildren.bind(this);
		this.clickHandler = this.clickHandler.bind(this);
		this.ruleSelector = this.ruleSelector.bind(this);
	}
	ruleSelector(n) {
		let count = (n-1)*100+'%';
        document.querySelector('.bee-tabs-tab-child').style.transform=`translate3d(${count},0,0)`
    }
	clickHandler(e){
		this.setState({
			activeKey:e.currentTarget.dataset.id
		})
		this.ruleSelector(e.currentTarget.dataset.id)
		this.formatChildren(e.currentTarget.dataset.id);
	}
	formatChildren(v){
		let arr = this.props.children;
		let width = 100/Number(this.props.children.length)+'%';
		this.setState({
			count:arr.length
		})
		let stateActiveKey = v||this.state.activeKey;
		let nav = this.props.navtype||this.props.nav,
			cont = this.props.contenttype||this.props.cont,
			clsname = '';
		clsname = `${nav}${this.props.navsuffix} ${cont}${this.props.contsuffix}`;

		const navArr = [];
		const contentArr = [];
		arr.forEach((e)=>{
			let key  = 	e.key,
				tab = e.props.tab,
				children = e.props.children,
				tab_active =classNames('bee-tabs-tab',{['bee-tabs-tab-active']:(e.key==stateActiveKey)}),
				cont_active =classNames('bee-content',{['bee-content-active']:(e.key==stateActiveKey)});
			navArr.push(
{tab}
)
			contentArr.push(
{children}
)
		});
		const content =  (

					{navArr}

					{contentArr}

		)
		this.setState({
			content:content
		})
	}
	componentDidMount() {
		this.formatChildren();
	}
	render(){
		return(

			{this.state.content}

		)
	}
}
Tabs.propTypes = propTypesTabs;
Tabs.defaultProps = defaultPropsTabs;
export default Tabs;<commit_msg>将之前的均分改为min-width:90px<commit_after>import React, { Component } from 'react';
import classNames from 'classnames';
const propTypesTabs = {
  	cls:React.PropTypes.string,
  	nav:React.PropTypes.string,
  	cont:React.PropTypes.string,
  	suffix:React.PropTypes.string,
  	defaultActiveKey:React.PropTypes.string
};
const defaultPropsTabs = {
	cls:'cls',
	nav:'simple',
	cont:'simple',
	navsuffix:'-tabs-nav',
	contsuffix:'-tabs-content',
	defaultActiveKey:"1",
	count:null
};
class Tabs extends Component {
	constructor(props) {
		super(props);
		this.state = {
			content:'',
			activeKey:this.props.defaultActiveKey
		};
		this.formatChildren = this.formatChildren.bind(this);
		this.clickHandler = this.clickHandler.bind(this);
		this.ruleSelector = this.ruleSelector.bind(this);
	}
	ruleSelector(n) {
		let count = (n-1)*100+'%';
        document.querySelector('.bee-tabs-tab-child').style.transform=`translate3d(${count},0,0)`
    }
	clickHandler(e){
		this.setState({
			activeKey:e.currentTarget.dataset.id
		})
		this.ruleSelector(e.currentTarget.dataset.id)
		this.formatChildren(e.currentTarget.dataset.id);
	}
	formatChildren(v){
		let arr = this.props.children;
		//let width = 100/Number(this.props.children.length)+'%';
		let minWidth = "90px";
		this.setState({
			count:arr.length
		})
		let stateActiveKey = v||this.state.activeKey;
		let nav = this.props.navtype||this.props.nav,
			cont = this.props.contenttype||this.props.cont,
			clsname = '';
		clsname = `${nav}${this.props.navsuffix} ${cont}${this.props.contsuffix}`;

		const navArr = [];
		const contentArr = [];
		arr.forEach((e)=>{
			let key  = 	e.key,
				tab = e.props.tab,
				children = e.props.children,
				tab_active =classNames('bee-tabs-tab',{['bee-tabs-tab-active']:(e.key==stateActiveKey)}),
				cont_active =classNames('bee-content',{['bee-content-active']:(e.key==stateActiveKey)});
			navArr.push(
{tab}
)
			contentArr.push(
{children}
)
		});
		const content =  (

					{navArr}

					{contentArr}

		)
		this.setState({
			content:content
		})
	}
	componentDidMount() {
		this.formatChildren();
	}
	render(){
		return(

			{this.state.content}

		)
	}
}
Tabs.propTypes = propTypesTabs;
Tabs.defaultProps = defaultPropsTabs;
export default Tabs;<|endoftext|>


<commit_before>function Task(taskFn, awaitFn) {
	if (typeof taskFn !== 'function')
		throw new TypeError("Invalid type of parameter 'taskFn'!");
	this.thisTaskFn_ = taskFn;
	this.taskArgs_ = Array.prototype.slice.call(arguments, 2, arguments.length);
	this.nextTask_ = null;
	this.awaiting_ = (typeof awaitFn == 'function') ? awaitFn : null;

	this.context_ = {};
	this.throuthContext_ = false;
	this.taskResult_ = {};

	this.state_ = null;
	this.timeout_ = null;
	this.timeoutObject_ = null;

	this.throuthTimeout_ = false;
}
Task.prototype = {
	get Result() {
		return this.taskResult_;
	},
	set Result(val) {
		this.taskResult_ = val;
	},
	get NextTask() {
		return this.nextTask_;
	},
	SetTimeout : function (val) {
		if (val == null || val === undefined)
			this.timeout_ = 0;
		else
			this.timeout_ = val;
		return this;
	},
	get ThrouthTimeout(){
		return this.throuthTimeout_;
	},
	set ThrouthTimeout(val) {
		if (typeof val != 'boolean') throw new TypeError('Setter of \'ThrouthTimeout\': setting value is not a Boolean type');
		this.throuthTimeout_ = val;
	},
	get State(){
		return this.state_;
	},
	get ThrouthContext() {
		return this.throuthContext_;
	},
	set ThrouthContext(val) {
		if (typeof val != 'boolean') throw new TypeError('Setter of \'ThrouthContext\': setting value is not a Boolean type');
		this.throuthContext_ = val;
	},
	get Context() {
		return this.context_;
	},
	set Context(val) {
		this.context_ = val;
	},
	get Args() {
		return this.taskArgs_;
	}
}
Task.prototype.Next = function (error) {
	if (this.state_ !== Task.TaskState.TimeIsOut && this.state_ !== Task.TaskState.Faulted && this.state_ !== Task.TaskState.Failed) {
		this.state_ = Task.TaskState.Completed;
	}
	if (this.timeoutObject_ != null && this.timeoutObject_ !== undefined)
		clearTimeout(this.timeoutObject_);
	this.thisTaskFn_ = undefined;
	this.taskArgs_.splice(0, this.taskArgs_.length);

	var lArgs = Array.prototype.slice.call(arguments, 1, arguments.length);

	if (error != null && error !== undefined) {
		if (this.awaiting_ !== undefined && this.awaiting_ != null) {
			this.awaiting_.call(null, error, this.Context);
			//this.awaiting_ = null;
			//this.nextTask_ = null;
		}
	}
	else if (this.state_ === Task.TaskState.TimeIsOut) {
		var lError = new TaskTimeoutError("Timeout expired!", this.timeout_);
		if (this.awaiting_ !== undefined && this.awaiting_ != null) {
			this.awaiting_.call(null, lError, this.Context);
			//this.awaiting_ = null;
			//this.nextTask_ = null;
		}
	}
	else  {
		if (this.nextTask_ == null || this.nextTask_ === undefined) {
			this.awaiting_.apply(null, [null, this.Context].concat(lArgs));
			//this.awaiting_ = null;
		}
		else {
			if (this.ThrouthContext === true) {// сквозной контекст
				this.nextTask_.ThrouthContext = true;
				this.nextTask_.Context = this.Context;
			}
			if (this.ThrouthTimeout === true) {// сквозной таймаут
				this.nextTask_.ThrouthTimeout = true;
				this.nextTask_.SetTimeout(this.timeout_);
			}
			this.nextTask_.Run.apply(this.nextTask_, [this.awaiting_].concat(lArgs));
		}
	}
	this.awaiting_ = null;
	this.nextTask_ = null;
}
Task.prototype.Run = function (runArg) {
	if (this.state_ === Task.TaskState.Completed)
		throw new Error('The task can not be started because it already completed.');

	var lSpecialArg = false;
	if (typeof runArg == 'function')
	{
		this.awaiting_ = runArg;
		lSpecialArg = true;
	}
	else if (typeof runArg == 'number')
	{
		this.SetTimeout(runArg);
		lSpecialArg = true;
	}

	this.Context.task = this;

	var lArgs = Array.prototype.slice.call(arguments, lSpecialArg == true ? 1 : 0, arguments.length);
	var lArguments = [ this.Context ].concat(Array.prototype.slice.call(this.taskArgs_, 0, this.taskArgs_.length)).concat(lArgs);
	try {
		this.state_ = Task.TaskState.Runing;
		if (this.timeout_ !== undefined && this.timeout_ != null &&
			typeof this.timeout_ == 'number' && this.timeout_ > 0) {
		    var lTimeoutHandler = (function() {
		        if (this.state_ === Task.TaskState.Completed) return;
		        if (this.state_ === Task.TaskState.Runing) {
		            this.state_ = Task.TaskState.TimeIsOut;
		        }
		    }).bind(this);
				this.timeoutObject_ = setTimeout(lTimeoutHandler, this.timeout_ + 3);
		}
		this.thisTaskFn_.apply(this, lArguments);
	}
	catch (error) {
		this.state_ = Task.TaskState.Faulted;
		this.Next(error);
	}
	finally {
		return this;
	}
}
Task.prototype.Continue = function (nextTask) {
	if (nextTask == null || nextTask === undefined) return this;

	var lNewNextTask = null;
	if (typeof nextTask == 'function') {
		lNewNextTask = new Task(nextTask, this.awaiting_);
		Array.prototype.push.apply(lNewNextTask.Args, Array.prototype.slice.call(arguments, 1, arguments.length));
	}
	else if (nextTask instanceof Task)
		lNewNextTask = nextTask;

	var lOldNextTask = null;
	if (this.nextTask_ != null && this.nextTask_ !== undefined) {
		 lOldNextTask = this.nextTask_;
	}

	this.nextTask_ = lNewNextTask;
	this.nextTask_.Continue(lOldNextTask);

	return this.nextTask_;
}
Task.prototype.AwaitingEnd = function (awaitFn, throuth) {
	this.awaiting_ = awaitFn;
	if (throuth) {
		var lTask = this.nextTask_;
		while (lTask !== undefined && lTask != null) {
			lTask = lTask.NextTask;
			lTask.AwaitingEnd(this.awaiting_);
		}
	}
}

Task.Chain = function (tasks, awaiting) {
	var lFirstTask = null;
	var lCurrTask = null;
	for (var task in tasks) {
		if (typeof task == 'function') {
			lCurrTask = new Task(task);
		}
		else if (task instanceof Task) {
			lCurrTask = task;
		}

		if (lFirstTask == null) {
			lFirstTask = lCurrTask;
			lFirstTask.AwaitingEnd(awaiting);
		}
		lCurrTask = lCurrTask.Continue(task);
	}
	return lFirstTask;
}
Task.Run = function (tasks, awaiting, timeout, throuthTimeout){
	var lFirstTask = Task.Chain(tasks, awaiting);
	lFirstTask.ThrouthTimeout = throuthTimeout;
	lFirstTask.Run(timeout);
}

function TaskState() { }
TaskState.prototype = {
	get Runing(){ return 1; },
	get Faulted(){ return 2; },
	get Failed() { return 3; },
	get Completed(){ return 4; },
	get TimeIsOut() { return 5; }
}

function TaskTimeoutError(description, timeout){
	Error.call(this);
	this.name = "TaskTimeoutError";
	this.timeout_ = timeout;
	this.message = "Task timeout expired.";
	this.description_ = description;

	if (Error.captureStackTrace) {
		Error.captureStackTrace(this, TaskTimeoutError);
	} else {
		this.stack = (new Error()).stack;
	}
}
TaskTimeoutError.prototype = Object.create(Error.prototype);
TaskTimeoutError.prototype = {
	get ExpiredTimeout(){
		return this.timeout_;
	},
	get Description(){
		return this.description_;
	}
}
Task.TaskState = new TaskState();

module.exports = function (){
	this.Task = Task;
	this.TaskTimeoutError = TaskTimeoutError;
}
<commit_msg>optimize code<commit_after>function Task(taskFn, awaitFn) {
	if (typeof taskFn !== 'function')
		throw new TypeError("Invalid type of parameter 'taskFn'!");
	this.thisTaskFn_ = taskFn;
	this.taskArgs_ = Array.prototype.slice.call(arguments, 2, arguments.length);
	this.nextTask_ = null;
	this.awaiting_ = (typeof awaitFn == 'function') ? awaitFn : null;

	this.context_ = {};
	this.throuthContext_ = false;
	this.taskResult_ = {};

	this.state_ = null;
	this.timeout_ = null;
	this.timeoutObject_ = null;

	this.throuthTimeout_ = false;
}
Task.prototype = {
	get Result() {
		return this.taskResult_;
	},
	set Result(val) {
		this.taskResult_ = val;
	},
	get NextTask() {
		return this.nextTask_;
	},
	SetTimeout : function (val) {
		if (val == null || val === undefined)
			this.timeout_ = 0;
		else
			this.timeout_ = val;
		return this;
	},
	get ThrouthTimeout(){
		return this.throuthTimeout_;
	},
	set ThrouthTimeout(val) {
		if (typeof val != 'boolean') throw new TypeError('Setter of \'ThrouthTimeout\': setting value is not a Boolean type');
		this.throuthTimeout_ = val;
	},
	get State(){
		return this.state_;
	},
	get ThrouthContext() {
		return this.throuthContext_;
	},
	set ThrouthContext(val) {
		if (typeof val != 'boolean') throw new TypeError('Setter of \'ThrouthContext\': setting value is not a Boolean type');
		this.throuthContext_ = val;
	},
	get Context() {
		return this.context_;
	},
	set Context(val) {
		this.context_ = val;
	},
	get Args() {
		return this.taskArgs_;
	}
}
Task.prototype.Next = function (error) {
	if (this.state_ !== Task.TaskState.TimeIsOut && this.state_ !== Task.TaskState.Faulted && this.state_ !== Task.TaskState.Failed) {
		this.state_ = Task.TaskState.Completed;
	}
	if (this.timeoutObject_ != null && this.timeoutObject_ !== undefined)
		clearTimeout(this.timeoutObject_);
	this.thisTaskFn_ = undefined;
	this.taskArgs_.splice(0, this.taskArgs_.length);

	var lArgs = Array.prototype.slice.call(arguments, 1, arguments.length);

	if (error != null && error !== undefined) {
		if (this.awaiting_ !== undefined && this.awaiting_ != null) {
			this.awaiting_.call(null, error, this.Context);
			//this.awaiting_ = null;
			//this.nextTask_ = null;
		}
	}
	else if (this.state_ === Task.TaskState.TimeIsOut) {
		var lError = new TaskTimeoutError("Timeout expired!", this.timeout_);
		if (this.awaiting_ !== undefined && this.awaiting_ != null) {
			this.awaiting_.call(null, lError, this.Context);
			//this.awaiting_ = null;
			//this.nextTask_ = null;
		}
	}
	else  {
		if (this.nextTask_ == null || this.nextTask_ === undefined) {
			this.awaiting_.apply(null, [null, this.Context].concat(lArgs));
			//this.awaiting_ = null;
		}
		else {
			if (this.ThrouthContext === true) {// сквозной контекст
				this.nextTask_.ThrouthContext = true;
				this.nextTask_.Context = this.Context;
			}
			if (this.ThrouthTimeout === true) {// сквозной таймаут
				this.nextTask_.ThrouthTimeout = true;
				this.nextTask_.SetTimeout(this.timeout_);
			}
			this.nextTask_.Run.apply(this.nextTask_, [this.awaiting_].concat(lArgs));
		}
	}
	this.awaiting_ = null;
	this.nextTask_ = null;
}
Task.prototype.Run = function (runArg) {
	if (this.state_ === Task.TaskState.Completed)
		throw new Error('The task can not be started because it already completed.');

	var lSpecialArg = false;
	if (typeof runArg == 'function')
	{
		this.awaiting_ = runArg;
		lSpecialArg = true;
	}
	else if (typeof runArg == 'number')
	{
		this.SetTimeout(runArg);
		lSpecialArg = true;
	}

	this.Context.task = this;

	var lArgs = Array.prototype.slice.call(arguments, lSpecialArg == true ? 1 : 0, arguments.length);
	var lArguments = [ this.Context ].concat(Array.prototype.slice.call(this.taskArgs_, 0, this.taskArgs_.length)).concat(lArgs);
	try {
		this.state_ = Task.TaskState.Runing;
		if (this.timeout_ && this.timeout_ > 0) {
		    var lTimeoutHandler = (function() {
		        if (this.state_ === Task.TaskState.Completed) return;
		        if (this.state_ === Task.TaskState.Runing) {
		            this.state_ = Task.TaskState.TimeIsOut;
		        }
		    }).bind(this);
				this.timeoutObject_ = setTimeout(lTimeoutHandler, this.timeout_ + 3);
		}
		this.thisTaskFn_.apply(this, lArguments);
	}
	catch (error) {
		this.state_ = Task.TaskState.Faulted;
		this.Next(error);
	}
	finally {
		return this;
	}
}
Task.prototype.Continue = function (nextTask) {
	if (nextTask == null || nextTask === undefined) return this;

	var lNewNextTask = null;
	if (typeof nextTask == 'function') {
		lNewNextTask = new Task(nextTask, this.awaiting_);
		Array.prototype.push.apply(lNewNextTask.Args, Array.prototype.slice.call(arguments, 1, arguments.length));
	}
	else if (nextTask instanceof Task)
		lNewNextTask = nextTask;

	var lOldNextTask = null;
	if (this.nextTask_ != null && this.nextTask_ !== undefined) {
		 lOldNextTask = this.nextTask_;
	}

	this.nextTask_ = lNewNextTask;
	this.nextTask_.Continue(lOldNextTask);

	return this.nextTask_;
}
Task.prototype.AwaitingEnd = function (awaitFn, throuth) {
	this.awaiting_ = awaitFn;
	if (throuth) {
		var lTask = this.nextTask_;
		while (lTask !== undefined && lTask != null) {
			lTask = lTask.NextTask;
			lTask.AwaitingEnd(this.awaiting_);
		}
	}
}

Task.Chain = function (tasks, awaiting) {
	var lFirstTask = null;
	var lCurrTask = null;
	for (var task in tasks) {
		if (typeof task == 'function') {
			lCurrTask = new Task(task);
		}
		else if (task instanceof Task) {
			lCurrTask = task;
		}

		if (lFirstTask == null) {
			lFirstTask = lCurrTask;
			lFirstTask.AwaitingEnd(awaiting);
		}
		lCurrTask = lCurrTask.Continue(task);
	}
	return lFirstTask;
}
Task.Run = function (tasks, awaiting, timeout, throuthTimeout){
	var lFirstTask = Task.Chain(tasks, awaiting);
	lFirstTask.ThrouthTimeout = throuthTimeout;
	lFirstTask.Run(timeout);
}

function TaskState() { }
TaskState.prototype = {
	get Runing(){ return 1; },
	get Faulted(){ return 2; },
	get Failed() { return 3; },
	get Completed(){ return 4; },
	get TimeIsOut() { return 5; }
}

function TaskTimeoutError(description, timeout){
	Error.call(this);
	this.name = "TaskTimeoutError";
	this.timeout_ = timeout;
	this.message = "Task timeout expired.";
	this.description_ = description;

	if (Error.captureStackTrace) {
		Error.captureStackTrace(this, TaskTimeoutError);
	} else {
		this.stack = (new Error()).stack;
	}
}
TaskTimeoutError.prototype = Object.create(Error.prototype);
TaskTimeoutError.prototype = {
	get ExpiredTimeout(){
		return this.timeout_;
	},
	get Description(){
		return this.description_;
	}
}
Task.TaskState = new TaskState();

module.exports = function (){
	this.Task = Task;
	this.TaskTimeoutError = TaskTimeoutError;
}
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import { Link } from 'react-router';
import { fromMongoDate, formatJSON } from './utils';
import { api, stateIDs, stateToClass } from './Api';

export default React.createClass({

  propTypes: {
    params: React.PropTypes.object,
  },

  getInitialState() {
    return {
      task: null,
      application_containers: [],
    };
  },

  componentDidMount() {
    const id = this.props.params.id;

    const taskPayload = {
      aggregate: [
        { $match: { _id: id } },
      ],
    };

    api.getTasks(taskPayload)
      .then(response => this.setState({ task: _.get(response, 'tasks[0]', {}) }));

    const acPayload = {
      aggregate: [
        {
          $match: {
            'task_id.0': id,
            state: { $ne: -1 },
          },
        },
        {
          $project: {
            _id: 1,
            state: 1,
            username: 1,
            created_at: 1,
          },
        },
        { $sort: { created_at: -1 } },
      ],
    };

    api.getApplicationContainers(acPayload)
      .then(({ application_containers }) => this.setState({ application_containers }));
  },

  render() {
    if (this.state.task == null) {
      return (
Loading Task
);
    }

    if (_.isEmpty(this.state.task)) {
      return (
Data not available
);
    }

    return (

Task

              ID
              Username
              State
              Created at

            {this.state.application_containers.map((container, i) =>

                <Link to={`/application-containers/${container._id}`}>{container._id}</Link>
                {container.username}
                {stateIDs[container.state]}
                {fromMongoDate(container.created_at)}

            )}

Task

          {formatJSON(this.state.task)}

    );
  },

});
<commit_msg>fixed wrong headings<commit_after>import React from 'react';
import _ from 'lodash';
import { Link } from 'react-router';
import { fromMongoDate, formatJSON } from './utils';
import { api, stateIDs, stateToClass } from './Api';

export default React.createClass({

  propTypes: {
    params: React.PropTypes.object,
  },

  getInitialState() {
    return {
      task: null,
      application_containers: [],
    };
  },

  componentDidMount() {
    const id = this.props.params.id;

    const taskPayload = {
      aggregate: [
        { $match: { _id: id } },
      ],
    };

    api.getTasks(taskPayload)
      .then(response => this.setState({ task: _.get(response, 'tasks[0]', {}) }));

    const acPayload = {
      aggregate: [
        {
          $match: {
            'task_id.0': id,
            state: { $ne: -1 },
          },
        },
        {
          $project: {
            _id: 1,
            state: 1,
            username: 1,
            created_at: 1,
          },
        },
        { $sort: { created_at: -1 } },
      ],
    };

    api.getApplicationContainers(acPayload)
      .then(({ application_containers }) => this.setState({ application_containers }));
  },

  render() {
    if (this.state.task == null) {
      return (
Loading Task
);
    }

    if (_.isEmpty(this.state.task)) {
      return (
Data not available
);
    }

    return (

Application Containers

              ID
              Username
              State
              Created at

            {this.state.application_containers.map((container, i) =>

                <Link to={`/application-containers/${container._id}`}>{container._id}</Link>
                {container.username}
                {stateIDs[container.state]}
                {fromMongoDate(container.created_at)}

            )}

Task

          {formatJSON(this.state.task)}

    );
  },

});
<|endoftext|>


<commit_before>var request = require('request');
var RSVP = require('rsvp');
var _ = require('lodash');
var qs = require('querystring');
var reOrder = require('./../lib/reOrder.js');
var cache = require('./q-cache');

var cacheTime = (60 * 1000); //cache specified in minutes
var telQCachingEnabled = true;

function TelQ() {
    'use strict';

    function get(options) {

        function qGetHttp(resolve, reject) {
            options.expires = (options.expires || 0) * cacheTime;

            var sanitizedOptions = checkRequiredInputs(options);

            if (!sanitizedOptions.url) {
                reject(new Error('No url or source provided.'));
            }

            var params = (sanitizedOptions.params) ? reOrder(sanitizedOptions.params) : null,
                url = params ? sanitizedOptions.url + '?' + qs.stringify(params) : sanitizedOptions.url;

            function requestCallback(error, response, body) {
                if (!error && response.statusCode === 200) {

                    var result = typeof body === 'string' ? JSON.parse(body) : body;

                    if (telQCachingEnabled && options.expires > 0) {
                        cache.add({
                            id: url,
                            value: [result, response],
                            expires: new Date(new Date().getTime() + options.expires)
                        });
                    }

                    resolve(result, response);
                } else {
                    reject(error);
                }
            }

            function returnIfCached(cachedItem) {
                if (cachedItem.id === url) {
                    resolve(cachedItem.value[0], cachedItem.value[1]);
                }
            }

            //memoize short circuit.
            if (telQCachingEnabled) {
                _.each(cache.list(), returnIfCached);
            }

            request(url, requestCallback);
        }

        return new RSVP.Promise(qGetHttp);
    }

    function post(options) {

        function qGetHttp(resolve, reject) {

            var sanitizedOptions = checkRequiredInputs(options);

            if (!sanitizedOptions.url) {
                reject(new Error('No url or source provided.'));
            }

            var params = (sanitizedOptions.params) ? reOrder(sanitizedOptions.params) : null,
                url = params ? sanitizedOptions.url + '?' + qs.stringify(params) : sanitizedOptions.url;

            options.url = sanitizedOptions.url;
            options.params = sanitizedOptions.params;

            function requestCallback(error, response, body) {
                if (!error && response.statusCode === 200) {
                    resolve(body, response);
                } else {
                    reject(error);
                }
            }

            request.post(options, requestCallback);

        }

        return new RSVP.Promise(qGetHttp);
    }

    function checkRequiredInputs(options) {
        var _url = options.url || options.source,
            _params = options.params || options.query;

        return {
            url: _url,
            params: _params
        };
    }

    function use(plugin, options) {
        if (plugin && plugin instanceof Function) {
            return plugin(q, options);
        }

        throw 'Must provide TelQ plugin as instance of Function';
    }

    var q = _.assign(this, RSVP);

    //RSVP.configure('onerror', function(reason){ console.assert(false,reason)}); //Error handling?

    q.use = use;
    q.post = post;
    q.get = get;
    return q;
}

module.exports = new TelQ();
<commit_msg>updated dependencies<commit_after>var request = require('request');
var RSVP = require('rsvp');
var _ = require('lodash');
var qs = require('querystring');
var reOrder = require('./../lib/reOrder.js');
var cache = require('./q-cache');

var cacheTime = (60 * 1000); //cache specified in minutes
var telQCachingEnabled = true;

function TelQ() {
  'use strict';

  function get(options) {

    function qGetHttp(resolve, reject) {
      options.expires = (options.expires || 0) * cacheTime;

      var sanitizedOptions = checkRequiredInputs(options);

      if (!sanitizedOptions.url) {
        reject(new Error('No url or source provided.'));
      }

      var params = (sanitizedOptions.params) ? reOrder(sanitizedOptions.params) : null,
        url = params ? sanitizedOptions.url + '?' + qs.stringify(params) : sanitizedOptions.url;

      function requestCallback(error, response, body) {
        if (!error && response.statusCode === 200) {

          var result = typeof body === 'string' ? JSON.parse(body) : body;

          if (telQCachingEnabled && options.expires > 0) {
            cache.add({
              id: url,
              value: [result, response],
              expires: new Date(new Date().getTime() + options.expires)
            });
          }

          resolve(result, response);
        } else {
          reject(error);
        }
      }

      function returnIfCached(cachedItem) {
        if (cachedItem.id === url) {
          resolve(cachedItem.value[0], cachedItem.value[1]);
        }
      }

      //memoize short circuit.
      if (telQCachingEnabled) {
        _.each(cache.list(), returnIfCached);
      }

      request(url, requestCallback);
    }

    return new RSVP.Promise(qGetHttp);
  }

  function post(options) {

    function qGetHttp(resolve, reject) {

      var sanitizedOptions = checkRequiredInputs(options);

      if (!sanitizedOptions.url) {
        reject(new Error('No url or source provided.'));
      }

      var params = (sanitizedOptions.params) ? reOrder(sanitizedOptions.params) : null,
        url = params ? sanitizedOptions.url + '?' + qs.stringify(params) : sanitizedOptions.url;

      options.url = sanitizedOptions.url;
      options.params = sanitizedOptions.params;

      function requestCallback(error, response, body) {
        if (!error && response.statusCode === 200) {
          resolve(body, response);
        } else {
          reject(error);
        }
      }

      request.post(options, requestCallback);

    }

    return new RSVP.Promise(qGetHttp);
  }

  function checkRequiredInputs(options) {
    var _url = options.url || options.source,
      _params = options.params || options.query;

    return {
      url: _url,
      params: _params
    };
  }

  function use(plugin, options) {
    if (plugin && plugin instanceof Function) {
      return plugin(q, options);
    }

    throw 'Must provide TelQ plugin as instance of Function';
  }

  var q = _.assign(this, RSVP);

  //RSVP.configure('onerror', function(reason){ console.assert(false,reason)}); //Error handling?

  q.use = use;
  q.post = post;
  q.get = get;
  return q;
}

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


<commit_before>var Util = {
  // '19:00'
  formatTime: function(date) {
    return date.toTimeString().substring(0, 5);
  },

  // 'Wed Jul 28'
  formatDate: function(date) {
    return date.toDateString().substring(0, 10);
  },

  trimLine: function(str) {
    return str.substring(0, 30);
  },

  // 'Wed Jul 28 19:00'
  getMessageDateTime: function(message) {
    var date = new Date(+message.internalDate);
    return Util.formatDate(date) + ', ' + Util.formatTime(date);
  },

  getMessageHeader: function(message, headerName) {
    var headers = message.payload.headers;
    for (var i = 0; i < headers.length; i++) {
      if (headers[i].name === headerName) {
        return headers[i].value;
      }
    }
    return '';
  },

  getMessageFromHeader: function(message) {
    var from = this.getMessageHeader(message, 'From');
    var bracketIndex = from.indexOf('<');

    // If the only thing in the from header is '<email>', keep it.
    if (bracketIndex > 0) {
      return from.substring(0, bracketIndex).trim();
    } else {
      return from;
    }
  },

  getMessageSubjectHeader: function(message) {
    return this.getMessageHeader(message, 'Subject') || '(no subject)';
  },

  // Removes all tags, comments, scripts, etc.
  // Source: http://stackoverflow.com/a/430240
  stripHTMLTags: function(html) {
    if (!html)  return '';
    if (!this.stripHTMLTagRegex) {
      var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
      Util.stripHTMLTagRegex = new RegExp(
          '<(?:' +
          // Comment body.
          '!--(?:(?:[^>]|[^-]-?>)*--|-?)' +
          // Special "raw text" elements whose content should be elided.
          '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' +
          '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' +
          // Regular name
          '|[/!]?[a-z]' + tagBody +
          ')>',
          'gi');
    }
    var oldHtml;
    do {
      oldHtml = html;
      html = html.replace(Util.stripHTMLTagRegex, '');
    } while (html !== oldHtml);
    return html.replace(/</g, '<');
  },

  // Decodes HTML entities into proper characters
  // Source: https://gist.github.com/liamato/bb93806c921d7767aa3d
  htmlEntities: { quot: 34, amp: 38, lt: 60, gt: 62, nbsp: 160, copy: 169, reg: 174, deg: 176, frasl: 47, trade: 8482, euro: 8364, Agrave: 192, Aacute: 193, Acirc: 194, Atilde: 195, Auml: 196, Aring: 197, AElig: 198, Ccedil: 199, Egrave: 200, Eacute: 201, Ecirc: 202, Euml: 203, Igrave: 204, Iacute: 205, Icirc: 206, Iuml: 207, ETH: 208, Ntilde: 209, Ograve: 210, Oacute: 211, Ocirc: 212, Otilde: 213, Ouml: 214, times: 215, Oslash: 216, Ugrave: 217, Uacute: 218, Ucirc: 219, Uuml: 220, Yacute: 221, THORN: 222, szlig: 223, agrave: 224, aacute: 225, acirc: 226, atilde: 227, auml: 228, aring: 229, aelig: 230, ccedil: 231, egrave: 232, eacute: 233, ecirc: 234, euml: 235, igrave: 236, iacute: 237, icirc: 238, iuml: 239, eth: 240, ntilde: 241, ograve: 242, oacute: 243, ocirc: 244, otilde: 245, ouml: 246, divide: 247, oslash: 248, ugrave: 249, uacute: 250, ucirc: 251, uuml: 252, yacute: 253, thorn: 254, yuml: 255, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, permil: 8240, lsaquo: 8249, rsaquo: 8250, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830, oline: 8254, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, hellip: 133, ndash: 150, mdash: 151, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, brkbar: 166, sect: 167, uml: 168, die: 168, ordf: 170, laquo: 171, not: 172, shy: 173, macr: 175, hibar: 175, plusmn: 177, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, sup1: 185, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, Alpha: 913, alpha: 945, Beta: 914, beta: 946, Gamma: 915, gamma: 947, Delta: 916, delta: 948, Epsilon: 917, epsilon: 949, Zeta: 918, zeta: 950, Eta: 919, eta: 951, Theta: 920, theta: 952, Iota: 921, iota: 953, Kappa: 922, kappa: 954, Lambda: 923, lambda: 955, Mu: 924, mu: 956, Nu: 925, nu: 957, Xi: 926, xi: 958, Omicron: 927, omicron: 959, Pi: 928, pi: 960, Rho: 929, rho: 961, Sigma: 931, sigma: 963, Tau: 932, tau: 964, Upsilon: 933, upsilon: 965, Phi: 934, phi: 966, Chi: 935, chi: 967, Psi: 936, psi: 968, Omega: 937, omega: 969 },
  decodeHTMLEntities: function(html) {
    if (!html) return '';
    return html.replace(/&#?(\w+);/g, function(match, dec) {
      return String.fromCharCode(isNaN(dec) ? Util.htmlEntities[dec] || dec : dec);
    });
  },

  // Extracts text from HTML with some attempt to improve formatting
  decodeHTML: function(html) {
    html = Util.decodeHTMLEntities(Util.stripHTMLTags(html));
    // Collapse whitespace. Allow paragraph breaks
    return html.replace(/\s\s+/g, function(match) {
      var index = match.indexOf('\n');
      if (index === -1) return ' ';
      return match.lastIndexOf('\n') === index ? '\n' : '\n\n';
    });
  },

  // Decodes base64
  // Credit: http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
  base64keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "abcdefghijklmnopqrstuvwxyz" +
                "0123456789-_=",
  decode64: function(input, maxlength) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    maxlength = maxlength ? (maxlength * 4 + 2) / 3 : input.length;
    maxlength = maxlength < input.length ? maxlength : input.length;

    do {
      enc1 = this.base64keyStr.indexOf(input.charAt(i++));
      enc2 = this.base64keyStr.indexOf(input.charAt(i++));
      enc3 = this.base64keyStr.indexOf(input.charAt(i++));
      enc4 = this.base64keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";

    } while (i < maxlength);

    /* Make the string proper UTF-8 */
    return decodeURIComponent(escape(output));
  },

  /* Recursively grabs the first text part of multipart messages
   * Prefers plaintext over html. */
  getMessageBody: function(message) {
    var body = null;
    if ('payload' in message) {
      if (!message.loaded) {
        return Util.decodeHTMLEntities(message.snippet);
      }
      body = Util.getMessageBody(message.payload);
      if (!body || !body.data) {
        return '';
      }
      var limit = Pebble.getActiveWatchInfo().platform == 'aplite' ? 768 : 0;
      body.data = Util.decode64(body.data, body.html ? 0 : limit);
      body.data = body.html ? Util.decodeHTML(body.data) : body.data;
      return body.html && limit ? body.data.substring(0, limit) : body.data;
    } else if (message.mimeType.substring(0, 4) == 'text' && message.body.data) {
      return { html: message.mimeType.slice(-4) == 'html', data: message.body.data };
    } else if (message.mimeType.substring(0, 9) == 'multipart') {
      for (var i = 0; i < message.parts.length; i++) {
        var part = Util.getMessageBody(message.parts[i]);
        if (part && !part.html) {
          return part;
        } else if (part && part.html && !body) {
          body = part;
        }
      }
    }
    return body;
  },

  getFriendlyLabelName: function(label) {
    if (label.type === 'system') {
      var match = /^CATEGORY_(.*)$/.exec(label.id);
      if (match) {
        return Util.capitalize(match[1]);
      } else {
        return Util.capitalize(label.name);
      }
    }
    return label.name;
  },

  capitalize: function(str) {
    if (str) {
      return str[0].toUpperCase() + str.substring(1).toLowerCase();
    }
    return '';
  },

  plural: function(number, text) {
    return number != 1 ? (text || 's') : '';
  },

  systemLabelSortComparator: function(a, b) {
    var priorities = {
      UNREAD: 1,
      STARRED: 2,
      IMPORTANT: 3,
      INBOX: 4,
      SPAM: 5,
      TRASH: 6
    };
    return (priorities[a.label.id] || 9) - (priorities[b.label.id] || 9);
  }
};

module.exports = Util;
<commit_msg>Cache decoded body and dump other parts<commit_after>var Util = {
  // '19:00'
  formatTime: function(date) {
    return date.toTimeString().substring(0, 5);
  },

  // 'Wed Jul 28'
  formatDate: function(date) {
    return date.toDateString().substring(0, 10);
  },

  trimLine: function(str) {
    return str.substring(0, 30);
  },

  // 'Wed Jul 28 19:00'
  getMessageDateTime: function(message) {
    var date = new Date(+message.internalDate);
    return Util.formatDate(date) + ', ' + Util.formatTime(date);
  },

  getMessageHeader: function(message, headerName) {
    var headers = message.payload.headers;
    for (var i = 0; i < headers.length; i++) {
      if (headers[i].name === headerName) {
        return headers[i].value;
      }
    }
    return '';
  },

  getMessageFromHeader: function(message) {
    var from = this.getMessageHeader(message, 'From');
    var bracketIndex = from.indexOf('<');

    // If the only thing in the from header is '<email>', keep it.
    if (bracketIndex > 0) {
      return from.substring(0, bracketIndex).trim();
    } else {
      return from;
    }
  },

  getMessageSubjectHeader: function(message) {
    return this.getMessageHeader(message, 'Subject') || '(no subject)';
  },

  // Removes all tags, comments, scripts, etc.
  // Source: http://stackoverflow.com/a/430240
  stripHTMLTags: function(html) {
    if (!html)  return '';
    if (!this.stripHTMLTagRegex) {
      var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
      Util.stripHTMLTagRegex = new RegExp(
          '<(?:' +
          // Comment body.
          '!--(?:(?:[^>]|[^-]-?>)*--|-?)' +
          // Special "raw text" elements whose content should be elided.
          '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' +
          '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' +
          // Regular name
          '|[/!]?[a-z]' + tagBody +
          ')>',
          'gi');
    }
    var oldHtml;
    do {
      oldHtml = html;
      html = html.replace(Util.stripHTMLTagRegex, '');
    } while (html !== oldHtml);
    return html.replace(/</g, '<');
  },

  // Decodes HTML entities into proper characters
  // Source: https://gist.github.com/liamato/bb93806c921d7767aa3d
  htmlEntities: { quot: 34, amp: 38, lt: 60, gt: 62, nbsp: 160, copy: 169, reg: 174, deg: 176, frasl: 47, trade: 8482, euro: 8364, Agrave: 192, Aacute: 193, Acirc: 194, Atilde: 195, Auml: 196, Aring: 197, AElig: 198, Ccedil: 199, Egrave: 200, Eacute: 201, Ecirc: 202, Euml: 203, Igrave: 204, Iacute: 205, Icirc: 206, Iuml: 207, ETH: 208, Ntilde: 209, Ograve: 210, Oacute: 211, Ocirc: 212, Otilde: 213, Ouml: 214, times: 215, Oslash: 216, Ugrave: 217, Uacute: 218, Ucirc: 219, Uuml: 220, Yacute: 221, THORN: 222, szlig: 223, agrave: 224, aacute: 225, acirc: 226, atilde: 227, auml: 228, aring: 229, aelig: 230, ccedil: 231, egrave: 232, eacute: 233, ecirc: 234, euml: 235, igrave: 236, iacute: 237, icirc: 238, iuml: 239, eth: 240, ntilde: 241, ograve: 242, oacute: 243, ocirc: 244, otilde: 245, ouml: 246, divide: 247, oslash: 248, ugrave: 249, uacute: 250, ucirc: 251, uuml: 252, yacute: 253, thorn: 254, yuml: 255, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, permil: 8240, lsaquo: 8249, rsaquo: 8250, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830, oline: 8254, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, hellip: 133, ndash: 150, mdash: 151, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, brkbar: 166, sect: 167, uml: 168, die: 168, ordf: 170, laquo: 171, not: 172, shy: 173, macr: 175, hibar: 175, plusmn: 177, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, sup1: 185, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, Alpha: 913, alpha: 945, Beta: 914, beta: 946, Gamma: 915, gamma: 947, Delta: 916, delta: 948, Epsilon: 917, epsilon: 949, Zeta: 918, zeta: 950, Eta: 919, eta: 951, Theta: 920, theta: 952, Iota: 921, iota: 953, Kappa: 922, kappa: 954, Lambda: 923, lambda: 955, Mu: 924, mu: 956, Nu: 925, nu: 957, Xi: 926, xi: 958, Omicron: 927, omicron: 959, Pi: 928, pi: 960, Rho: 929, rho: 961, Sigma: 931, sigma: 963, Tau: 932, tau: 964, Upsilon: 933, upsilon: 965, Phi: 934, phi: 966, Chi: 935, chi: 967, Psi: 936, psi: 968, Omega: 937, omega: 969 },
  decodeHTMLEntities: function(html) {
    if (!html) return '';
    return html.replace(/&#?(\w+);/g, function(match, dec) {
      return String.fromCharCode(isNaN(dec) ? Util.htmlEntities[dec] || dec : dec);
    });
  },

  // Extracts text from HTML with some attempt to improve formatting
  decodeHTML: function(html) {
    html = Util.decodeHTMLEntities(Util.stripHTMLTags(html));
    // Collapse whitespace. Allow paragraph breaks
    return html.replace(/\s\s+/g, function(match) {
      var index = match.indexOf('\n');
      if (index === -1) return ' ';
      return match.lastIndexOf('\n') === index ? '\n' : '\n\n';
    });
  },

  // Decodes base64
  // Credit: http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html
  base64keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "abcdefghijklmnopqrstuvwxyz" +
                "0123456789-_=",
  decode64: function(input, maxlength) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    maxlength = maxlength ? (maxlength * 4 + 2) / 3 : input.length;
    maxlength = maxlength < input.length ? maxlength : input.length;

    do {
      enc1 = this.base64keyStr.indexOf(input.charAt(i++));
      enc2 = this.base64keyStr.indexOf(input.charAt(i++));
      enc3 = this.base64keyStr.indexOf(input.charAt(i++));
      enc4 = this.base64keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";

    } while (i < maxlength);

    /* Make the string proper UTF-8 */
    return decodeURIComponent(escape(output));
  },

  /* Recursively grabs the first text part of multipart messages
   * Prefers plaintext over html. */
  getMessageBody: function(message) {
    var body = null;
    if ('payload' in message) {
      if (!message.loaded) {
        return Util.decodeHTMLEntities(message.snippet);
      }
      if (message.payload.mimeType == 'pebble') {
        body = message.payload.data;
      } else {
        body = Util.getMessageBody(message.payload);
        if (!body || !body.data) {
          return '';
        }
        body.data = Util.decode64(body.data);
        body = body.html ? Util.decodeHTML(body.data) : body.data;
        /* Ditch the rest of the payload data and store the result */
        message.payload.mimeType = 'pebble';
        message.payload.data = body;
        message.payload.parts = [];
      }
      var limit = Pebble.getActiveWatchInfo().platform == 'aplite' ? 768 : 0;
      return limit ? body.substring(0, limit) : body;
    } else if (message.mimeType.substring(0, 4) == 'text' && message.body.data) {
      return { html: message.mimeType.slice(-4) == 'html', data: message.body.data };
    } else if (message.mimeType.substring(0, 9) == 'multipart') {
      for (var i = 0; i < message.parts.length; i++) {
        var part = Util.getMessageBody(message.parts[i]);
        if (part && !part.html) {
          return part;
        } else if (part && part.html && !body) {
          body = part;
        }
      }
    }
    return body;
  },

  getFriendlyLabelName: function(label) {
    if (label.type === 'system') {
      var match = /^CATEGORY_(.*)$/.exec(label.id);
      if (match) {
        return Util.capitalize(match[1]);
      } else {
        return Util.capitalize(label.name);
      }
    }
    return label.name;
  },

  capitalize: function(str) {
    if (str) {
      return str[0].toUpperCase() + str.substring(1).toLowerCase();
    }
    return '';
  },

  plural: function(number, text) {
    return number != 1 ? (text || 's') : '';
  },

  systemLabelSortComparator: function(a, b) {
    var priorities = {
      UNREAD: 1,
      STARRED: 2,
      IMPORTANT: 3,
      INBOX: 4,
      SPAM: 5,
      TRASH: 6
    };
    return (priorities[a.label.id] || 9) - (priorities[b.label.id] || 9);
  }
};

module.exports = Util;
<|endoftext|>


<commit_before>// https://gist.github.com/Xeoncross/7663273
function ajax(url, options, callback, data, cache) {
  // Must encode data
  if(data && typeof data === 'object') {
    var y = '', e = encodeURIComponent;
    for (var m in data) {
      y += '&' + e(m) + '=' + e(data[m]);
    }
    data = y.slice(1) + (!cache ? '&_t=' + new Date : '');
  }

  try {
    var x = new (XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
    x.open(data ? 'POST' : 'GET', url, 1);
    if (!options.crossDomain) {
      x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }
    x.withCredentials = !!options.withCredentials;
    if (data) {
      x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.onreadystatechange = function() {
      x.readyState > 3 && callback && callback(x.responseText, x);
    };
    x.send(data);
  } catch (e) {
    window.console && console.log(e);
  }
}

export default ajax;
<commit_msg>Update ajax.js<commit_after>// https://gist.github.com/Xeoncross/7663273
function ajax(url, options, callback, data, cache) {
  // Must encode data
  if(data && typeof data === 'object') {
    var y = '', e = encodeURIComponent;
    for (var m in data) {
      y += '&' + e(m) + '=' + e(data[m]);
    }
    data = y.slice(1) + (!cache ? '&_t=' + new Date : '');
  }

  try {
    var x = new (XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
    x.open(data ? 'POST' : 'GET', url, 1);
    if (!options.crossDomain) {
      x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }
    x.withCredentials = !!options.withCredentials;
    if (data) {
      x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    x.onreadystatechange = function() {
      x.readyState > 3 && callback && callback(x.responseText, x);
    };
    x.send(data);
  } catch (e) {
    console && console.log(e);
  }
}

export default ajax;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 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.
 */

(function() {

  var isWorker = typeof importScripts !== 'undefined';
  var isServer = ( ! isWorker ) && typeof window === 'undefined';

  var flags    = this.FOAM_FLAGS || {};
  flags.web    = ! isServer,
  flags.node   = isServer;
  flags.loader = ! isServer;
  if ( ! flags.hasOwnProperty('debug') ) flags.debug = true;
  if ( ! flags.hasOwnProperty('js')    ) flags.js    = true;

  function createLoadBrowser() {
    var path = document.currentScript && document.currentScript.src;

    // document.currentScript isn't supported on all browsers, so the following
    // hack gets the job done on those browsers.
    if ( ! path ) {
      var scripts = document.getElementsByTagName('script');
      for ( var i = 0 ; i < scripts.length ; i++ ) {
        if ( scripts[i].src.match(/\/foam.js$/) ) {
          path = scripts[i].src;
          break;
        }
      }
    }

    path = path.substring(0, path.lastIndexOf('src/')+4);

    if ( typeof global !== 'undefined' ) global.FOAM_ROOT = path;
    if ( typeof window !== 'undefined' ) window.FOAM_ROOT = path;

    return function(filename) {
      document.writeln(
        '<script type="text/javascript" src="' + path + filename + '.js"></script>\n');
    };
  }

  function loadServer() {
    var caller = flags.src || __filename;
    var path = caller.substring(0, caller.lastIndexOf('src/')+4);

    return function (filename) {
      require(path + filename + '.js');
    }
  }

  function createLoadWorker(filename) {
    var path = FOAM_BOOT_PATH;
    return function(filename) {
      importScripts(path + filename + '.js');
    };
  }

  function getLoader() {
    return isServer ? loadServer() :
      isWorker ? createLoadWorker() :
      createLoadBrowser();
  }

  this.FOAM_FILES = function(files) {
    var load = getLoader();

    files.
      filter(function(f) {
        if ( f.flags ) {
          for ( var i = 0; i < f.flags.length; i++ ) {
            if ( ! flags[f.flags[i]] ) return false;
          }
        }
        if ( f.notFlags ) {
          for ( var i = 0; i < f.notFlags.length; i++ ) {
            if ( flags[f.notFlags[i]] ) return false;
          }
        }
        return true;
      }).
      map(function(f) { return f.name; }).
      forEach(load);

  //  delete this.FOAM_FILES;
  };

  getLoader()('files');
})();
<commit_msg>Add global.FOAM_ROOT when running as server.<commit_after>/**
 * @license
 * Copyright 2016 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.
 */

(function() {

  var isWorker = typeof importScripts !== 'undefined';
  var isServer = ( ! isWorker ) && typeof window === 'undefined';

  var flags    = this.FOAM_FLAGS || {};
  flags.web    = ! isServer,
  flags.node   = isServer;
  flags.loader = ! isServer;
  if ( ! flags.hasOwnProperty('debug') ) flags.debug = true;
  if ( ! flags.hasOwnProperty('js')    ) flags.js    = true;

  function createLoadBrowser() {
    var path = document.currentScript && document.currentScript.src;

    // document.currentScript isn't supported on all browsers, so the following
    // hack gets the job done on those browsers.
    if ( ! path ) {
      var scripts = document.getElementsByTagName('script');
      for ( var i = 0 ; i < scripts.length ; i++ ) {
        if ( scripts[i].src.match(/\/foam.js$/) ) {
          path = scripts[i].src;
          break;
        }
      }
    }

    path = path.substring(0, path.lastIndexOf('src/')+4);

    if ( typeof global !== 'undefined' ) global.FOAM_ROOT = path;
    if ( typeof window !== 'undefined' ) window.FOAM_ROOT = path;

    return function(filename) {
      document.writeln(
        '<script type="text/javascript" src="' + path + filename + '.js"></script>\n');
    };
  }

  function loadServer() {
    var caller = flags.src || __filename;
    var path = caller.substring(0, caller.lastIndexOf('src/')+4);

    if ( typeof global !== 'undefined' ) global.FOAM_ROOT = path;

    return function (filename) {
      require(path + filename + '.js');
    }
  }

  function createLoadWorker(filename) {
    var path = FOAM_BOOT_PATH;
    return function(filename) {
      importScripts(path + filename + '.js');
    };
  }

  function getLoader() {
    return isServer ? loadServer() :
      isWorker ? createLoadWorker() :
      createLoadBrowser();
  }

  this.FOAM_FILES = function(files) {
    var load = getLoader();

    files.
      filter(function(f) {
        if ( f.flags ) {
          for ( var i = 0; i < f.flags.length; i++ ) {
            if ( ! flags[f.flags[i]] ) return false;
          }
        }
        if ( f.notFlags ) {
          for ( var i = 0; i < f.notFlags.length; i++ ) {
            if ( flags[f.notFlags[i]] ) return false;
          }
        }
        return true;
      }).
      map(function(f) { return f.name; }).
      forEach(load);

  //  delete this.FOAM_FILES;
  };

  getLoader()('files');
})();
<|endoftext|>