<commit_before>const path = require('path')

const messages = {
  'invalid className': expected => `invalid className\n\nexpected '${expected}'`,
  'no component className': `invalid className\n\nonly root nodes can have a className that starts with 'component'`,
  'no className': 'className is not allowed on custom components\n\nonly native (lower case) elements can have a className',
  'no export base': 'base components can not be exported\n\nremove the `export` keyword',
  'no layoutClassName': 'layoutClassName can not be used on child components\n\nset the layoutClassName as the className of the root node',
  'invalid component name': expected => `invalid component name\n\nexpected '${expected}'`,
}
module.exports = {
  messages,
  rules: {
    // Test.js -> import styles from './Test.css'
    'root-component-class-name': {
      create(context) {
        const checked = new Set()

        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] MemberExpression[object.name = 'styles']`](node) {
            const jsxElement = getParentJSXElement(node)
            if (checked.has(jsxElement)) return
            else checked.add(jsxElement)

            if (!isRootJSXElement(jsxElement)) return
            const expected = `component${getFunctionName(context)}`
            if (node.property.name !== expected) context.report({
              message: messages['invalid className'](expected),
              node: node.property,
            })
          }
        }
      }
    },
    'child-no-component-class-name': {
      create(context) {
        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] MemberExpression[object.name = 'styles']`](node) {
            const jsxElement = getParentJSXElement(node)

            if (isRootJSXElement(jsxElement)) return
            if (node.property.name.startsWith('component')) context.report({
              message: messages['no component className'],
              node: node.property,
            })
          },
        }
      }
    },
    'no-custom-component-class-name': {
      create(context) {
        return {
          [`JSXSpreadAttribute Property[key.name = 'className']`]: noClassName,
          [`JSXAttribute[name.name = 'className']`]: noClassName,
        }

        function noClassName(node) {
          const jsxElement = getParentJSXElement(node)
          const name = getJSXElementName(jsxElement)

          if (firstLetterLowerCase(name) || name.endsWith('Base')) return

          context.report({
            message: messages['no className'],
            node,
          })
        }
      }
    },
    'no-export-base': {
      create(context) {
        return {
          'ExportNamedDeclaration > FunctionDeclaration'(node) {
            const { name } = node.id
            if (!name.endsWith('Base') || firstLetterLowerCase(name)) return

            const exportNode = node.parent
            context.report({
              message: messages['no export base'],
              node: exportNode,
              loc: {
                start: exportNode.loc.start,
                end: node.loc.start
              },
            })
          }
        }
      }
    },
    'child-no-layout-class-name': {
      create(context) {
        const checked = new Set()
        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] Identifier[name = 'layoutClassName']`](node) {
            const jsxElement = getParentJSXElement(node)
            if (checked.has(jsxElement)) return
            else checked.add(jsxElement)

            if (isRootJSXElement(jsxElement)) return

            context.report({
              message: messages['no layoutClassName'],
              node,
            })
          }
        }
      }
    },
    'component-name-starts-with-file-name': {
      create(context) {
        return {
          'ExportNamedDeclaration > FunctionDeclaration'(node) {
            const { name } = node.id
            if (firstLetterLowerCase(name)) return

            const filename = context.getFilename()
            const expectedPrefix = path.basename(filename, '.js')
            if (name.startsWith(expectedPrefix)) return

            const expected = `${expectedPrefix}${name}`
            context.report({
              message: messages['invalid component name'](expected),
              node: node.id,
            })
          }
        }
      }
    }
  },
}

function firstLetterLowerCase(word) {
  const firstLetter = word.slice(0, 1)
  return firstLetter.toLowerCase() === firstLetter
}

function getJSXElementName(jsxElement) {
  return jsxElement.openingElement.name.name
}

function getFunctionName(context) {
  return context.getScope().block.id.name
}

function isRootJSXElement(jsxElement) {
  return !getParentJSXElement(jsxElement)
}

function getParentJSXElement({ parent }) {
  if (!parent) return
  return parent.type === 'JSXElement'
    ? parent
    : getParentJSXElement(parent)

}
<commit_msg>consistently use early returns<commit_after>const path = require('path')

const messages = {
  'invalid className': expected => `invalid className\n\nexpected '${expected}'`,
  'no component className': `invalid className\n\nonly root nodes can have a className that starts with 'component'`,
  'no className': 'className is not allowed on custom components\n\nonly native (lower case) elements can have a className',
  'no export base': 'base components can not be exported\n\nremove the `export` keyword',
  'no layoutClassName': 'layoutClassName can not be used on child components\n\nset the layoutClassName as the className of the root node',
  'invalid component name': expected => `invalid component name\n\nexpected '${expected}'`,
}
module.exports = {
  messages,
  rules: {
    // Test.js -> import styles from './Test.css'
    'root-component-class-name': {
      create(context) {
        const checked = new Set()

        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] MemberExpression[object.name = 'styles']`](node) {
            const jsxElement = getParentJSXElement(node)
            if (checked.has(jsxElement)) return
            else checked.add(jsxElement)

            if (!isRootJSXElement(jsxElement)) return
            const expected = `component${getFunctionName(context)}`
            if (node.property.name === expected) return

            context.report({
              message: messages['invalid className'](expected),
              node: node.property,
            })
          }
        }
      }
    },
    'child-no-component-class-name': {
      create(context) {
        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] MemberExpression[object.name = 'styles']`](node) {
            const jsxElement = getParentJSXElement(node)

            if (isRootJSXElement(jsxElement) || !node.property.name.startsWith('component')) return

            context.report({
              message: messages['no component className'],
              node: node.property,
            })
          },
        }
      }
    },
    'no-custom-component-class-name': {
      create(context) {
        return {
          [`JSXSpreadAttribute Property[key.name = 'className']`]: noClassName,
          [`JSXAttribute[name.name = 'className']`]: noClassName,
        }

        function noClassName(node) {
          const jsxElement = getParentJSXElement(node)
          const name = getJSXElementName(jsxElement)

          if (firstLetterLowerCase(name) || name.endsWith('Base')) return

          context.report({
            message: messages['no className'],
            node,
          })
        }
      }
    },
    'no-export-base': {
      create(context) {
        return {
          'ExportNamedDeclaration > FunctionDeclaration'(node) {
            const { name } = node.id
            if (!name.endsWith('Base') || firstLetterLowerCase(name)) return

            const exportNode = node.parent
            context.report({
              message: messages['no export base'],
              node: exportNode,
              loc: {
                start: exportNode.loc.start,
                end: node.loc.start
              },
            })
          }
        }
      }
    },
    'child-no-layout-class-name': {
      create(context) {
        const checked = new Set()
        return {
          [`ReturnStatement JSXAttribute[name.name = 'className'] Identifier[name = 'layoutClassName']`](node) {
            const jsxElement = getParentJSXElement(node)
            if (checked.has(jsxElement)) return
            else checked.add(jsxElement)

            if (isRootJSXElement(jsxElement)) return

            context.report({
              message: messages['no layoutClassName'],
              node,
            })
          }
        }
      }
    },
    'component-name-starts-with-file-name': {
      create(context) {
        return {
          'ExportNamedDeclaration > FunctionDeclaration'(node) {
            const { name } = node.id
            if (firstLetterLowerCase(name)) return

            const filename = context.getFilename()
            const expectedPrefix = path.basename(filename, '.js')
            if (name.startsWith(expectedPrefix)) return

            const expected = `${expectedPrefix}${name}`
            context.report({
              message: messages['invalid component name'](expected),
              node: node.id,
            })
          }
        }
      }
    }
  },
}

function firstLetterLowerCase(word) {
  const firstLetter = word.slice(0, 1)
  return firstLetter.toLowerCase() === firstLetter
}

function getJSXElementName(jsxElement) {
  return jsxElement.openingElement.name.name
}

function getFunctionName(context) {
  return context.getScope().block.id.name
}

function isRootJSXElement(jsxElement) {
  return !getParentJSXElement(jsxElement)
}

function getParentJSXElement({ parent }) {
  if (!parent) return
  return parent.type === 'JSXElement'
    ? parent
    : getParentJSXElement(parent)

}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         bot_AH_FT
// @namespace    http://aposte.me/
// @version      0.2.16
// @description  Utiliza ao vivo no Asian Handicap
// @author       Ronaldo
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js
// @match        https://mobile.bet365.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue

// ==/UserScript==

/* jshint -W097 */
'use strict';

const PRIMEIRO_TEMPO = "151017012C1_1_3";
const SEGUNDO_TEMPO  = "151014714C1_1_3";

function primeiroTempo(){
   return location.hash.includes(PRIMEIRO_TEMPO);
}
function segundoTempo(){
   return location.hash.includes(SEGUNDO_TEMPO);
}

//Simula o click real, clicando em um ponto do aleatório do objeto
unsafeWindow.jQuery.fn.extend({rclick:function(){var a=function(a,b){var c=function(a,b){var c,d=!1;return function(){var e;if(d)e=c,d=!1;else{var f,g,h;do f=2*Math.random()-1,g=2*Math.random()-1,h=f*f+g*g;while(h>=1);h=Math.sqrt(-2*Math.log(h)/h),e=f*h,c=g*h,d=!0}var i=a+b*e;return i>0?i:-i}},d=Math.round(c((b+a)/2,(b-a)/6)());return d>b&&(d=b),d<a&&(d=a),d},b={x1:$(this).offset().left,y1:$(this).offset().top,x2:$(this).offset().left+$(this).width(),y2:$(this).offset().top+$(this).height()},c=function(a,b){var c=document.createEvent("MouseEvent"),d=document.elementFromPoint(a,b);c.initMouseEvent("click",!0,!0,unsafeWindow,null,a,b,0,0,!1,!1,!1,!1,0,null),d.dispatchEvent(c)};c(a(b.x1,b.x2),a(b.y1,b.y2))}});

function login(){
	if($('.mmhdr-UserInfo_UserName').text()==''){
		$('.hm-HeaderLinkLogin_Launcher').click();
		$('#PopUp_UserName').val('ronaldoaf');
		$('#PopUp_Password').val('rr842135');
		$('#PopUp_KML').val('on');
		$('#LogInPopUpBttn').click();
	}
};

console.log([primeiroTempo(),segundoTempo()]);

var time_;

unsafeWindow.bot={};

bot.apostando_agora=false;
bot.betslipBarEnhanced_selecionado=false;
bot.copiado_betslip=false

bot.stake=function(){
    var soma=0;
	$( bot.textMyBets.match(/VA=[0-9\.]+/g) ).each(function(i,e){
		soma+=Number(e.split('=')[1]);
	});

	soma+=bot.balance;

	return (Math.floor(soma*0.05)+0.5);
};

bot.jogoLive = function (home,away){
	var ahSel=function(selObj){
	   var arr_ah=selObj.find('.ip-Participant_OppName').text().split(',');

	   var s=0;
	   $(arr_ah).each(function(i,e){ s+=Number(e); });
	   return s/$(arr_ah).size();
	};

	jogo=-1;
	$('div.ipe-ParticipantCouponFixtureName_Participant ').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			//saida=i;
			jogo={
					market: $(e).parents('.ipe-Market')
			};

		}

	});
	if (jogo==-1) return jogo;

	jogo.selecoes=$(jogo.market).find('.ip-Participant ');
	jogo.numJogos=$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').size();
	$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			jogo.positionInMarket=i;
			jogo.posSelsJogo=[jogo.positionInMarket, jogo.positionInMarket+jogo.numJogos];
			jogo.selHome=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[0]);
			jogo.selAway=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[1]);
		}
	});
	jogo.tempo=Number($(jogo.market).find('.ipe-ParticipantCouponFixtureName_Timer').eq(jogo.positionInMarket).text().split(':')[0]);
	jogo.AH_Home=ahSel(jogo.selHome);
	jogo.AH_Away=ahSel(jogo.selAway);

	return jogo;
};

bot.jaFoiApostado=function(home,away){
    return bot.textMyBets.includes(home+' v '+away);
};

bot.apostar=function(selObj){
	 bot.apostando_agora=true;
	 selObj.rclick();

};

bot.anotar=function(nota){
	GM_xmlhttpRequest({
		method: "POST",
		url: "http://aposte.me/live/notas.php",
		data:  JSON.stringify(nota),
		onload: function(res){
			console.log(res.responseText);
		}
	});
};

//---Toda vez que as estatisticas do arquivo JSON forem carregadas
bot.onLoadStats=function(response){

   //console.log(response);
   var jogos=eval(response.responseText);
   //console.log(jogos);
   foreach(i in jogos) {
     var jj=jogos[i];
     console.log([jj.home, jj.away, jj.ind, jj.ind2]);
   }
   //Se o flag bot.apostando_agora estiver true, não tenta aposta
   if(bot.apostando_agora) return;

    var anota_jogos=[];
    var anota_apostas=[];
   //Para jogo no cupom
   $('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){

	   var home=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').text();
	   var away=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').text();

	   //anota_apostas.push([jogo)+'<<<>>>'+JSON.stringify(jogos)+'<<<>>>'+bot.textMyBets+'<<<>>>>'+ $('#MarketGrid').html() );
	   //Cada jogo do Ajax
	   $(jogos).each(function(ii,jogo){
			 //if (apostando_agora) return;

			 if(  (jogo.home==home) && (jogo.away==away) ){

				   //Se já houve aposta nesse jogo sai.
				   if( bot.jaFoiApostado(home,away) )return;

				   //Se o elemento DOM da linha do jogo
				   jogo_selecionado=bot.jogoLive(home,away);

                   //Acumula as anotacoes
                   //anota_jogos.push([jogo.home, jogo.away, jogo.ind, jogo.ind2, jogo_selecionado.AH_Home,jogo_selecionado.AH_Away,jogo.gH,jogo.gA,primeiroTempo() ,jogo_selecionado.tempo]);

					//Aposta no Home
					if (
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	   ( jogo_selecionado.AH_Home==-0.5)  &&  ( jogo.gH<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home==-0.25)  &&  ( jogo.gH<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	( jogo_selecionado.AH_Home>=0)  &&  ( jogo.g<=0.0) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
                    ){
						bot.apostar(jogo_selecionado.selHome);
						anota_apostas.push( jogo );
					}

					//Aposta no Away
					if (
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.5)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away==-0.25)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) ) ||
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	( jogo_selecionado.AH_Away>=0)  &&  ( jogo.gA<=1) &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
					){
						bot.apostar(jogo_selecionado.selAway);
						anota_apostas.push( jogo );

					}

			 }
	   });
   });
   //Envia as anotacoes
   bot.anotar({jogos: JSON.stringify(jogos), apostas: anota_apostas, myBets: bot.textMyBets, pagina: $('#MarketGrid').html() });

};

//---A cada 30 segundos
bot.on30segs=function(){
       console.log('on30segs');

	   //Faz um ajax para o arquivo JSON "http://aposte.me/live/stats.php"
	   GM_xmlhttpRequest({
		   method: "GET",
		   url: "http://aposte.me/live/stats.php?t="+time_,
		   headers: {
			   'Accept': "*/*; charset=utf-8",
		   },
		   onload: function(response){
             //Pega a lista de apostas ativas
             $.get('https://mobile.bet365.com/mybets/mybetsdata.ashx?pt=0&tl=OPENBETS%3B__time&ci=28', function(data){
                bot.textMyBets=data;
                bot.onLoadStats(response);
             });

			//Pega o valor da banca disponível
            $.get('https://mobile.bet365.com/Controls/BetSlip/GetBalance.aspx',function(data){
                   bot.balance=Number(data.balance);
               });
           }
	   });
}

//Modo interativo
bot.interativo=function(){
   GM_xmlhttpRequest({
	   method: "GET",
	   url: "http://aposte.me/live/in.php?t="+time_,
	   headers: {
		   'Accept': "*/*; charset=utf-8",
	   },
	   onload: function(response){
			eval(response);
	   }
   });
};

//Loop Principal repete todos os comandos a cada 1 segund
unsafeWindow.setInterval(function(){
	if (location.hash)

	time_=Math.floor( (+new Date) /1000);

    //Se estiver no primeiro tempo dá uma shift de 15 segundos para que ambos os bots não executem as tarefas ao mesmo tempo
    if (primeiroTempo()) time_+=15;

	//A cada 30 segundos
	if ( !(time_ % 30) ) bot.on30segs();

	//bot.interativo();

	//Aparecer a caixa informando que as odds mudaram clica no Botão "Accept"
	if( !$('.acceptChanges').hasClass('hidden') ) $('button:contains(Accept)').click();

    //Se a betSlipBar aparecer clica nela depois de 5 segundos
	if( $('#betslipBarEnhanced').hasClass('showingBetSlipEnhancedBar')) {
		if (bot.betslipBarEnhanced_selecionado==false) {
			bot.betslipBarEnhanced_selecionado=true;
            setTimeout(function(){
				$('#betslipBarEnhanced').click();
			},5000);

		}
	}
	//Se não aparece a betSlipBar nem o formulário para apostar, indica que não está sendo apostado no momento
	else if( $('#betSlipOverlay').hasClass('opaque')==false){
	   bot.apostando_agora=false;
	}

	//Se o formulario de aposta aparecer
	if ( $('#betSlipOverlay').hasClass('opaque') ){
	   //deseleciona ao flag bot.betslipBarEnhanced_selecionado
       bot.betslipBarEnhanced_selecionado=false;

	   //Coloca o valor dos stakes para cada seleção
	   $('.selectionRow').each(function(i,e){
			$(e).find('.stk').val('1.00');
	   });

	   //Clica em "Place Bet"
	   $('.placeBet button').click();
	}

	//Copia betslip para Debug
	if( $('.selectionRow').size()>0 ){
		if(bot.copiado_betslip==false){
	   		bot.anotar({betslip: $('#betslipContainer').html() } );
	   		bot.copiado_betslip=true;
		}
	}
	else{
		bot.copiado_betslip=false;
	}

	//Se aparecer o "Botão Continue" depois que apostas foram colocadas, clica nele
	if( $('.betReceipt').size()>0 ) $('button:contains(Continue)').click();

	//Senão estiver logado, loga
	login()

},1000);

//A cada 15 minutos recarrega a pagina
window.setInterval(function(){
    window.location.reload();
},15*60*1000);
<commit_msg>TESTE - redução dos paramentros para testar logo<commit_after>// ==UserScript==
// @name         bot_AH_FT
// @namespace    http://aposte.me/
// @version      0.2.17
// @description  Utiliza ao vivo no Asian Handicap
// @author       Ronaldo
// @require      https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js
// @match        https://mobile.bet365.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue

// ==/UserScript==

/* jshint -W097 */
'use strict';

const PRIMEIRO_TEMPO = "151017012C1_1_3";
const SEGUNDO_TEMPO  = "151014714C1_1_3";

function primeiroTempo(){
   return location.hash.includes(PRIMEIRO_TEMPO);
}
function segundoTempo(){
   return location.hash.includes(SEGUNDO_TEMPO);
}

//Simula o click real, clicando em um ponto do aleatório do objeto
unsafeWindow.jQuery.fn.extend({rclick:function(){var a=function(a,b){var c=function(a,b){var c,d=!1;return function(){var e;if(d)e=c,d=!1;else{var f,g,h;do f=2*Math.random()-1,g=2*Math.random()-1,h=f*f+g*g;while(h>=1);h=Math.sqrt(-2*Math.log(h)/h),e=f*h,c=g*h,d=!0}var i=a+b*e;return i>0?i:-i}},d=Math.round(c((b+a)/2,(b-a)/6)());return d>b&&(d=b),d<a&&(d=a),d},b={x1:$(this).offset().left,y1:$(this).offset().top,x2:$(this).offset().left+$(this).width(),y2:$(this).offset().top+$(this).height()},c=function(a,b){var c=document.createEvent("MouseEvent"),d=document.elementFromPoint(a,b);c.initMouseEvent("click",!0,!0,unsafeWindow,null,a,b,0,0,!1,!1,!1,!1,0,null),d.dispatchEvent(c)};c(a(b.x1,b.x2),a(b.y1,b.y2))}});

function login(){
	if($('.mmhdr-UserInfo_UserName').text()==''){
		$('.hm-HeaderLinkLogin_Launcher').click();
		$('#PopUp_UserName').val('ronaldoaf');
		$('#PopUp_Password').val('rr842135');
		$('#PopUp_KML').val('on');
		$('#LogInPopUpBttn').click();
	}
};

console.log([primeiroTempo(),segundoTempo()]);

var time_;

unsafeWindow.bot={};

bot.apostando_agora=false;
bot.betslipBarEnhanced_selecionado=false;
bot.copiado_betslip=false

bot.stake=function(){
    var soma=0;
	$( bot.textMyBets.match(/VA=[0-9\.]+/g) ).each(function(i,e){
		soma+=Number(e.split('=')[1]);
	});

	soma+=bot.balance;

	return (Math.floor(soma*0.05)+0.5);
};

bot.jogoLive = function (home,away){
	var ahSel=function(selObj){
	   var arr_ah=selObj.find('.ip-Participant_OppName').text().split(',');

	   var s=0;
	   $(arr_ah).each(function(i,e){ s+=Number(e); });
	   return s/$(arr_ah).size();
	};

	jogo=-1;
	$('div.ipe-ParticipantCouponFixtureName_Participant ').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			//saida=i;
			jogo={
					market: $(e).parents('.ipe-Market')
			};

		}

	});
	if (jogo==-1) return jogo;

	jogo.selecoes=$(jogo.market).find('.ip-Participant ');
	jogo.numJogos=$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').size();
	$(jogo.market).find('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){
		if(
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').html()==home)  &&
			($(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').html()==away )
		){
			jogo.positionInMarket=i;
			jogo.posSelsJogo=[jogo.positionInMarket, jogo.positionInMarket+jogo.numJogos];
			jogo.selHome=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[0]);
			jogo.selAway=$(jogo.market).find('.ip-Participant').eq(jogo.posSelsJogo[1]);
		}
	});
	jogo.tempo=Number($(jogo.market).find('.ipe-ParticipantCouponFixtureName_Timer').eq(jogo.positionInMarket).text().split(':')[0]);
	jogo.AH_Home=ahSel(jogo.selHome);
	jogo.AH_Away=ahSel(jogo.selAway);

	return jogo;
};

bot.jaFoiApostado=function(home,away){
    return bot.textMyBets.includes(home+' v '+away);
};

bot.apostar=function(selObj){
	 bot.apostando_agora=true;
	 selObj.rclick();

};

bot.anotar=function(nota){
	GM_xmlhttpRequest({
		method: "POST",
		url: "http://aposte.me/live/notas.php",
		data:  JSON.stringify(nota),
		onload: function(res){
			console.log(res.responseText);
		}
	});
};

//---Toda vez que as estatisticas do arquivo JSON forem carregadas
bot.onLoadStats=function(response){

   //console.log(response);
   var jogos=eval(response.responseText);
   //console.log(jogos);
   for(i in jogos) {
     var jj=jogos[i];
     console.log([jj.home, jj.away, jj.ind, jj.ind2]);
   }
   //Se o flag bot.apostando_agora estiver true, não tenta aposta
   if(bot.apostando_agora) return;

    var anota_jogos=[];
    var anota_apostas=[];
   //Para jogo no cupom
   $('.ipe-ParticipantCouponFixtureName_Participant').each(function(i,e){

	   var home=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(0)').text();
	   var away=$(e).find('.ipe-ParticipantCouponFixtureName_TeamName:eq(1)').text();

	   //anota_apostas.push([jogo)+'<<<>>>'+JSON.stringify(jogos)+'<<<>>>'+bot.textMyBets+'<<<>>>>'+ $('#MarketGrid').html() );
	   //Cada jogo do Ajax
	   $(jogos).each(function(ii,jogo){
			 //if (apostando_agora) return;

			 if(  (jogo.home==home) && (jogo.away==away) ){

				   //Se já houve aposta nesse jogo sai.
				   if( bot.jaFoiApostado(home,away) )return;

				   //Se o elemento DOM da linha do jogo
				   jogo_selecionado=bot.jogoLive(home,away);

                   //Acumula as anotacoes
                   //anota_jogos.push([jogo.home, jogo.away, jogo.ind, jogo.ind2, jogo_selecionado.AH_Home,jogo_selecionado.AH_Away,jogo.gH,jogo.gA,primeiroTempo() ,jogo_selecionado.tempo]);

					//Aposta no Home
					if (
						 ( ( jogo.ind>=0.5 ) &&  ( jogo.ind2>0) && 	   ( jogo_selecionado.AH_Home>=-1.0)  &&  ( jogo.gH<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )

                    			){
						bot.apostar(jogo_selecionado.selHome);
						anota_apostas.push( jogo );
					}

					//Aposta no Away
					if (
						 ( ( jogo.ind<=-0.5 ) &&  ( jogo.ind2<0) && 	   ( jogo_selecionado.AH_Away>=-1.0)  &&  ( jogo.gA<=1)  &&  ( (primeiroTempo() && (jogo_selecionado.tempo>=17)) ||  (segundoTempo() && (jogo_selecionado.tempo>=62))    ) )
					){
						bot.apostar(jogo_selecionado.selAway);
						anota_apostas.push( jogo );

					}

			 }
	   });
   });
   //Envia as anotacoes
   bot.anotar({jogos: JSON.stringify(jogos), apostas: anota_apostas, myBets: bot.textMyBets, pagina: $('#MarketGrid').html() });

};

//---A cada 30 segundos
bot.on30segs=function(){
       console.log('on30segs');

	   //Faz um ajax para o arquivo JSON "http://aposte.me/live/stats.php"
	   GM_xmlhttpRequest({
		   method: "GET",
		   url: "http://aposte.me/live/stats.php?t="+time_,
		   headers: {
			   'Accept': "*/*; charset=utf-8",
		   },
		   onload: function(response){
             //Pega a lista de apostas ativas
             $.get('https://mobile.bet365.com/mybets/mybetsdata.ashx?pt=0&tl=OPENBETS%3B__time&ci=28', function(data){
                bot.textMyBets=data;
                bot.onLoadStats(response);
             });

			//Pega o valor da banca disponível
            $.get('https://mobile.bet365.com/Controls/BetSlip/GetBalance.aspx',function(data){
                   bot.balance=Number(data.balance);
               });
           }
	   });
}

//Modo interativo
bot.interativo=function(){
   GM_xmlhttpRequest({
	   method: "GET",
	   url: "http://aposte.me/live/in.php?t="+time_,
	   headers: {
		   'Accept': "*/*; charset=utf-8",
	   },
	   onload: function(response){
			eval(response);
	   }
   });
};

//Loop Principal repete todos os comandos a cada 1 segund
unsafeWindow.setInterval(function(){
	if (location.hash)

	time_=Math.floor( (+new Date) /1000);

    //Se estiver no primeiro tempo dá uma shift de 15 segundos para que ambos os bots não executem as tarefas ao mesmo tempo
    if (primeiroTempo()) time_+=15;

	//A cada 30 segundos
	if ( !(time_ % 30) ) bot.on30segs();

	//bot.interativo();

	//Aparecer a caixa informando que as odds mudaram clica no Botão "Accept"
	if( !$('.acceptChanges').hasClass('hidden') ) $('button:contains(Accept)').click();

    //Se a betSlipBar aparecer clica nela depois de 5 segundos
	if( $('#betslipBarEnhanced').hasClass('showingBetSlipEnhancedBar')) {
		if (bot.betslipBarEnhanced_selecionado==false) {
			bot.betslipBarEnhanced_selecionado=true;
            setTimeout(function(){
				$('#betslipBarEnhanced').click();
			},5000);

		}
	}
	//Se não aparece a betSlipBar nem o formulário para apostar, indica que não está sendo apostado no momento
	else if( $('#betSlipOverlay').hasClass('opaque')==false){
	   bot.apostando_agora=false;
	}

	//Se o formulario de aposta aparecer
	if ( $('#betSlipOverlay').hasClass('opaque') ){
	   //deseleciona ao flag bot.betslipBarEnhanced_selecionado
       bot.betslipBarEnhanced_selecionado=false;

	   //Coloca o valor dos stakes para cada seleção
	   $('.selectionRow').each(function(i,e){
			$(e).find('.stk').val('1.00');
	   });

	   //Clica em "Place Bet"
	   $('.placeBet button').click();
	}

	//Copia betslip para Debug
	if( $('.selectionRow').size()>0 ){
		if(bot.copiado_betslip==false){
	   		bot.anotar({betslip: $('#betslipContainer').html() } );
	   		bot.copiado_betslip=true;
		}
	}
	else{
		bot.copiado_betslip=false;
	}

	//Se aparecer o "Botão Continue" depois que apostas foram colocadas, clica nele
	if( $('.betReceipt').size()>0 ) $('button:contains(Continue)').click();

	//Senão estiver logado, loga
	login()

},1000);

//A cada 15 minutos recarrega a pagina
window.setInterval(function(){
    window.location.reload();
},15*60*1000);
<|endoftext|>


<commit_before>import Platform from '../plugins/Platform.js'

export default {
  name: 'go-back',

  bind (el, { value, modifiers }, vnode) {
    let ctx = { value, position: window.history.length - 1, single: modifiers.single }

    if (Platform.is.cordova) {
      ctx.goBack = () => {
        vnode.context.$router.go(ctx.single ? -1 : ctx.position - window.history.length)
      }
    }
    else {
      ctx.goBack = () => {
        vnode.context.$router.replace(ctx.value)
      }
    }
    ctx.goBackKey = ev => {
      if (ev.keyCode === 13) {
        ctx.goBack(ev)
      }
    }

    if (el.__qgoback) {
      el.__qgoback_old = el.__qgoback
    }

    el.__qgoback = ctx
    el.addEventListener('click', ctx.goBack)
    el.addEventListener('keyup', ctx.goBackKey)
  },

  update (el, { value, oldValue }) {
    if (value !== oldValue) {
      el.__qgoback.value = value
    }
  },

  unbind (el) {
    const ctx = el.__qgoback_old || el.__qgoback
    if (ctx !== void 0) {
      el.removeEventListener('click', ctx.goBack)
      el.removeEventListener('keyup', ctx.goBackKey)
      delete el[el.__qgoback_old ? '__qgoback_old' : '__qgoback']
    }
  }
}
<commit_msg>fix(GoBack): Fixes the single modification (#4135)<commit_after>import Platform from '../plugins/Platform.js'

export default {
  name: 'go-back',

  bind (el, { value, modifiers }, vnode) {
    let ctx = { value, position: window.history.length - 1, single: modifiers.single }

    if (Platform.is.cordova) {
      ctx.goBack = () => {
        vnode.context.$router.go(ctx.single ? -1 : ctx.position - window.history.length)
      }
    }
    else {
      ctx.goBack = () => {
        if (ctx.single){
          vnode.context.$router.go(-1)
        } else {
          vnode.context.$router.replace(ctx.value)
        }
      }
    }
    ctx.goBackKey = ev => {
      if (ev.keyCode === 13) {
        ctx.goBack(ev)
      }
    }

    if (el.__qgoback) {
      el.__qgoback_old = el.__qgoback
    }

    el.__qgoback = ctx
    el.addEventListener('click', ctx.goBack)
    el.addEventListener('keyup', ctx.goBackKey)
  },

  update (el, { value, oldValue }) {
    if (value !== oldValue) {
      el.__qgoback.value = value
    }
  },

  unbind (el) {
    const ctx = el.__qgoback_old || el.__qgoback
    if (ctx !== void 0) {
      el.removeEventListener('click', ctx.goBack)
      el.removeEventListener('keyup', ctx.goBackKey)
      delete el[el.__qgoback_old ? '__qgoback_old' : '__qgoback']
    }
  }
}
<|endoftext|>


<commit_before>/***********************************************************************

    Check in, check uit

    Copyright 2010, Martijn Vermaat <martijn@vermaat.name>

      http://checkincheckuit.nl
      http://svn.vermaat.name/checkincheckuit

    Licensed under the MIT license, see the LICENSE file

      http://en.wikipedia.org/wiki/Mit_license

    Some of the Twitter handling code was adapted from the jQuery
    plugin Tweet!, found at http://tweet.seaofclouds.com/

    This code uses:
      jQuery          http://jquery.com
      jQuery Timers   http://plugins.jquery.com/project/timers

***********************************************************************/

$(document).ready(function() {

    var twitterSearch = 'ovchipkaart OR chipkaart OR ovchip';
    var twitterCount = 50;
    var twitterBlacklist = ['Regio_Alphen',
                            'Regio_Leiden',
                            'LeidenNL',
                            'Regio_Duin_Bol',
                            'Edestad',
                            'nieuwsede',
                            'edenieuwspunt.nl',
                            'nieuwsinutrecht',
                            'UtrechtNL',
                            'rtvutrecht',
                            'echo_utrecht',
                            'regio_nieuws',
                            'hetlokalenieuws',
                            'Nieuwsbekijken',
                            'totaalnieuwsweb',
                            'De_Pers',
                            '123nieuws',
                            'nieuwsnld',
                            'economie_nieuws',
                            'treinreizigernl',
                            'doormijverloren',
                            'doormijgevonden',
                            'ov_chipkaart'];
    var twitterDisplayTime = 1000 * 8;
    var twitterFadeTime = 800;
    /*
      There seems to be a bug, where animations are not smooth when the
      interval is specified as a string, e.g. '5s'.
    */
    var twitterReloadTime = 1000 * 60 * 5;

    var deliciousUser = 'checkuitcheckin';
    var deliciousTag = 'nieuws';
    var deliciousCount = 10;

    // Unfortunately, twitter query cannot exceed 140 characters
    var twitterUrl = 'http://search.twitter.com/search?&q='
        + encodeURIComponent(twitterSearch);
    var twitterApiUrl = 'http://search.twitter.com/search.json?&q='
        + encodeURIComponent(twitterSearch)
        + '&rpp=' + twitterCount + '&callback=?';
    var initialTweet = true;
    var tweets = [];
    var currentTweet = 0;

    var deliciousUrl = 'http://delicious.com/' + deliciousUser
        + '/' + deliciousTag;
    var deliciousApiUrl = 'http://feeds.delicious.com/v2/json/'
        + deliciousUser + '/' + deliciousTag
        + '?count=' + deliciousCount + '&callback=?';

    // Load Twitter search results and call callback function
    function updateTwitter(callback) {

        // http://apiwiki.twitter.com/Return-Values

        $.getJSON(twitterApiUrl, function(data) {

            currentTweet = 0;
            tweets = [];

            $.each((data.results || data), function(i, tweet) {
                var user = tweet.from_user || tweet.user.screen_name;
                if (twitterBlacklist.indexOf(user) == -1) {
                    tweets.push({
                        text    : twittify(tweet.text),
                        user    : user,
                        date    : relativeTime(tweet.created_at),
                        url     : 'http://twitter.com/' + user
                                  + '/statuses/' + tweet.id,
                        userUrl : 'http://twitter.com/' + user
                    });
                }
            });

            if ($.isFunction(callback)) callback();

        });

    }

    // Load Delicious links and show them on the page
    function updateDelicious() {

        // http://delicious.com/help/feeds

        $.getJSON(deliciousApiUrl, function(data) {
            var list = $('
').appendTo($('#delicious'));
            $.each((data.results || data), function(i, item) {
                list.append($('
').text(shortDate(item.dt)));
                list.append($('
').append(
                    $('').attr('href', item.u).text(item.d)));
            });
            $('#delicious').append($('
').append(
                $('Meer nieuwsberichten...').attr('href', deliciousUrl)));
        });

    }

    // Advance to the next twee
    function showNextTweet() {
        if (tweets.length < 1) return;
        currentTweet = (currentTweet + 1) % tweets.length;
        showTweet();
    }

    // Like the function above, with a minor difference
    function showPreviousTweet() {
        if (tweets.length < 1) return;
        currentTweet = (tweets.length + currentTweet - 1) % tweets.length;
        showTweet();
    }

    /*
      Show the current tweet on the page. If this is the first twee we show,
      do just that. Otherwise fadeout the old tweet and fadein the new.
    */
    function showTweet() {

        var show = function() {
            var tweet = tweets[currentTweet];
            var pane = $('#content .tweet');
            /*
              The documentation (and experience) tells us we get the tweet
              text 'escaped and HTML encoded'.
              I still don't like to .html() this into the page, but being more
              cautious would make twittify() much more involved.

              http://apiwiki.twitter.com/Return-Values
            */
            pane.find('.text').html(tweet.text);
            pane.find('h2').empty().append(
                $('').attr('href', tweet.userUrl).text('@' + tweet.user));
            pane.find('h2').append(
                $('').attr('href', tweet.url).text(tweet.date).addClass(
                    'date'));
        }

        if (initialTweet)
            show();
        else
            $("#content .tweet").fadeOut(twitterFadeTime, function () {
                show();
                $("#content .tweet").fadeIn(twitterFadeTime);
            });

        initialTweet = false;

    }

    // Setup the Twitter stream
    function setupTwitter() {

        // Get tweets, show the first one, and skip to next tweet every 5 seconds
        updateTwitter(function() {

            if (tweets.length > 0)
                showTweet();

            if (tweets.length > 1) {

                $(document).everyTime(twitterDisplayTime,
                                      'next',
                                      showNextTweet);

                // We add navigation links and reset the skip timer on click
                $('#content').append($('
').append(
                    $('
<
').click(function() {
                        showPreviousTweet();
                        $(document).stopTime('next');
                        $(document).everyTime(twitterDisplayTime,
                                              'next',
                                              showNextTweet);
                    })
                ).append(
                    $('
>
').click(function() {
                        showNextTweet();
                        $(document).stopTime('next');
                        $(document).everyTime(twitterDisplayTime,
                                              'next',
                                              showNextTweet);
                    })
                ));

            }

        });

        // Every 5 minutes, get tweets and start at the latest tweet again
        $(document).everyTime(twitterReloadTime, 'reload', updateTwitter);

        // Show link to Twitter search results
        $('#content').append($('
').append(
            $('meer...').attr('href', twitterUrl)));

        // Pause auto advancing of tweets on mouse hover
        $('#content .tweet').hover(function() {
            $(document).stopTime('next');
        }, function() {
            if (tweets.length > 1) {
                // If we directly want to advance on hover-out, uncomment this
                //showNextTweet();
                $(document).everyTime(twitterDisplayTime,
                                      'next',
                                      showNextTweet);
            }
        });

    }

    // Show Delicious links
    updateDelicious();

    // If this is the index page, setup the Twitter stream
    if ($('body').hasClass('index'))
        setupTwitter();

});

// Create links for urls, users, and hashtags
function twittify(tweet) {

    var linkUrl = function(s) {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        return s.replace(regexp,"$1");
    }

    var linkUser = function(s) {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        return s.replace(regexp,"@$1");
    }

    var linkHash = function(s) {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        return s.replace(regexp, ' #$1');
    }

    return linkHash(linkUser(linkUrl(tweet)));

}

/*
  The non-search twitter APIs return inconsistently-formatted dates, which
  Date.parse cannot handle in IE. We therefore perform the following
  transformation:

  Wed Apr 29 08:53:31 +0000 2009
  =>
  Wed, Apr 29 2009 08:53:31 +0000
*/
function parseDate(s) {
    return Date.parse(s.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,
                                '$1,$2$4$3'));
}

// Turn a date/time string into a relative time
function relativeTime(time) {

    var parsedDate = parseDate(time);
    var relativeTo = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relativeTo.getTime() - parsedDate) / 1000);

    var pluralize = function(singular, n) {
        var plurals = {
            'minuut' : 'minuten',
            'uur'    : 'uur',
            'dag'    : 'dagen'
        };
        return '' + n + ' ' + (n == 1 ? singular : plurals[singular]);
    };

    if (delta < 60)
        return 'seconden geleden';
    else if (delta < (60 * 60))
        return pluralize('minuut', parseInt(delta / 60)) + ' geleden';
    else if (delta < (24 * 60 * 60))
        return pluralize('uur', parseInt(delta / 3600)) + ' geleden';
    else
        return pluralize('dag', parseInt(delta / 86400)) + ' geleden';

}

// Create a short description from a date string
function shortDate(s) {

    var months = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
                  'jul', 'aug', 'sep', 'okt', 'nov', 'dec'];

    if (!s)
        return (new Date).getDate() + ' ' + months[(new Date).getMonth() + 1];

    var d = s.match(/^\d{4}-(\d{2})-(\d{2}).*$/);
    if (d != null)
        return d[2] + ' ' + months[parseInt(d[1]) - 1];

    return '';

}
<commit_msg>Fix for IE: arrays dont have .indexOf() method.<commit_after>/***********************************************************************

    Check in, check uit

    Copyright 2010, Martijn Vermaat <martijn@vermaat.name>

      http://checkincheckuit.nl
      http://svn.vermaat.name/checkincheckuit

    Licensed under the MIT license, see the LICENSE file

      http://en.wikipedia.org/wiki/Mit_license

    Some of the Twitter handling code was adapted from the jQuery
    plugin Tweet!, found at http://tweet.seaofclouds.com/

    This code uses:
      jQuery          http://jquery.com
      jQuery Timers   http://plugins.jquery.com/project/timers

***********************************************************************/

$(document).ready(function() {

    var twitterSearch = 'ovchipkaart OR chipkaart OR ovchip';
    var twitterCount = 50;
    var twitterBlacklist = ['Regio_Alphen',
                            'Regio_Leiden',
                            'LeidenNL',
                            'Regio_Duin_Bol',
                            'Edestad',
                            'nieuwsede',
                            'edenieuwspunt.nl',
                            'nieuwsinutrecht',
                            'UtrechtNL',
                            'rtvutrecht',
                            'echo_utrecht',
                            'regio_nieuws',
                            'hetlokalenieuws',
                            'Nieuwsbekijken',
                            'totaalnieuwsweb',
                            'De_Pers',
                            '123nieuws',
                            'nieuwsnld',
                            'economie_nieuws',
                            'treinreizigernl',
                            'doormijverloren',
                            'doormijgevonden',
                            'ov_chipkaart'];
    var twitterDisplayTime = 1000 * 8;
    var twitterFadeTime = 800;
    /*
      There seems to be a bug, where animations are not smooth when the
      interval is specified as a string, e.g. '5s'.
    */
    var twitterReloadTime = 1000 * 60 * 5;

    var deliciousUser = 'checkuitcheckin';
    var deliciousTag = 'nieuws';
    var deliciousCount = 10;

    // Unfortunately, twitter query cannot exceed 140 characters
    var twitterUrl = 'http://search.twitter.com/search?&q='
        + encodeURIComponent(twitterSearch);
    var twitterApiUrl = 'http://search.twitter.com/search.json?&q='
        + encodeURIComponent(twitterSearch)
        + '&rpp=' + twitterCount + '&callback=?';
    var initialTweet = true;
    var tweets = [];
    var currentTweet = 0;

    var deliciousUrl = 'http://delicious.com/' + deliciousUser
        + '/' + deliciousTag;
    var deliciousApiUrl = 'http://feeds.delicious.com/v2/json/'
        + deliciousUser + '/' + deliciousTag
        + '?count=' + deliciousCount + '&callback=?';

    // Load Twitter search results and call callback function
    function updateTwitter(callback) {

        // http://apiwiki.twitter.com/Return-Values

        $.getJSON(twitterApiUrl, function(data) {

            currentTweet = 0;
            tweets = [];

            $.each((data.results || data), function(i, tweet) {
                var user = tweet.from_user || tweet.user.screen_name;
                if ($.inArray(user, twitterBlacklist) == -1) {
                    tweets.push({
                        text    : twittify(tweet.text),
                        user    : user,
                        date    : relativeTime(tweet.created_at),
                        url     : 'http://twitter.com/' + user
                                  + '/statuses/' + tweet.id,
                        userUrl : 'http://twitter.com/' + user
                    });
                }
            });

            if ($.isFunction(callback)) callback();

        });

    }

    // Load Delicious links and show them on the page
    function updateDelicious() {

        // http://delicious.com/help/feeds

        $.getJSON(deliciousApiUrl, function(data) {
            var list = $('
').appendTo($('#delicious'));
            $.each((data.results || data), function(i, item) {
                list.append($('
').text(shortDate(item.dt)));
                list.append($('
').append(
                    $('').attr('href', item.u).text(item.d)));
            });
            $('#delicious').append($('
').append(
                $('Meer nieuwsberichten...').attr('href', deliciousUrl)));
        });

    }

    // Advance to the next twee
    function showNextTweet() {
        if (tweets.length < 1) return;
        currentTweet = (currentTweet + 1) % tweets.length;
        showTweet();
    }

    // Like the function above, with a minor difference
    function showPreviousTweet() {
        if (tweets.length < 1) return;
        currentTweet = (tweets.length + currentTweet - 1) % tweets.length;
        showTweet();
    }

    /*
      Show the current tweet on the page. If this is the first twee we show,
      do just that. Otherwise fadeout the old tweet and fadein the new.
    */
    function showTweet() {

        var show = function() {
            var tweet = tweets[currentTweet];
            var pane = $('#content .tweet');
            /*
              The documentation (and experience) tells us we get the tweet
              text 'escaped and HTML encoded'.
              I still don't like to .html() this into the page, but being more
              cautious would make twittify() much more involved.

              http://apiwiki.twitter.com/Return-Values
            */
            pane.find('.text').html(tweet.text);
            pane.find('h2').empty().append(
                $('').attr('href', tweet.userUrl).text('@' + tweet.user));
            pane.find('h2').append(
                $('').attr('href', tweet.url).text(tweet.date).addClass(
                    'date'));
        }

        if (initialTweet)
            show();
        else
            $("#content .tweet").fadeOut(twitterFadeTime, function () {
                show();
                $("#content .tweet").fadeIn(twitterFadeTime);
            });

        initialTweet = false;

    }

    // Setup the Twitter stream
    function setupTwitter() {

        // Get tweets, show the first one, and skip to next tweet every 5 seconds
        updateTwitter(function() {

            if (tweets.length > 0)
                showTweet();

            if (tweets.length > 1) {

                $(document).everyTime(twitterDisplayTime,
                                      'next',
                                      showNextTweet);

                // We add navigation links and reset the skip timer on click
                $('#content').append($('
').append(
                    $('
<
').click(function() {
                        showPreviousTweet();
                        $(document).stopTime('next');
                        $(document).everyTime(twitterDisplayTime,
                                              'next',
                                              showNextTweet);
                    })
                ).append(
                    $('
>
').click(function() {
                        showNextTweet();
                        $(document).stopTime('next');
                        $(document).everyTime(twitterDisplayTime,
                                              'next',
                                              showNextTweet);
                    })
                ));

            }

        });

        // Every 5 minutes, get tweets and start at the latest tweet again
        $(document).everyTime(twitterReloadTime, 'reload', updateTwitter);

        // Show link to Twitter search results
        $('#content').append($('
').append(
            $('meer...').attr('href', twitterUrl)));

        // Pause auto advancing of tweets on mouse hover
        $('#content .tweet').hover(function() {
            $(document).stopTime('next');
        }, function() {
            if (tweets.length > 1) {
                // If we directly want to advance on hover-out, uncomment this
                //showNextTweet();
                $(document).everyTime(twitterDisplayTime,
                                      'next',
                                      showNextTweet);
            }
        });

    }

    // Show Delicious links
    updateDelicious();

    // If this is the index page, setup the Twitter stream
    if ($('body').hasClass('index'))
        setupTwitter();

});

// Create links for urls, users, and hashtags
function twittify(tweet) {

    var linkUrl = function(s) {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        return s.replace(regexp,"$1");
    }

    var linkUser = function(s) {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        return s.replace(regexp,"@$1");
    }

    var linkHash = function(s) {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        return s.replace(regexp, ' #$1');
    }

    return linkHash(linkUser(linkUrl(tweet)));

}

/*
  The non-search twitter APIs return inconsistently-formatted dates, which
  Date.parse cannot handle in IE. We therefore perform the following
  transformation:

  Wed Apr 29 08:53:31 +0000 2009
  =>
  Wed, Apr 29 2009 08:53:31 +0000
*/
function parseDate(s) {
    return Date.parse(s.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i,
                                '$1,$2$4$3'));
}

// Turn a date/time string into a relative time
function relativeTime(time) {

    var parsedDate = parseDate(time);
    var relativeTo = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relativeTo.getTime() - parsedDate) / 1000);

    var pluralize = function(singular, n) {
        var plurals = {
            'minuut' : 'minuten',
            'uur'    : 'uur',
            'dag'    : 'dagen'
        };
        return '' + n + ' ' + (n == 1 ? singular : plurals[singular]);
    };

    if (delta < 60)
        return 'seconden geleden';
    else if (delta < (60 * 60))
        return pluralize('minuut', parseInt(delta / 60)) + ' geleden';
    else if (delta < (24 * 60 * 60))
        return pluralize('uur', parseInt(delta / 3600)) + ' geleden';
    else
        return pluralize('dag', parseInt(delta / 86400)) + ' geleden';

}

// Create a short description from a date string
function shortDate(s) {

    var months = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
                  'jul', 'aug', 'sep', 'okt', 'nov', 'dec'];

    if (!s)
        return (new Date).getDate() + ' ' + months[(new Date).getMonth() + 1];

    var d = s.match(/^\d{4}-(\d{2})-(\d{2}).*$/);
    if (d != null)
        return d[2] + ' ' + months[parseInt(d[1]) - 1];

    return '';

}
<|endoftext|>


<commit_before>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/
    //
    // Hack city!!! Turn off the component cache so that we can enable hot reloading of components
    //
    isStaticHtmlPageApp = false
    //
    //
    //

    var argBaseComponentId = null
    var cardId = null
    await loadV2("appEmbed")

    if (args) {
        argBaseComponentId = args.base_component_id
        cardId = args.card_id
    }
    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                        <input  class='caption' style='display: inline-block;' v-if='edit_name' v-model='new_name'></input>
                        <button type=button class='btn btn-primary' style='margin-left: 10px' v-if='edit_name' v-on:click='rename(new_name)'>Save new name</button>

                            <select v-if='false' class="custom-select" v-model="selected_app" v-bind:onchange='load_new_app(selected_app)'>
                              <option value='' selected>Select an application to edit</option>
                              <option v-for='app in apps'
                                      v-bind:value="app.base_component_id"
                                      >{{app.display_name}}</option>
                            </select>
                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id,null)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>
                            <button  v-if='(editor_component != "editor_component") && (!read_only)' type=button class=' btn btn-secondary'   v-on:click='editAsText()' >Edit as text</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='setTimeout(function(){save(base_component_id, code_id,null)},100)'
                                                  type="button" class="btn btn-primary btn-sm">

                                                      Save changes
                                         </button>
                          </component>

                                    {{show_new_tab_tooltip?"Open page in new browser tab (shareable :)":""}}
                                    {{show_open_app_tooltip?"Create shippable HTML file":""}}

                                ← → ↻
                                ❏

                                    <input  readonly size="40" style='font-size: 13px;'
                                        v-bind:value='"http://" + location.hostname + ":" + location.port + "/app/" + base_component_id + ".html"'></input>

                                ♨

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit",
               show_name:           true,
               edit_name:           false,
               new_name:            "",
               show_new_tab_tooltip:false,
               show_open_app_tooltip:false
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: async function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                this.mode      = "edit"

                var text = await this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                await this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                this.mode      = "edit"

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true

                this.mode      = "edit"
            },

            rename: function(nn) {
                this.edit_name = false
                this.show_name = true

                nn = nn.replace(/[\W_]+/g,"_");
                this.copyAppMethod( this.base_component_id , nn)
            },

            editAsText: async function() {
                var mm = this
                //zzz
                var text = await this.$refs.editorComponentRef.getText()
                //alert(text.indexOf("editors_old"))

                var eds = saveHelper.getValueOfCodeString(text, "editors")
                if (eds) {
                    text = saveHelper.deleteCodeString(text, "editors")
                    text = saveHelper.insertCodeString(text, "editors_old",eds)
                }

                await mm.save(   this.base_component_id,   this.code_id,   text   )

                await mm.load_new_app( this.base_component_id )
                //alert(text.indexOf("editors_old"))
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId , newAppId) {
                var mm = this
                callDriverMethod( {driver_name: "copyApp",
                                   method_name: "copyAppshareApp"}
                                  ,{
                                      base_component_id:    appId,
                                      new_app_id:           newAppId
                                   }
                            ,
                            async function(result) {
                                await mm.load_new_app( result.value.base_component_id )
                                mm.$root.$emit('message', {
                                                                type:               "insert_app_at",
                                                                base_component_id:   result.value.base_component_id,
                                                                card_index:          mm.card_index
                                                            })

                            })
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id , textIn) {
               console.log("1) AppEditor: save")
               var text =  textIn
               if (text == null) {
                    text = await this.$refs.editorComponentRef.getText()
               }
               console.log("5) AppEditor: getText done")

               var mm = this
               if (mm.read_only) {
                    return
               }
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text,
                        options:                {
                                                    sub_components: Object.keys(dev_app_component_loaded)
                                                }
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               dev_app_component_loaded = new Object()
               this.editor_loaded = false
               this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
                mm.selected_app = ""

               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                       }
                       mm.code = code
                       mm.code_id = codeId
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await loadV2(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           var mm = this
           //alert(argBaseComponentId)
           //alert(this.app_id)
            if (this.app_id) {
                //alert(this.app_id)
                //this.base_component_id = app_id

                component_loaded[this.app_id]           = false
                dev_app_component_loaded[this.app_id]   = false
                component_cache[this.app_id]            = null

                this.load_app(this.app_id)
            }
           else if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<commit_msg>Trying to fix save function<commit_after>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/
    //
    // Hack city!!! Turn off the component cache so that we can enable hot reloading of components
    //
    isStaticHtmlPageApp = false
    //
    //
    //

    var argBaseComponentId = null
    var cardId = null
    await loadV2("appEmbed")

    if (args) {
        argBaseComponentId = args.base_component_id
        cardId = args.card_id
    }
    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                        <input  class='caption' style='display: inline-block;' v-if='edit_name' v-model='new_name'></input>
                        <button type=button class='btn btn-primary' style='margin-left: 10px' v-if='edit_name' v-on:click='rename(new_name)'>Save new name</button>

                            <select v-if='false' class="custom-select" v-model="selected_app" v-bind:onchange='load_new_app(selected_app)'>
                              <option value='' selected>Select an application to edit</option>
                              <option v-for='app in apps'
                                      v-bind:value="app.base_component_id"
                                      >{{app.display_name}}</option>
                            </select>
                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id,null)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>
                            <button  v-if='(editor_component != "editor_component") && (!read_only)' type=button class=' btn btn-secondary'   v-on:click='editAsText()' >Edit as text</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='setTimeout(async function(){await save(base_component_id, code_id,null)},100)'
                                                  type="button" class="btn btn-primary btn-sm">

                                                      Save changes
                                         </button>
                          </component>

                                    {{show_new_tab_tooltip?"Open page in new browser tab (shareable :)":""}}
                                    {{show_open_app_tooltip?"Create shippable HTML file":""}}

                                ← → ↻
                                ❏

                                    <input  readonly size="40" style='font-size: 13px;'
                                        v-bind:value='"http://" + location.hostname + ":" + location.port + "/app/" + base_component_id + ".html"'></input>

                                ♨

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit",
               show_name:           true,
               edit_name:           false,
               new_name:            "",
               show_new_tab_tooltip:false,
               show_open_app_tooltip:false
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: async function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                this.mode      = "edit"

                var text = await this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                await this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                this.mode      = "edit"

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true

                this.mode      = "edit"
            },

            rename: function(nn) {
                this.edit_name = false
                this.show_name = true

                nn = nn.replace(/[\W_]+/g,"_");
                this.copyAppMethod( this.base_component_id , nn)
            },

            editAsText: async function() {
                var mm = this
                //zzz
                var text = await this.$refs.editorComponentRef.getText()
                //alert(text.indexOf("editors_old"))

                var eds = saveHelper.getValueOfCodeString(text, "editors")
                if (eds) {
                    text = saveHelper.deleteCodeString(text, "editors")
                    text = saveHelper.insertCodeString(text, "editors_old",eds)
                }

                await mm.save(   this.base_component_id,   this.code_id,   text   )

                await mm.load_new_app( this.base_component_id )
                //alert(text.indexOf("editors_old"))
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId , newAppId) {
                var mm = this
                callDriverMethod( {driver_name: "copyApp",
                                   method_name: "copyAppshareApp"}
                                  ,{
                                      base_component_id:    appId,
                                      new_app_id:           newAppId
                                   }
                            ,
                            async function(result) {
                                await mm.load_new_app( result.value.base_component_id )
                                mm.$root.$emit('message', {
                                                                type:               "insert_app_at",
                                                                base_component_id:   result.value.base_component_id,
                                                                card_index:          mm.card_index
                                                            })

                            })
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id , textIn) {
               console.log("1) AppEditor: save")
               var text =  textIn
               if (text == null) {
                    text = await this.$refs.editorComponentRef.getText()
               }
               console.log("5) AppEditor: getText done")

               var mm = this
               if (mm.read_only) {
                    return
               }
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text,
                        options:                {
                                                    sub_components: Object.keys(dev_app_component_loaded)
                                                }
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               dev_app_component_loaded = new Object()
               this.editor_loaded = false
               this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
                mm.selected_app = ""

               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                            mm.code = code
                            mm.code_id = codeId
                       }
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await loadV2(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           var mm = this
           //alert(argBaseComponentId)
           //alert(this.app_id)
            if (this.app_id) {
                //alert(this.app_id)
                //this.base_component_id = app_id

                component_loaded[this.app_id]           = false
                dev_app_component_loaded[this.app_id]   = false
                component_cache[this.app_id]            = null

                this.load_app(this.app_id)
            }
           else if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<|endoftext|>


<commit_before>define([], function () {
    if (window.__CRYPTPAD_TEST_OBJ_) { return window.__CRYPTPAD_TEST_OBJ_; }
    // XXX localhost secureiframe fix
    var out = function () {};
    out.options = {};
    out.testing = false;
    out.registerInner = function () { };
    out.registerOuter = function () { };
    return out;

    var locks = [];
    var tests = [];
    var failed = false;
    var totalTests = 0;
    var out = window.__CRYPTPAD_TEST_OBJ__ = function (f) {
        if (!out.testing) { return; }
        tests.push(f);
        totalTests++;
        var runLock = function (lock) {
            lock(function () { setTimeout(function () { runLock(locks.shift()); }); });
        };
        f({
            pass: function () {
                if (failed) { return; }
                var i = tests.indexOf(f);
                if (i === -1) {
                    throw new Error("Pass called on an unknown test (called multiple times?)");
                }
                tests.splice(i, 1);
                if (!tests.length) {
                    console.log("Completed " + totalTests + " successfully");
                    out.passed();
                }
            },
            fail: function (reason) {
                failed = true;
                out.failed(reason);
            },
            lock: function (f) {
                locks.push(f);
                if (locks.length === 1) {
                    runLock(locks.shift());
                }
            },
            assert: function (expr) {
                if (expr || failed) { return; }
                failed = true;
                out.failed("Failed assertion");
            }
        });
    };

    out.passed = out.failed = out;
    var enableAuto = function () {
        console.log("Enable auto testing 1 " + window.origin);
        if (window.__CRYPTPAD_TEST__) { return; }
        var cpt = window.__CRYPTPAD_TEST__ = {
            data: [],
            getData: function () {
                var data = JSON.stringify(cpt.data);
                cpt.data = [];
                return data;
            }
        };

        // jshint -W103
        var errProto = (new Error()).__proto__;
        var doLog = function (o) {
            var s;
            if (typeof(o) === 'object' && o.__proto__ === errProto) {
                s = JSON.stringify([ o.message, o.stack ]);
            } else if (typeof(s) !== 'string') {
                try {
                    s = JSON.stringify(o);
                } catch (e) {
                    s = String(o);
                }
            }
            var out = [s];
            try { throw new Error(); } catch (e) { out.push(e.stack.split('\n')[3]); }
            cpt.data.push({ type: 'log', val: out.join('') });
        };

        window.console._error = window.console.error;
        window.console._log = window.console.log;
        window.console.error = function (e) { window.console._error(e); doLog(e); };
        window.console.log = function (l) { window.console._log(l); doLog(l); };

        window.onerror = function (msg, url, lineNo, columnNo, e) {
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: {
                    message: e ? e.message : msg,
                    stack: e ? e.stack : (url + ":" + lineNo)
                }
            });
        };
        require.onError = function (e) {
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: { message: e.message, stack: e.stack }
            });
        };
        out.testing = 'auto';
        out.passed = function () {
            cpt.data.push({
                type: 'report',
                val: 'passed'
            });
        };
        out.failed = function (reason) {
            var e;
            try { throw new Error(reason); } catch (err) { e = err; }
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: { message: e.message, stack: e.stack }
            });
        };

        out.registerInner = function (sframeChan) {
            sframeChan.whenReg('EV_TESTDATA', function () {
                cpt.data.forEach(function (x) { sframeChan.event('EV_TESTDATA', x); });
                // override cpt.data.push() with a function which will send the content to the
                // outside where it will go on the outer window cpt.data array.
                cpt = window.__CRYPTPAD_TEST__ = {
                    data: {
                        push: function (elem) {
                            sframeChan.event('EV_TESTDATA', elem);
                        }
                    },
                    getData: function () {
                        throw new Error('getData should never be called from the inside');
                    }
                };
            });
        };
        out.registerOuter = function (sframeChan) {
            sframeChan.on('EV_TESTDATA', function (data) { cpt.data.push(data); });
        };
    };
    var enableManual = function () {
        out.testing = 'manual';
        console.log('manual testing enabled');
        out.passed = function () {
            window.alert("Test passed");
        };
        out.failed = function (reason) {
            try { throw new Error(reason); } catch (err) { console.log(err.stack); }
            window.alert("Test failed [" + reason + "]");
        };
        out.registerInner = function () { };
        out.registerOuter = function () { };
    };

    out.options = {};
    out.testing = false;
    out.registerInner = function () { };
    out.registerOuter = function () { };

    try {
        if (document.cookie.indexOf('test=') === 0) {
            var x = JSON.parse(decodeURIComponent(document.cookie.replace('test=', '')));
            if (x.test === 'auto') {
                out.options = x.opts;
                enableAuto('auto');
                console.log("Enable auto testing " + window.origin);
            } else if (x.test === 'manual') {
                out.options = x.opts;
                enableManual();
                console.log("Enable manual testing " + window.origin);
            }
        }
    } catch (e) { }

    return out;
});
<commit_msg>lint compliance<commit_after>define([], function () {
    if (window.__CRYPTPAD_TEST_OBJ_) { return window.__CRYPTPAD_TEST_OBJ_; }
/*
    // XXX localhost secureiframe fix
    var out = function () {};
    out.options = {};
    out.testing = false;
    out.registerInner = function () { };
    out.registerOuter = function () { };
    return out;
*/

    var locks = [];
    var tests = [];
    var failed = false;
    var totalTests = 0;
    var out = window.__CRYPTPAD_TEST_OBJ__ = function (f) {
        if (!out.testing) { return; }
        tests.push(f);
        totalTests++;
        var runLock = function (lock) {
            lock(function () { setTimeout(function () { runLock(locks.shift()); }); });
        };
        f({
            pass: function () {
                if (failed) { return; }
                var i = tests.indexOf(f);
                if (i === -1) {
                    throw new Error("Pass called on an unknown test (called multiple times?)");
                }
                tests.splice(i, 1);
                if (!tests.length) {
                    console.log("Completed " + totalTests + " successfully");
                    out.passed();
                }
            },
            fail: function (reason) {
                failed = true;
                out.failed(reason);
            },
            lock: function (f) {
                locks.push(f);
                if (locks.length === 1) {
                    runLock(locks.shift());
                }
            },
            assert: function (expr) {
                if (expr || failed) { return; }
                failed = true;
                out.failed("Failed assertion");
            }
        });
    };

    out.passed = out.failed = out;
    var enableAuto = function () {
        console.log("Enable auto testing 1 " + window.origin);
        if (window.__CRYPTPAD_TEST__) { return; }
        var cpt = window.__CRYPTPAD_TEST__ = {
            data: [],
            getData: function () {
                var data = JSON.stringify(cpt.data);
                cpt.data = [];
                return data;
            }
        };

        // jshint -W103
        var errProto = (new Error()).__proto__;
        var doLog = function (o) {
            var s;
            if (typeof(o) === 'object' && o.__proto__ === errProto) {
                s = JSON.stringify([ o.message, o.stack ]);
            } else if (typeof(s) !== 'string') {
                try {
                    s = JSON.stringify(o);
                } catch (e) {
                    s = String(o);
                }
            }
            var out = [s];
            try { throw new Error(); } catch (e) { out.push(e.stack.split('\n')[3]); }
            cpt.data.push({ type: 'log', val: out.join('') });
        };

        window.console._error = window.console.error;
        window.console._log = window.console.log;
        window.console.error = function (e) { window.console._error(e); doLog(e); };
        window.console.log = function (l) { window.console._log(l); doLog(l); };

        window.onerror = function (msg, url, lineNo, columnNo, e) {
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: {
                    message: e ? e.message : msg,
                    stack: e ? e.stack : (url + ":" + lineNo)
                }
            });
        };
        require.onError = function (e) {
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: { message: e.message, stack: e.stack }
            });
        };
        out.testing = 'auto';
        out.passed = function () {
            cpt.data.push({
                type: 'report',
                val: 'passed'
            });
        };
        out.failed = function (reason) {
            var e;
            try { throw new Error(reason); } catch (err) { e = err; }
            cpt.data.push({
                type: 'report',
                val: 'failed',
                error: { message: e.message, stack: e.stack }
            });
        };

        out.registerInner = function (sframeChan) {
            sframeChan.whenReg('EV_TESTDATA', function () {
                cpt.data.forEach(function (x) { sframeChan.event('EV_TESTDATA', x); });
                // override cpt.data.push() with a function which will send the content to the
                // outside where it will go on the outer window cpt.data array.
                cpt = window.__CRYPTPAD_TEST__ = {
                    data: {
                        push: function (elem) {
                            sframeChan.event('EV_TESTDATA', elem);
                        }
                    },
                    getData: function () {
                        throw new Error('getData should never be called from the inside');
                    }
                };
            });
        };
        out.registerOuter = function (sframeChan) {
            sframeChan.on('EV_TESTDATA', function (data) { cpt.data.push(data); });
        };
    };
    var enableManual = function () {
        out.testing = 'manual';
        console.log('manual testing enabled');
        out.passed = function () {
            window.alert("Test passed");
        };
        out.failed = function (reason) {
            try { throw new Error(reason); } catch (err) { console.log(err.stack); }
            window.alert("Test failed [" + reason + "]");
        };
        out.registerInner = function () { };
        out.registerOuter = function () { };
    };

    out.options = {};
    out.testing = false;
    out.registerInner = function () { };
    out.registerOuter = function () { };

    try {
        if (document.cookie.indexOf('test=') === 0) {
            var x = JSON.parse(decodeURIComponent(document.cookie.replace('test=', '')));
            if (x.test === 'auto') {
                out.options = x.opts;
                enableAuto('auto');
                console.log("Enable auto testing " + window.origin);
            } else if (x.test === 'manual') {
                out.options = x.opts;
                enableManual();
                console.log("Enable manual testing " + window.origin);
            }
        }
    } catch (e) { }

    return out;
});
<|endoftext|>