code
stringlengths 2
1.05M
|
---|
//常量
//Canvas
const VERSION="v2067UR";
const WINDOW_X=1000;
const WINDOW_Y=600;
const HIT_FULLSCREEN=new PIXI.Rectangle(-10000,-10000,20000,20000);
const RADIUS=170;
const EDGE_DIST=Math.sqrt(WINDOW_X*WINDOW_X+WINDOW_Y*WINDOW_Y)/2-RADIUS;
const CENTER_POS=new PIXI.Point(WINDOW_X/2,WINDOW_Y/2);
const MAX_SCENE=5;
//Anchor
const AC_CENTER=new PIXI.Point(0.5,0.5);
const AC_LEFT=new PIXI.Point(0,0.5);
const AC_RIGHT=new PIXI.Point(1,0.5);
//游戏参数
const BS_CONST=new Array(Math.PI*2/3,Math.PI/2,Math.PI*5/12,Math.PI/3,Math.PI/4,Math.PI/6);
const SP_CONST=new Array(0.1,0.15,0.2,0.25,0.3,0.4);
const SP_TIME_CONST=new Array(3400,2300,1700,1400,1200,900);
const AG_CONST=new Array(0,Math.PI/6,Math.PI/3,Math.PI/2,Math.PI*2/3,Math.PI*5/6);
//计分
const BASE_NONE=100;
const BASE_KEY=2.5;
//Beatmap总数据库
var GAME_DATA=new Array();
//资源变量
var texPD=new Array();
for (var i=0;i<=5;i++)
texPD[i]=new PIXI.Texture.fromImage("asset/paddle"+i+".png");
var texB=new PIXI.Texture.fromImage("asset/beat.png");
//全局变量
var gameScene=0; //0:初始 1:选歌 2:载入 3:游戏 4:结算 5:暂停
var useMouse=true; //鼠标开关
var mouseX,mouseY; //鼠标坐标
var padPos=0; //挡板位置(0-2pi)
var timeStart; //开始时间(绝对)
var timePlay; //进行时间(自timeStart)
var timePause; //上次暂停时间(自timeStart)
var timeLastkey=0; //上次按键时间(绝对)
var timeOffset=0; //打击误差
//游戏内全局变量
var gameBeats=new Array(); //Beat数组
var gameBeatsStart=0; //Beat数组起点
var gameBeatsEnd=0; //Beat数组终点
var gameBS; //挡板大小(0-5)
var gameSP; //Beat速度(0-5)
var gameAG; //Beat倾角大小(0-5)
var gameBSStd; //原谱挡板大小(0-5)
var gameSPStd; //原谱Beat速度(0-5)
var gameAGStd; //原谱Beat倾角大小(0-5)
var gameHP; //(0-1)
var gameCombo;
var gameLastCombo;
var gameMaxCombo;
var gameBaseScore; //0cb max 得分
var gameHitMax;
var gameHitGood;
var gameHitBad;
var gameMiss;
var gameAcc; //(0-10000)显示为0.00-100.00
var gameRank; //(0-80)显示为0.0-8.0
var gameScore;
var gameBeatmapID=0; //Beatmap代号
var gameDiff; //Beatmap难度
var gameBpm; //Beatmap BPM
var gameBmTotal; //Beatmap物件数
//FPS指示器
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild( stats.domElement );
//转换场景
function changeScene(s)
{
gameScene=s;
for (var i=0;i<=MAX_SCENE;i++)
{
scene[i].visible=false;
scene[i].interactive=false;
}
scene[s].visible=true;
scene[s].interactive=true;
}
//加载游戏参数
function loadJSON(n,full,callback)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonres=JSON.parse(xmlhttp.responseText);
gameBSStd=jsonres.size;
gameSPStd=jsonres.speed;
gameAGStd=jsonres.angle;
gameDiff=jsonres.diff;
gameBpm=jsonres.bpm;
if (full)
{
for (var i=0;i<gameBeats.length;i++)
scene[3].removeChild(gameBeats[i].sprite);
gameBeats=new Array();
for (var i=0;jsonres.beats[i]!=null;i++)
gameBeats[i]=new Beat(jsonres.beats[i].time+timeOffset,jsonres.beats[i].degree,jsonres.beats[i].angle);
gameBmTotal=gameBeats.length;
audio.src="data/"+n+".mp3";
audio.load();
}
callback();
}
}
xmlhttp.open("GET","data/"+n+".json",true);
xmlhttp.send();
}
//计算夹角
function diffAngle(a,b)
{
var diff=Math.abs(a-b);
if (diff>Math.PI)
return 2*Math.PI-diff;
else
return diff;
}
//循环递增
function cycleNext(a,b)
{
if (b==a-1)
return 0;
return b+1;
}
//循环递减
function cyclePrev(a,b)
{
if (b==0)
return a-1;
return b-1;
}
//限制范围
function bound(a,b,x)
{
if (x<a)
return a;
if (x>b)
return b;
return x;
}
//延迟t时间播放声音s
function playSound(s,t)
{
setTimeout(function()
{
//s.pause();
s.currentTime=0;
s.play();
}
,t);
}
//Beat 类
function Beat(time,degree,fly)
{
//打击时间
this.time=time;
//轨道终点倾角
this.degree=degree*2*Math.PI;
//轨道实际倾角
this.fly=this.degree+(fly-0.5)*AG_CONST[gameAG];
//终点坐标
this.x=RADIUS*Math.cos(this.degree);
this.y=RADIUS*Math.sin(this.degree);
//速度向量
this.dx=Math.cos(this.fly);
this.dy=Math.sin(this.fly);
//距终点距离
this.dist=0;
//Sprite对象
this.sprite=new PIXI.Sprite(texB);
//颜色矩阵
if (degree<1/12)
var colorMatrix=[1,0,0,0,0,-4.5*degree+0.625,0,0,0,0,0.25,0,0,0,0,1];
else if (degree>=1/12 && degree<3/12)
var colorMatrix=[1,0,0,0,0,0.25,0,0,0,0,4.5*degree-0.125,0,0,0,0,1];
else if (degree>=3/12 && degree<5/12)
var colorMatrix=[-4.5*degree+2.125,0,0,0,0,0.25,0,0,0,0,1,0,0,0,0,1];
else if (degree>=5/12 && degree<7/12)
var colorMatrix=[0.25,0,0,0,0,4.5*degree-1.625,0,0,0,0,1,0,0,0,0,1];
else if (degree>=7/12 && degree<9/12)
var colorMatrix=[0.25,0,0,0,0,1,0,0,0,0,-4.5*degree+3.625,0,0,0,0,1];
else if (degree>=9/12 && degree<11/12)
var colorMatrix=[4.5*degree-3.125,0,0,0,0,1,0,0,0,0,0.25,0,0,0,0,1];
else if (degree>=11/12)
var colorMatrix=[1,0,0,0,0,-4.5*degree+5.125,0,0,0,0,0.25,0,0,0,0,1];
//颜色滤镜
var filter=new PIXI.ColorMatrixFilter();
filter.matrix=colorMatrix;
this.sprite.filters=[filter];
//中心点
this.sprite.anchor=AC_CENTER;
//可见度
this.sprite.visible=false;
//加入该Sprite
scene[3].addChild(this.sprite);
}
// 更新数据和Sprite
Beat.prototype.update=function(callback)
{
//Sprite更新
if (this.time-timePlay<SP_TIME_CONST[gameSP])
{
this.dist=SP_CONST[gameSP]*(this.time-timePlay);
this.sprite.position.x=WINDOW_X/2+this.x+this.dist*this.dx;
this.sprite.position.y=WINDOW_Y/2+this.y+this.dist*this.dy;
if (this.sprite.position.x>=100 && this.sprite.position.x<=WINDOW_X-100)
this.sprite.visible=true;
else
this.sprite.visible=false;
}
else
this.sprite.visible=false;
//击打判定
if (this.time-timePlay<20)
{
//Hit
if (diffAngle(padPos,this.degree)<=BLOCK_SIZE/2)
{
gameCombo++;
if (gameCombo>gameMaxCombo)
gameMaxCombo=gameCombo;
if (gameHP>=0.6)
{
gameScore=Math.floor(gameScore+gameBaseScore*(1+Math.log(gameCombo)));
gameHitMax++;
}
else if (gameHP>=0.3)
{
gameScore=Math.floor(gameScore+gameBaseScore/3*(1+Math.log(gameCombo)));
gameHitGood++;
}
else
{
gameScore=Math.floor(gameScore+gameBaseScore/6*(1+Math.log(gameCombo)));
gameHitBad++;
}
gameHP+=0.01;
playSound(hitsound,this.time-(new Date().getTime()-timeStart));
}
//Miss
else
{
gameLastCombo=gameCombo;
gameCombo=0;
gameMiss++;
gameHP-=Math.max(gameHP*0.05,0.02);
if (gameLastCombo>=5)
playSound(misssound,this.time-(new Date().getTime()-timeStart));
}
gameAcc=Math.floor(10000*(gameHitMax+gameHitGood+gameHitBad)/(gameHitMax+gameHitGood+gameHitBad+gameMiss));
this.sprite.visible=false;
gameBeatsStart++;
callback();
}
}
//游戏初始化
function gameInit()
{
gameHP=1;
gameCombo=0;
gameLastCombo=0;
gameMaxCombo=0;
gameHitMax=0;
gameHitGood=0;
gameHitBad=0;
gameMiss=0;
gameAcc=10000;
gameScore=0;
timePause=-1;
for (var i=0;i<gameBeats.length;i++)
gameBeats[i].sprite.visible=false;
gameBeatsStart=0;
gameBeatsEnd=0;
while (gameBeatsEnd<gameBmTotal && gameBeats[gameBeatsEnd].time<SP_TIME_CONST[gameSP])
gameBeatsEnd++;
}
//渲染器
var renderer=new PIXI.autoDetectRecommendedRenderer(WINDOW_X,WINDOW_Y);
renderer.clearBeforeRender=true;
document.body.appendChild(renderer.view);
var stage=new PIXI.Stage(0x000000);
//场景
var scene=new Array();
for (var i=0;i<=MAX_SCENE;i++)
{
scene[i]=new PIXI.DisplayObjectContainer();
stage.addChild(scene[i]);
}
//加载资源
scene[0].addChild(new PIXI.Text("",{font:"24px font1"})); //缓存字体
//音乐对象
var audio=document.createElement("audio");
document.body.appendChild(audio);
audio.preload="none";
var hitsound=document.createElement("audio");
document.body.appendChild(hitsound);
hitsound.src="sound/hitsound1.mp3";
hitsound.load();
var misssound=document.createElement("audio");
document.body.appendChild(misssound);
misssound.src="sound/misssound.mp3";
misssound.load();
//图形对象
var disk=new PIXI.Sprite.fromImage("asset/disk.png");
disk.position=CENTER_POS;
disk.anchor=AC_CENTER;
scene[3].addChild(disk);
var paddle=new PIXI.Sprite(texPD[2]);
paddle.position=CENTER_POS;
paddle.anchor=AC_CENTER;
paddle.filters=[new PIXI.ColorMatrixFilter()];
scene[3].addChild(paddle);
var center=new PIXI.Sprite.fromImage("asset/center.png");;
center.position=CENTER_POS;
center.anchor=AC_CENTER;
center.filters=[new PIXI.ColorMatrixFilter()];
scene[3].addChild(center);
var mask1=new PIXI.Graphics();
var mask2=new PIXI.Graphics();
var hp1=new PIXI.Sprite.fromImage("asset/hp.png");;
hp1.position=new PIXI.Point(50,WINDOW_Y/2);
hp1.anchor=AC_CENTER;
hp1.mask=mask1;
scene[3].addChild(hp1);
var hp2=new PIXI.Sprite.fromImage("asset/hp.png");;
hp2.position=new PIXI.Point(WINDOW_X-50,WINDOW_Y/2);
hp2.anchor=AC_CENTER;
hp2.mask=mask2;
scene[3].addChild(hp2);
//按钮
var button3Pause=new PIXI.Sprite.fromImage("asset/pause.png");
button3Pause.position=new PIXI.Point(100,WINDOW_Y);
button3Pause.anchor=new PIXI.Point(0,1);
button3Pause.buttonMode=true;
button3Pause.interactive=true;
button3Pause.click=function()
{
timePause=new Date().getTime()-timeStart;
audio.pause();
changeScene(5);
};
button3Pause.tap=button3Pause.click;
scene[3].addChild(button3Pause);
var button4Continue=new PIXI.Sprite.fromImage("asset/null.png");
button4Continue.position=new PIXI.Point(750,500);
button4Continue.anchor=AC_CENTER;
button4Continue.interactive=true;
button4Continue.hitArea=HIT_FULLSCREEN;
button4Continue.click=function()
{
changeScene(1);
};
button4Continue.tap=button4Continue.click;
scene[4].addChild(button4Continue);
var button5Resume=new PIXI.Sprite.fromImage("asset/pause1.png");
button5Resume.position=new PIXI.Point(WINDOW_X/2,150);
button5Resume.anchor=AC_CENTER;
button5Resume.buttonMode=true;
button5Resume.interactive=true;
button5Resume.click=function()
{
timeStart=new Date().getTime()-timePause;
audio.play();
changeScene(3);
};
button5Resume.tap=button5Resume.click;
scene[5].addChild(button5Resume);
var button5Restart=new PIXI.Sprite.fromImage("asset/pause2.png");
button5Restart.position=new PIXI.Point(WINDOW_X/2,300);
button5Restart.anchor=AC_CENTER;
button5Restart.buttonMode=true;
button5Restart.interactive=true;
button5Restart.click=function()
{
gameInit();
timeStart=new Date().getTime();
audio.currentTime=0;
audio.play();
changeScene(3);
};
button5Restart.tap=button5Restart.click;
scene[5].addChild(button5Restart);
var button5Quit=new PIXI.Sprite.fromImage("asset/pause3.png");
button5Quit.position=new PIXI.Point(WINDOW_X/2,450);
button5Quit.anchor=AC_CENTER;
button5Quit.buttonMode=true;
button5Quit.interactive=true;
button5Quit.click=function()
{
changeScene(1);
};
button5Quit.tap=button5Quit.click;
scene[5].addChild(button5Quit);
//选曲界面
var text1Ver=new PIXI.Text(VERSION,{font:"14px Consolas", fill:"#FFFFFF"});
text1Ver.position=new PIXI.Point(998,8);
text1Ver.anchor=AC_RIGHT;
scene[1].addChild(text1Ver);
var text1Offset=new PIXI.Text("Offset="+timeOffset,{font:"14px Consolas", fill:"#FFFFFF"});
text1Offset.position=new PIXI.Point(998,24);
text1Offset.anchor=AC_RIGHT;
scene[1].addChild(text1Offset);
var button1TitleL=new PIXI.Sprite.fromImage("asset/loading.png");
button1TitleL.position=new PIXI.Point(200,160);
button1TitleL.anchor=AC_CENTER;
button1TitleL.width=150;
button1TitleL.height=150;
button1TitleL.buttonMode=true;
button1TitleL.interactive=true;
button1TitleL.click=function()
{
gameBeatmapID=cyclePrev(GAME_DATA.length,gameBeatmapID);
loadJSON(GAME_DATA[gameBeatmapID][0],false,function(){
gameBS=gameBSStd;
gameSP=gameSPStd;
gameAG=gameAGStd;
});
};
button1TitleL.tap=button1TitleL.click;
scene[1].addChild(button1TitleL);
var text1Title=new PIXI.Text("",{font:"48px Segoe UI", fill:"#66CCFF"});
text1Title.position=new PIXI.Point(500,330);
text1Title.anchor=AC_CENTER;
scene[1].addChild(text1Title);
var button1Title=new PIXI.Sprite.fromImage("asset/loading.png");
button1Title.position=new PIXI.Point(500,140);
button1Title.anchor=AC_CENTER;
button1Title.width=250;
button1Title.height=250;
button1Title.buttonMode=true;
button1Title.interactive=true;
button1Title.click=function()
{
loadJSON(GAME_DATA[gameBeatmapID][0],true,function()
{
paddle.texture=texPD[gameBS];
BLOCK_SIZE=BS_CONST[gameBS];
gameBaseScore=BASE_NONE;
if (!useMouse)
gameBaseScore*=BASE_KEY;
button2Title.setTexture(GAME_DATA[gameBeatmapID][2]);
button2Title.width=250;
button2Title.height=250;
text2Title.setText(text1Title.text);
changeScene(2);
});
};
button1Title.tap=button1Title.click;
scene[1].addChild(button1Title);
var button1TitleR=new PIXI.Sprite.fromImage("asset/loading.png");
button1TitleR.position=new PIXI.Point(800,160);
button1TitleR.width=150;
button1TitleR.height=150;
button1TitleR.anchor=AC_CENTER;
button1TitleR.buttonMode=true;
button1TitleR.interactive=true;
button1TitleR.click=function()
{
gameBeatmapID=cycleNext(GAME_DATA.length,gameBeatmapID);
loadJSON(GAME_DATA[gameBeatmapID][0],false,function(){
gameBS=gameBSStd;
gameSP=gameSPStd;
gameAG=gameAGStd;
});
};
button1TitleR.tap=button1TitleR.click;
scene[1].addChild(button1TitleR);
var button2Title=new PIXI.Sprite.fromImage("asset/loading.png");
button2Title.position=new PIXI.Point(500,140);
button2Title.anchor=AC_CENTER;
button2Title.width=250;
button2Title.height=250;
button2Title.interactive=true;
button2Title.hitArea=HIT_FULLSCREEN;
button2Title.click=function()
{
if (audio.buffered.end(0)==audio.duration)
{
gameInit();
audio.currentTime=0;
audio.play();
timeStart=new Date().getTime();
changeScene(3);
}
};
button2Title.tap=button2Title.click;
scene[2].addChild(button2Title);
//调节参数的对象
var text1Mouse=new PIXI.Text("",{font:"72px Consolas", fill:"#FFFFFF"});
text1Mouse.position=new PIXI.Point(80,500);
text1Mouse.anchor=AC_CENTER;
text1Mouse.buttonMode=true;
text1Mouse.interactive=true;
text1Mouse.click=function()
{
useMouse=!useMouse;
};
text1Mouse.tap=text1Mouse.click;
scene[1].addChild(text1Mouse);
var text1MouseTag=new PIXI.Text("MOUSE",{font:"18px Consolas", fill:"#FFFFFF"});
text1MouseTag.position=new PIXI.Point(80,460);
text1MouseTag.anchor=AC_CENTER;
scene[1].addChild(text1MouseTag);
var text1BS=new PIXI.Text("",{font:"72px Consolas", fill:"#FFFFFF"});
text1BS.position=new PIXI.Point(200,500);
text1BS.anchor=AC_CENTER;
scene[1].addChild(text1BS);
var text1BSTag=new PIXI.Text("SIZE",{font:"18px Consolas", fill:"#FFFFFF"});
text1BSTag.position=new PIXI.Point(200,460);
text1BSTag.anchor=AC_CENTER;
scene[1].addChild(text1BSTag);
var button1BSL=new PIXI.Text("-",{font:"36px Consolas", fill:"#FFFFFF"});
button1BSL.position=new PIXI.Point(200,555);
button1BSL.anchor=AC_CENTER;
button1BSL.buttonMode=true;
button1BSL.interactive=true;
button1BSL.click=function()
{
gameBS=bound(0,5,gameBS-1);
};
button1BSL.tap=button1BSL.click;
scene[1].addChild(button1BSL);
var button1BSR=new PIXI.Text("+",{font:"36px Consolas", fill:"#FFFFFF"});
button1BSR.position=new PIXI.Point(200,425);
button1BSR.anchor=AC_CENTER;
button1BSR.buttonMode=true;
button1BSR.interactive=true;
button1BSR.click=function()
{
gameBS=bound(0,5,gameBS+1);
};
button1BSR.tap=button1BSR.click;
scene[1].addChild(button1BSR);
var text1SP=new PIXI.Text("",{font:"72px Consolas", fill:"#FFFFFF"});
text1SP.position=new PIXI.Point(300,500);
text1SP.anchor=AC_CENTER;
scene[1].addChild(text1SP);
var text1SPTag=new PIXI.Text("SPEED",{font:"18px Consolas", fill:"#FFFFFF"});
text1SPTag.position=new PIXI.Point(300,460);
text1SPTag.anchor=AC_CENTER;
scene[1].addChild(text1SPTag);
var button1SPL=new PIXI.Text("-",{font:"36px Consolas", fill:"#FFFFFF"});
button1SPL.position=new PIXI.Point(300,555);
button1SPL.anchor=AC_CENTER;
button1SPL.buttonMode=true;
button1SPL.interactive=true;
button1SPL.click=function()
{
gameSP=bound(0,5,gameSP-1);
};
button1SPL.tap=button1SPL.click;
scene[1].addChild(button1SPL);
var button1SPR=new PIXI.Text("+",{font:"36px Consolas", fill:"#FFFFFF"});
button1SPR.position=new PIXI.Point(300,425);
button1SPR.anchor=AC_CENTER;
button1SPR.buttonMode=true;
button1SPR.interactive=true;
button1SPR.click=function()
{
gameSP=bound(0,5,gameSP+1);
};
button1SPR.tap=button1SPR.click;
scene[1].addChild(button1SPR);
var text1AG=new PIXI.Text("",{font:"72px Consolas", fill:"#FFFFFF"});
text1AG.position=new PIXI.Point(400,500);
text1AG.anchor=AC_CENTER;
scene[1].addChild(text1AG);
var text1AGTag=new PIXI.Text("ANGLE",{font:"18px Consolas", fill:"#FFFFFF"});
text1AGTag.position=new PIXI.Point(400,460);
text1AGTag.anchor=AC_CENTER;
scene[1].addChild(text1AGTag);
var button1AGL=new PIXI.Text("-",{font:"36px Consolas", fill:"#FFFFFF"});
button1AGL.position=new PIXI.Point(400,555);
button1AGL.anchor=AC_CENTER;
button1AGL.buttonMode=true;
button1AGL.interactive=true;
button1AGL.click=function()
{
gameAG=bound(0,5,gameAG-1);
};
button1AGL.tap=button1AGL.click;
scene[1].addChild(button1AGL);
var button1AGR=new PIXI.Text("+",{font:"36px Consolas", fill:"#FFFFFF"});
button1AGR.position=new PIXI.Point(400,425);
button1AGR.anchor=AC_CENTER;
button1AGR.buttonMode=true;
button1AGR.interactive=true;
button1AGR.click=function()
{
gameAG=bound(0,5,gameAG+1);
};
button1AGR.tap=button1AGR.click;
scene[1].addChild(button1AGR);
var text1Diff=new PIXI.Sprite.fromImage("asset/diff.png");
text1Diff.position=new PIXI.Point(700,450);
text1Diff.anchor=AC_CENTER;
var maskDiff=new PIXI.Graphics();
text1Diff.mask=maskDiff;
scene[1].addChild(text1Diff);
var text1Bpm=new PIXI.Text("",{font:"48px Consolas", fill:"#FFFFFF"});
text1Bpm.position=new PIXI.Point(540,530);
text1Bpm.anchor=AC_LEFT;
scene[1].addChild(text1Bpm);
var text1BpmTag=new PIXI.Text("BPM",{font:"24px Consolas", fill:"#FFFFFF"});
text1BpmTag.position=new PIXI.Point(500,510);
text1BpmTag.anchor=AC_CENTER;
scene[1].addChild(text1BpmTag);
//载入界面
var text2Title=new PIXI.Text("",{font:"48px Segoe UI", fill:"#FF66CC"});
text2Title.position=text1Title.position;
text2Title.anchor=AC_CENTER;
scene[2].addChild(text2Title);
var text2Load=new PIXI.Text("",{font:"40px Consolas", fill:"#FFFFFF"});
text2Load.position=new PIXI.Point(500,490);
text2Load.anchor=AC_CENTER;
scene[2].addChild(text2Load);
var text2Loading=new PIXI.Sprite.fromImage("asset/load.png");
text2Loading.position=new PIXI.Point(500,490);
text2Loading.anchor=AC_CENTER;
var maskLoad=new PIXI.Graphics();
text2Loading.mask=maskLoad;
scene[2].addChild(text2Loading);
//游戏界面
var text3Cb=new PIXI.Text("0x",{font:"64px font1", fill:"#FFFFFF"});
text3Cb.position=CENTER_POS;
text3Cb.anchor=AC_CENTER;
scene[3].addChild(text3Cb);
var text3Acc=new PIXI.Text("100.00%",{font:"60px font1", fill:"#FFFFFF"});
text3Acc.position=new PIXI.Point(150,30);
text3Acc.anchor=AC_LEFT;
scene[3].addChild(text3Acc);
var text3Score=new PIXI.Text("0",{font:"72px font1", fill:"#FFFFFF"});
text3Score.position=new PIXI.Point(850,30);
text3Score.anchor=AC_RIGHT;
//结算界面
scene[3].addChild(text3Score);
var text4Score=new PIXI.Text("0",{font:"100px font1", fill:"#FFFFFF"});
text4Score.position=new PIXI.Point(80,80);
text4Score.anchor=AC_LEFT;
scene[4].addChild(text4Score);
var text4Title=new PIXI.Text("",{font:"32px Consolas", fill:"#CCFF66"});
text4Title.position=new PIXI.Point(440,80);
text4Title.anchor=AC_LEFT;
scene[4].addChild(text4Title);
var text4Max=new PIXI.Text("0",{font:"72px font1", fill:"#66CCFF"});
text4Max.position=new PIXI.Point(250,200);
text4Max.anchor=AC_LEFT;
scene[4].addChild(text4Max);
var text4Good=new PIXI.Text("0",{font:"72px font1", fill:"#00D44D"});
text4Good.position=new PIXI.Point(250,300);
text4Good.anchor=AC_LEFT;
scene[4].addChild(text4Good);
var text4Bad=new PIXI.Text("0",{font:"72px font1", fill:"#A9C719"});
text4Bad.position=new PIXI.Point(250,400);
text4Bad.anchor=AC_LEFT;
scene[4].addChild(text4Bad);
var text4Miss=new PIXI.Text("0",{font:"72px font1", fill:"#D81428"});
text4Miss.position=new PIXI.Point(250,500);
text4Miss.anchor=AC_LEFT;
scene[4].addChild(text4Miss);
var text4Acc=new PIXI.Text("100.00%",{font:"72px font1", fill:"#FFFFFF"});
text4Acc.position=new PIXI.Point(700,200);
text4Acc.anchor=AC_LEFT;
scene[4].addChild(text4Acc);
var text4Hr=new PIXI.Text("100.00%",{font:"72px font1", fill:"#FFFFFF"});
text4Hr.position=new PIXI.Point(700,300);
text4Hr.anchor=AC_LEFT;
scene[4].addChild(text4Hr);
var text4Mc=new PIXI.Text("0x",{font:"72px font1", fill:"#FFFFFF"});
text4Mc.position=new PIXI.Point(700,400);
text4Mc.anchor=AC_LEFT;
scene[4].addChild(text4Mc);
var text4M=new PIXI.Text("MAX",{font:"60px font1", fill:"#66CCFF"});
text4M.position=new PIXI.Point(80,180);
text4M.anchor=AC_LEFT;
scene[4].addChild(text4M);
var text4G=new PIXI.Text("GOOD",{font:"60px font1", fill:"#00D44D"});
text4G.position=new PIXI.Point(80,280);
text4G.anchor=AC_LEFT;
scene[4].addChild(text4G);
var text4B=new PIXI.Text("BAD",{font:"60px font1", fill:"#A9C719"});
text4B.position=new PIXI.Point(80,380);
text4B.anchor=AC_LEFT;
scene[4].addChild(text4B);
var text4MS=new PIXI.Text("MISS",{font:"60px font1", fill:"#D81428"});
text4MS.position=new PIXI.Point(80,480);
text4MS.anchor=AC_LEFT;
scene[4].addChild(text4MS);
var text4A=new PIXI.Text("Accuracy",{font:"50px font1", fill:"#FFFFFF"});
text4A.position=new PIXI.Point(420,175);
text4A.anchor=AC_LEFT;
scene[4].addChild(text4A);
var text4H=new PIXI.Text("Rank",{font:"50px font1", fill:"#FFFFFF"});
text4H.position=new PIXI.Point(420,275);
text4H.anchor=AC_LEFT;
scene[4].addChild(text4H);
var text4MC=new PIXI.Text("Max Combo",{font:"50px font1", fill:"#FFFFFF"});
text4MC.position=new PIXI.Point(420,375);
text4MC.anchor=AC_LEFT;
scene[4].addChild(text4MC);
//初始化
changeScene(0);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonres=JSON.parse(xmlhttp.responseText);
var assetlist=new Array();
for (var i=0;i<jsonres.data.length;i++)
{
GAME_DATA[i]=new Array(jsonres.data[i].id,jsonres.data[i].name);
assetlist[i]="data/"+jsonres.data[i].id+".png";
}
var asset=new PIXI.AssetLoader(assetlist);
asset.load();
asset.onComplete=function()
{
for (var i=0;i<jsonres.data.length;i++)
{
GAME_DATA[i][2]=PIXI.Texture.fromImage("data/"+jsonres.data[i].id+".png");
}
loadJSON(GAME_DATA[gameBeatmapID][0],false,function(){
gameBS=gameBSStd;
gameSP=gameSPStd;
gameAG=gameAGStd;
button1TitleL.setTexture(GAME_DATA[cyclePrev(GAME_DATA.length,gameBeatmapID)][2]);
button1TitleL.width=150;
button1TitleL.height=150;
button1Title.setTexture(GAME_DATA[gameBeatmapID][2]);
button1Title.width=250;
button1Title.height=250;
button1TitleR.setTexture(GAME_DATA[cycleNext(GAME_DATA.length,gameBeatmapID)][2]);
button1TitleR.width=150;
button1TitleR.height=150;
changeScene(1);
});
};
}
}
xmlhttp.open("GET","data/gamedata.json",true);
xmlhttp.send();
kd.UP.down(function()
{
if (gameScene==1)
{
timeOffset++;
}
});
kd.DOWN.down(function()
{
if (gameScene==1)
{
timeOffset--;
}
});
kd.LEFT.down(function()
{
if (gameScene==1)
{
if (new Date().getTime()-timeLastkey>150)
{
button1TitleL.click();
timeLastkey=new Date().getTime();
}
}
else if (gameScene==3)
{
if (kd.SHIFT.isDown())
padPos-=0.025*Math.PI;
else
padPos-=0.05*Math.PI;
if (padPos<0)
padPos+=2*Math.PI;
}
});
kd.RIGHT.down(function()
{
if (gameScene==1)
{
if (new Date().getTime()-timeLastkey>150)
{
button1TitleR.click();
timeLastkey=new Date().getTime();
}
}
else if (gameScene==3)
{
if (kd.SHIFT.isDown())
padPos+=0.025*Math.PI;
else
padPos+=0.05*Math.PI;
if (padPos>=2*Math.PI)
padPos-=2*Math.PI;
}
});
kd.SPACE.down(function()
{
if (gameScene==1)
{
if (new Date().getTime()-timeLastkey>150)
{
text1Mouse.click();
timeLastkey=new Date().getTime();
}
}
});
kd.ENTER.down(function()
{
if (gameScene==1)
{
if (new Date().getTime()-timeLastkey>150)
{
button1Title.click();
timeLastkey=new Date().getTime();
}
}
else if (gameScene==2)
{
if (new Date().getTime()-timeLastkey>150)
{
button2Title.click();
timeLastkey=new Date().getTime();
}
}
else if (gameScene==4)
{
if (new Date().getTime()-timeLastkey>150)
{
button4Continue.click();
timeLastkey=new Date().getTime();
}
}
});
kd.ESC.down(function()
{
if (gameScene==3)
{
if (new Date().getTime()-timeStart-timePause>1000)
button3Pause.click();
}
else if (gameScene==5)
{
if (new Date().getTime()-timeStart-timePause>1000)
button5Resume.click();
}
});
function animate()
{
stats.begin();
if (gameScene==1)
{
text1Offset.setText("Offset="+timeOffset);
if (useMouse)
text1Mouse.setText("ON");
else
text1Mouse.setText("OFF");
text1BS.setText(gameBS);
text1SP.setText(gameSP);
text1AG.setText(gameAG);
maskDiff.clear();
maskDiff.beginFill(0xFFFFFF);
maskDiff.drawRect(500,425,400*gameDiff/9,50);
text1Bpm.setText(gameBpm);
button1TitleL.setTexture(GAME_DATA[cyclePrev(GAME_DATA.length,gameBeatmapID)][2]);
button1TitleL.width=150;
button1TitleL.height=150;
button1Title.setTexture(GAME_DATA[gameBeatmapID][2]);
button1Title.width=250;
button1Title.height=250;
button1TitleR.setTexture(GAME_DATA[cycleNext(GAME_DATA.length,gameBeatmapID)][2]);
button1TitleR.width=150;
button1TitleR.height=150;
text1Title.setText(GAME_DATA[gameBeatmapID][1]);
}
else if (gameScene==2)
{
if (audio.buffered.length>0)
{
if (audio.buffered.end(0)==audio.duration)
{
text2Load.setText("Click To Start!");
audio.currentTime=0;
maskLoad.clear();
maskLoad.beginFill(0xFFFFFF);
maskLoad.drawRect(100,400,800,180);
}
else
{
text2Load.setText("Now Loading: "+Math.floor(100*audio.buffered.end(0)/audio.duration)+"%");
audio.currentTime=audio.buffered.end(0);
maskLoad.clear();
maskLoad.beginFill(0xFFFFFF);
maskLoad.drawRect(100,400,800*audio.buffered.end(0)/audio.duration,180);
}
}
else
{
text2Load.setText("Now Loading...");
maskLoad.clear();
maskLoad.beginFill(0xFFFFFF);
maskLoad.drawRect(100,400,0,180);
}
}
else if (gameScene==3)
{
timePlay=new Date().getTime()-timeStart;
if (useMouse)
{
if (stage.getMousePosition().x!=0)
mouseX=stage.getMousePosition().x;
else if(stage.interactionManager.touchs[0]!=null)
mouseX=stage.interactionManager.touchs[0].global.x;
if (stage.getMousePosition().y!=0)
mouseY=stage.getMousePosition().y;
else if(stage.interactionManager.touchs[0]!=null)
mouseY=stage.interactionManager.touchs[0].global.y;
if (Math.abs(mouseX-WINDOW_X/2)>=30 || Math.abs(mouseY-WINDOW_Y/2)>=30)
{
if (mouseX==WINDOW_X/2)
padPos=mouseY>WINDOW_Y/2 ? Math.PI/2 : Math.PI*3/2;
else if (mouseY==WINDOW_Y/2)
padPos=mouseX>WINDOW_X/2 ? 0 : Math.PI;
else if (mouseX>WINDOW_X/2)
padPos=Math.atan((mouseY-WINDOW_Y/2)/(mouseX-WINDOW_X/2));
else
padPos=Math.PI+Math.atan((mouseY-WINDOW_Y/2)/(mouseX-WINDOW_X/2));
}
}
mask1.clear();
mask1.beginFill(0xFFFFFF);
mask1.drawRect(0,WINDOW_Y-timePlay/audio.duration*WINDOW_Y/1000,100,timePlay/audio.duration*WINDOW_Y/1000);
mask2.clear();
mask2.beginFill(0xFFFFFF);
mask2.drawRect(WINDOW_X-100,WINDOW_Y-WINDOW_Y*gameHP,100,WINDOW_Y*gameHP);
paddle.rotation=padPos;
text3Acc.setText(Math.floor(gameAcc/100)+"."+(Math.floor(gameAcc/10))%10+gameAcc%10+"%");
text3Cb.setText(gameCombo+"x");
text3Score.setText(gameScore);
if (gameHP>=0.6)
{
paddle.filters[0].matrix=[0.7,0,0,0,0,1,0,0,0,0,0.7,0,0,0,0,1];
center.filters[0].matrix=[0,0,0,0,0,0.3,0,0,0,0,0,0,0,0,0,0.3];
}
else if (gameHP>=0.3)
{
paddle.filters[0].matrix=[1,0,0,0,0,1,0,0,0,0,0.7,0,0,0,0,1];
center.filters[0].matrix=[0.3,0,0,0,0,0.3,0,0,0,0,0,0,0,0,0,0.3];
}
else
{
paddle.filters[0].matrix=[1,0,0,0,0,0.7,0,0,0,0,0.7,0,0,0,0,1];
center.filters[0].matrix=[0.3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.3];
}
gameHP-=Math.max(gameHP*0.0003,0.0001);
gameHP=bound(0,1,gameHP);
for (var i=gameBeatsStart;i<gameBeatsEnd;i++)
gameBeats[i].update(function(){});
while (gameBeatsEnd<gameBmTotal && gameBeats[gameBeatsEnd].time-timePlay<SP_TIME_CONST[gameSP])
gameBeatsEnd++;
if (audio.ended)
{
setTimeout(function()
{
text4Score.setText(gameScore);
text4Title.setText(text1Title.text);
text4Max.setText(gameHitMax);
text4Good.setText(gameHitGood);
text4Bad.setText(gameHitBad);
text4Miss.setText(gameMiss);
text4Acc.setText(Math.floor(gameAcc/100)+"."+(Math.floor(gameAcc/10))%10+gameAcc%10+"%");
gameRank=Math.pow(1+gameAcc/10000,2)+gameMaxCombo/gameBmTotal-1;
if (gameAcc>9000)
gameRank+=Math.pow((gameAcc-9000)/500,2);
gameRank=Math.floor(10*gameRank);
text4Hr.setText(Math.floor(gameRank/10)+"."+gameRank%10);
text4Mc.setText(gameMaxCombo+"x");
changeScene(4);
},1500);
}
}
kd.tick();
requestAnimFrame(animate);
renderer.render(stage);
stats.end();
}
requestAnimFrame(animate);
|
'use strict';
var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
var arraySlice = require('../internals/array-slice');
var arrayToSpliced = require('../internals/array-to-spliced');
var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
var TYPED_ARRAY_CONSTRUCTOR = ArrayBufferViewCore.TYPED_ARRAY_CONSTRUCTOR;
// `%TypedArray%.prototype.toSpliced` method
// https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toSpliced
// eslint-disable-next-line no-unused-vars -- required for .length
exportTypedArrayMethod('toSpliced', function toSpliced(start, deleteCount /* , ...items */) {
return arrayToSpliced(aTypedArray(this), this[TYPED_ARRAY_CONSTRUCTOR], arraySlice(arguments));
}, true);
|
var searchData=
[
['value',['value',['../struct_q_joystick_axis_event.html#a3cc39770f2ffc48ce84bbc8f0626735a',1,'QJoystickAxisEvent']]]
];
|
version https://git-lfs.github.com/spec/v1
oid sha256:8b21d81f79bca28721b3410dd4ecf631e99e5668a2ba2ef467b762759b4133fd
size 646
|
export default class Body {
constructor(width, height) {
this.x = 0;
this.y = 0;
this.w = width;
this.h = height;
this.vx = 0;
this.vy = 0;
}
setPosition(x, y) {
this.x = x;
this.y = y;
}
setVelocity(vx, vy) {
this.vx = vx;
this.vy = vy;
}
update() {
this.x += this.vx;
this.y += this.vy;
}
}
|
/*
@license
dhtmlxGantt v.4.1.0 Stardard
This software is covered by GPL license. You also can obtain Commercial or Enterprise license to use it in non-GPL project - please contact sales@dhtmlx.com. Usage without proper license is prohibited.
(c) Dinamenta, UAB.
*/
gantt.locale={date:{month_full:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","November","December"],month_short:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"],day_full:["Duminica","Luni","Marti","Miercuri","Joi","Vineri","Sambata"],day_short:["Du","Lu","Ma","Mi","Jo","Vi","Sa"]},labels:{dhx_cal_today_button:"Astazi",day_tab:"Zi",week_tab:"Saptamana",month_tab:"Luna",new_event:"Eveniment nou",icon_save:"Salveaza",icon_cancel:"Anuleaza",
icon_details:"Detalii",icon_edit:"Editeaza",icon_delete:"Sterge",confirm_closing:"Schimbarile nu vor fi salvate, esti sigur?",confirm_deleting:"Evenimentul va fi sters permanent, esti sigur?",section_description:"Descriere",section_time:"Interval",section_type:"Type",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",
minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years",message_ok:"OK",message_cancel:"Anuleaza"}};
//# sourceMappingURL=../sources/locale/locale_ro.js.map
|
var _dasherize = require('underscore.string/dasherize');
var _curry = require('chickencurry');
module.exports = _curry(_dasherize);
|
YUI.add('axis-time', function (Y, NAME) {
/**
* Provides functionality for drawing a time axis for use with a chart.
*
* @module charts
* @submodule axis-time
*/
/**
* TimeAxis draws a time-based axis for a chart.
*
* @class TimeAxis
* @constructor
* @extends Axis
* @uses TimeImpl
* @param {Object} config (optional) Configuration parameters.
* @submodule axis-time
*/
Y.TimeAxis = Y.Base.create("timeAxis", Y.Axis, [Y.TimeImpl], {
/**
* Calculates and returns a value based on the number of labels and the index of
* the current label.
*
* @method _getLabelByIndex
* @param {Number} i Index of the label.
* @param {Number} l Total number of labels.
* @return String
* @private
*/
_getLabelByIndex: function(i, l)
{
var min = this.get("minimum"),
max = this.get("maximum"),
increm,
label;
l -= 1;
increm = ((max - min)/l) * i;
label = min + increm;
return label;
},
/**
* Calculates the position of ticks and labels based on an array of specified label values. Returns
* an object containing an array of values to be used for labels and an array of objects containing
* x and y coordinates for each label.
*
* @method _getDataFromLabelValues
* @param {Object} startPoint An object containing the x and y coordinates for the start of the axis.
* @param {Array} labelValues An array containing values to be used for determining the number and
* position of labels and ticks on the axis.
* @param {Number} edgeOffset The distance, in pixels, on either edge of the axis.
* @param {Number} layoutLength The length, in pixels, of the axis. If the axis is vertical, the length
* is equal to the height. If the axis is horizontal, the length is equal to the width.
* @return Object
* @private
*/
_getDataFromLabelValues: function(startPoint, labelValues, edgeOffset, layoutLength, direction)
{
var points = [],
labelValue,
i,
len = labelValues.length,
staticCoord,
dynamicCoord,
constantVal,
newPoint,
max = this.get("maximum"),
min = this.get("minimum"),
values = [],
scaleFactor = (layoutLength - (edgeOffset * 2)) / (max - min);
if(direction === "vertical")
{
staticCoord = "x";
dynamicCoord = "y";
}
else
{
staticCoord = "y";
dynamicCoord = "x";
}
constantVal = startPoint[staticCoord];
for(i = 0; i < len; i = i + 1)
{
labelValue = this._getNumber(labelValues[i]);
if(Y.Lang.isNumber(labelValue) && labelValue >= min && labelValue <= max)
{
newPoint = {};
newPoint[staticCoord] = constantVal;
newPoint[dynamicCoord] = edgeOffset + ((labelValue - min) * scaleFactor);
points.push(newPoint);
values.push(labelValue);
}
}
return {
points: points,
values: values
};
}
});
}, '3.10.3', {"requires": ["axis", "axis-time-base"]});
|
BASE.require(["Object"], function () {
BASE.namespace("LG.core.dataModel.core");
var _globalObject = this;
LG.core.dataModel.core.LGEmployeeRoleTitle = (function (Super) {
var LGEmployeeRoleTitle = function () {
var self = this;
if (self === _globalObject) {
throw new Error("LGEmployeeRoleTitle constructor invoked with global context. Say new.");
}
Super.call(self);
self["LGEmployeeRoleId"] = null;
self["LGEmployeeRole"] = null;
self["title"] = null;
self["startDate"] = null;
self["endDate"] = null;
self["id"] = null;
return self;
};
BASE.extend(LGEmployeeRoleTitle, Super);
return LGEmployeeRoleTitle;
}(Object));
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M5.5 22v-7.5H4V9c0-1.1.9-2 2-2h3c1.1 0 2 .9 2 2v5.5H9.5V22h-4zM18 22v-6h3l-2.54-7.63C18.18 7.55 17.42 7 16.56 7h-.12c-.86 0-1.63.55-1.9 1.37L12 16h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z"
}), 'Wc');
exports.default = _default;
|
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, IAPFactory) {
IAPFactory.doTest("Test from AppCtrl");
IAPFactory.setVar("monkey1234");
$scope.IAPFactory = IAPFactory;
$scope.IAPFactory.IAP.render = function(){
alert("IAP.render()! products:" + JSON.stringify($scope.IAPFactory.IAP.products) );
};
var onDeviceReady = function(){
alert("onDeviceReady!");
var productList = ["M1","M2","MF1.CONSUMABLE"];
$scope.IAPFactory.initialize(productList);
};
document.addEventListener('deviceready', onDeviceReady, false);
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('ProductCtrl', function($scope, $stateParams) {
})
.controller('ProductsCtrl', function($scope, IAPFactory){
// alert("ProductsCtrl IAPFactory.testVar:"+IAPFactory.getVar());
$scope.products = [
{"id":"M2", "title":"Buy Monkey Two"},
{"id":"MF1.CONSUMABLE", "title":"Buy Monkey Food One"}
];
$scope.buy = function (productId) {
console.log("buy product:"+productId);
alert("buy product: "+productId);
IAPFactory.buy(productId);
// IAPFactory.doTest("Test from ProductsCtrl");
};
});
|
'use strict';
var walletBalanceCtrl = function($scope, $sce, $rootScope) {
$scope.ajaxReq = ajaxReq;
$scope.tokensLoaded = false;
$scope.showAllTokens = false;
$scope.localToken = {
contractAdd: "",
symbol: "",
decimals: "",
type: "custom",
};
$scope.slide = 1;
$scope.customTokenField = false;
$scope.saveTokenToLocal = function() {
globalFuncs.saveTokenToLocal($scope.localToken, function(data) {
if (!data.error) {
$scope.addressDrtv.ensAddressField = "";
$scope.localToken = {
contractAdd: "",
symbol: "",
decimals: "",
type: "custom"
};
$scope.wallet.setTokens();
$scope.validateLocalToken = $sce.trustAsHtml('');
$scope.customTokenField = false;
} else {
$scope.notifier.danger(data.msg);
}
});
}
$scope.setAndVerifyBalance = function(token) {
if ( token.balance == 'Click to Load' ) {
token.balance='loading';
token.setBalance(function() {
var autoTokens = globalFuncs.localStorage.getItem('autoLoadTokens')
$scope.autoLoadTokens = autoTokens ? JSON.parse(autoTokens) : [];
if ( parseInt(token.balance) > 0 ) {
$scope.autoLoadTokens.push( token.contractAddress );
globalFuncs.localStorage.setItem( 'autoLoadTokens', JSON.stringify($scope.autoLoadTokens) );
}
});
}
}
/*
$scope.$watch('wallet', function() {
if ($scope.wallet) $scope.reverseLookup();
});
$scope.reverseLookup = function() {
var _ens = new ens();
_ens.getName($scope.wallet.getAddressString().substring(2) + '.addr.reverse', function(data) {
if (data.error) uiFuncs.notifier.danger(data.msg);
else if (data.data == '0x') {
$scope.showens = false;
} else {
$scope.ensAddress = data.data;
$scope.showens = true;
}
});
}
*/
$scope.removeTokenFromLocal = function(tokensymbol) {
globalFuncs.removeTokenFromLocal(tokensymbol, $scope.wallet.tokenObjs);
$rootScope.rootScopeShowRawTx = false;
}
$scope.showDisplayOnTrezor = function() {
return ($scope.wallet != null && $scope.wallet.hwType === 'trezor');
}
$scope.displayOnTrezor = function() {
TrezorConnect.ethereumGetAddress({
path: $scope.wallet.path,
showOnTrezor: true
});
}
$scope.showDisplayOnLedger = function() {
return ($scope.wallet != null && $scope.wallet.hwType === 'ledger');
}
$scope.displayOnLedger = function() {
var app = new ledgerEth($scope.wallet.getHWTransport());
app.getAddress($scope.wallet.path, function(){}, true, false);
}
};
module.exports = walletBalanceCtrl;
|
"use strict";
var redis = require('redis');
var url = require("url");
exports.createRedisClient = createRedisClient;
exports.redis = redis;
function createRedisClient(redisUrl) {
if(!redisUrl) {
var client = withErrorHandling(redis.createClient());
return client;
}
var parsedUrl = url.parse(redisUrl);
var client = withErrorHandling(redis.createClient(parsedUrl.port, parsedUrl.hostname));
client.on('error', function(err) {
console.log(err);
});
if(parsedUrl.auth && parsedUrl.auth.indexOf(":") != -1){
client.auth(parsedUrl.auth.split(":")[1]);
}
return client;
}
function withErrorHandling(client) {
client.on('error', function() {
console.log(arguments);
});
return client;
}
|
/*
alameda 1.2.1 Copyright jQuery Foundation and other contributors.
Released under MIT license, https://github.com/requirejs/alameda/blob/master/LICENSE
*/
var requirejs,require,define;
(function(Y,L,D){function na(g,e){return e||""}function p(g,e){return g&&E.call(g,e)&&g[e]}function h(){return Object.create(null)}function M(g,e){for(var p in g)if(E.call(g,p)&&e(g[p],p))break}function Z(g,e,p,r){return e&&M(e,function(e,h){(p||!E.call(g,h))&&(!r||"object"!=typeof e||!e||Array.isArray(e)||"function"==typeof e||e instanceof RegExp?g[h]=e:(!g[h]&&(g[h]={}),Z(g[h],e,p,r)))}),g}function oa(g){if(!g)return g;var e=Y;return g.split(".").forEach(function(g){e=e[g]}),e}function aa(g){function e(a,
b,c){var d,m,f,n,F;var l=b=b&&b.split("/");var g=k.map,e=g&&g["*"];if(a){a=a.split("/");var h=a.length-1;k.nodeIdCompat&&N.test(a[h])&&(a[h]=a[h].replace(N,""));"."===a[0].charAt(0)&&b&&(l=b.slice(0,b.length-1),a=l.concat(a));h=a;var r=h.length;for(l=0;l<r;l++)(f=h[l],"."===f)?(h.splice(l,1),--l):".."!==f||0===l||1===l&&".."===h[2]||".."===h[l-1]||0<l&&(h.splice(l-1,2),l-=2);a=a.join("/")}if(c&&g&&(b||e)){c=a.split("/");f=c.length;a:for(;0<f;--f){if(l=c.slice(0,f).join("/"),b)for(h=b.length;0<h;--h)if(m=
p(g,b.slice(0,h).join("/")),m&&(m=p(m,l),m)){var q=m;var t=f;break a}!n&&e&&p(e,l)&&(n=p(e,l),F=f)}!q&&n&&(q=n,t=F);q&&(c.splice(0,t,q),a=c.join("/"))}return d=p(k.pkgs,a),d?d:a}function r(a){return function(){var b;return a.init&&(b=a.init.apply(Y,arguments)),b||a.exports&&oa(a.exports)}}function u(a){var b,c;for(b=0;b<x.length;b+=1){if("string"==typeof x[b][0])a&&0===a.indexOf(x[b][0])&&(x[b]=x[b].slice(1),x[b].unshift(a),a=D);else if(a)x[b].unshift(a),a=D;else break;var d=x.shift();var m=d[0];
--b;m in q||m in G||(m in y?I.apply(D,d):G[m]=d)}a&&(c=p(k.shim,a)||{},I(a,c.deps||[],c.exportsFn))}function B(a,b){var c=function(d,m,f,n){var F,l;if(b&&u(),"string"==typeof d){if(z[d])return z[d](a);if(F=v(d,a,!0).id,!(F in q))throw Error("Not loaded: "+F);return q[F]}return d&&!Array.isArray(d)&&(l=d,d=D,Array.isArray(m)&&(d=m,m=f,f=n),b)?c.config(l)(d,m,f):(m=m||function(){return T.call(arguments,0)},qa.then(function(){return u(),I(D,d||[],m,f,a)}))};return c.isBrowser="undefined"!=typeof document&&
"undefined"!=typeof navigator,c.nameToUrl=function(a,b,f){var d,m,l;var g=p(k.pkgs,a);if(g&&(a=g),d=p(U,a),d)return c.nameToUrl(d,b,f);if(ra.test(a))var e=a+(b||"");else{d=k.paths;g=a.split("/");for(m=g.length;0<m;--m)if(e=g.slice(0,m).join("/"),l=p(d,e),l){Array.isArray(l)&&(l=l[0]);g.splice(0,m,l);break}e=g.join("/");e+=b||(/^data:|^blob:|\?/.test(e)||f?"":".js");e=("/"===e.charAt(0)||e.match(/^[\w\+\.\-]+:/)?"":k.baseUrl)+e}return k.urlArgs&&!/^blob:/.test(e)?e+k.urlArgs(a,e):e},c.toUrl=function(b){var d,
f=b.lastIndexOf("."),n=b.split("/")[0];return-1!==f&&(!("."===n||".."===n)||1<f)&&(d=b.substring(f,b.length),b=b.substring(0,f)),c.nameToUrl(e(b,a),d,!0)},c.defined=function(b){return v(b,a,!0).id in q},c.specified=function(b){return b=v(b,a,!0).id,b in q||b in y},c}function C(a,b,c){a&&(q[a]=c,requirejs.onResourceLoad&&requirejs.onResourceLoad(O,b.map,b.deps));b.finished=!0;b.resolve(c)}function H(a,b){a.finished=!0;a.rejected=!0;a.reject(b)}function S(a){return function(b){return e(b,a,!0)}}function ba(a){a.factoryCalled=
!0;var b=a.map.id;try{var c=O.execCb(b,a.factory,a.values,q[b])}catch(d){return H(a,d)}b?c===D&&(a.cjsModule?c=a.cjsModule.exports:a.usingExports&&(c=q[b])):A.splice(A.indexOf(a),1);C(b,a,c)}function sa(a,b){this.rejected||this.depDefined[b]||(this.depDefined[b]=!0,this.depCount+=1,this.values[b]=a,!this.depending&&this.depCount===this.depMax&&ba(this))}function ca(a,b){var c={};return c.promise=new L(function(b,m){c.resolve=b;c.reject=function(b){a||A.splice(A.indexOf(c),1);m(b)}}),c.map=a?b||v(a):
{},c.depCount=0,c.depMax=0,c.values=[],c.depDefined=[],c.depFinished=sa,c.map.pr&&(c.deps=[v(c.map.pr)]),c}function w(a,b){var c;return a?(c=a in y&&y[a],!c&&(c=y[a]=ca(a,b))):(c=ca(),A.push(c)),c}function da(a,b){return function(c){a.rejected||(!c.dynaId&&(c.dynaId="id"+(ta+=1),c.requireModules=[b]),H(a,c))}}function ea(a,b,c,d){c.depMax+=1;V(a,b).then(function(a){c.depFinished(a,d)},da(c,a.id))["catch"](da(c,c.map.id))}function ua(a){function b(b){c||C(a,w(a),b)}var c;return b.error=function(b){H(w(a),
b)},b.fromText=function(b,m){var f=w(a),d=v(v(a).n),e=d.id;c=!0;f.factory=function(a,b){return b};m&&(b=m);E.call(k.config,a)&&(k.config[e]=k.config[a]);try{t.exec(b)}catch(pa){var g=Error("fromText eval for "+e+" failed: "+pa);g.requireType="fromtexteval";H(f,g)}u(e);f.deps=[d];ea(d,null,f,f.deps.length)},b}function fa(a,b,c){a.load(b.n,B(c),ua(b.id),k)}function ha(a){var b,c=a?a.indexOf("!"):-1;return-1<c&&(b=a.substring(0,c),a=a.substring(c+1,a.length)),[b,a]}function W(a,b,c){var d=a.map.id;b[d]=
!0;!a.finished&&a.deps&&a.deps.forEach(function(d){var f=d.id;d=!E.call(z,f)&&w(f,d);!d||d.finished||c[f]||(E.call(b,f)?a.deps.forEach(function(b,c){b.id===f&&a.depFinished(q[f],c)}):W(d,b,c))});c[d]=!0}function ia(a){var b,c=[],d=1E3*k.waitSeconds;d=d&&ja+d<(new Date).getTime();if(0===J&&(a?!a.finished&&W(a,{},{}):A.length&&A.forEach(function(a){W(a,{},{})})),d){for(b in y)a=y[b],a.finished||c.push(a.map.id);var e=Error("Timeout for modules: "+c);e.requireModules=c;e.requireType="timeout";c.forEach(function(a){H(w(a),
e)})}else(J||A.length)&&(X||(X=!0,setTimeout(function(){X=!1;ia()},70)))}function va(a){return setTimeout(function(){a.dynaId&&ka[a.dynaId]||(ka[a.dynaId]=!0,t.onError(a))}),a}var t,I,v,V,z,X,K,O,q=h(),G=h(),k={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},P=h(),A=[],y=h(),la=h(),ma=h(),J=0,ja=(new Date).getTime(),ta=0,ka=h(),Q=h(),U=h(),qa=L.resolve();return K="function"==typeof importScripts?function(a){var b=a.url;Q[b]||(Q[b]=!0,w(a.id),importScripts(b),u(a.id))}:function(a){var b,
c=a.id;a=a.url;Q[a]||(Q[a]=!0,b=document.createElement("script"),b.setAttribute("data-requiremodule",c),b.type=k.scriptType||"text/javascript",b.charset="utf-8",b.async=!0,J+=1,b.addEventListener("load",function(){--J;u(c)},!1),b.addEventListener("error",function(){--J;var a;(a=p(k.paths,c))&&Array.isArray(a)&&1<a.length?(b.parentNode.removeChild(b),a.shift(),a=w(c),a.map=v(c),a.map.url=t.nameToUrl(c),K(a.map)):(a=Error("Load failed: "+c+": "+b.src),a.requireModules=[c],a.requireType="scripterror",
H(w(c),a))},!1),b.src=a,10===document.documentMode?wa.then(function(){document.head.appendChild(b)}):document.head.appendChild(b))},V=function(a,b){var c=a.id;var d=k.shim[c];if(c in G)d=G[c],delete G[c],I.apply(D,d);else if(!(c in y))if(a.pr)if(d=p(U,c))a.url=t.nameToUrl(d),K(a);else return V(v(a.pr)).then(function(d){var f=a.prn?a:v(c,b,!0),e=f.id,g=p(k.shim,e);return e in ma||(ma[e]=!0,g&&g.deps?t(g.deps,function(){fa(d,f,b)}):fa(d,f,b)),w(e).promise});else d&&d.deps?t(d.deps,function(){K(a)}):
K(a);return w(c).promise},v=function(a,b,c){if("string"!=typeof a)return a;var d,g,f,n,h,l,k=a+" & "+(b||"")+" & "+!!c;return(f=ha(a),n=f[0],a=f[1],!n&&k in P)?P[k]:(n&&(n=e(n,b,c),d=n in q&&q[n]),n?d&&d.normalize?(a=d.normalize(a,S(b)),l=!0):a=-1===a.indexOf("!")?e(a,b,c):a:(a=e(a,b,c),f=ha(a),n=f[0],a=f[1],g=t.nameToUrl(a)),h={id:n?n+"!"+a:a,n:a,pr:n,url:g,prn:n&&l},n||(P[k]=h),h)},z={require:function(a){return B(a)},exports:function(a){var b=q[a];return"undefined"==typeof b?q[a]={}:b},module:function(a){return{id:a,
uri:"",exports:z.exports(a),config:function(){return p(k.config,a)||{}}}}},I=function(a,b,c,d,e){if(a){if(a in la)return;la[a]=!0}var f=w(a);return b&&!Array.isArray(b)&&(c=b,b=[]),b=b?T.call(b,0):null,d||(E.call(k,"defaultErrback")?k.defaultErrback&&(d=k.defaultErrback):d=va),d&&f.promise["catch"](d),e=e||a,"function"==typeof c?(!b.length&&c.length&&(c.toString().replace(xa,na).replace(ya,function(a,c){b.push(c)}),b=(1===c.length?["require"]:["require","exports","module"]).concat(b)),f.factory=c,
f.deps=b,f.depending=!0,b.forEach(function(c,d){var g;b[d]=g=v(c,e,!0);c=g.id;"require"===c?f.values[d]=z.require(a):"exports"===c?(f.values[d]=z.exports(a),f.usingExports=!0):"module"===c?f.values[d]=f.cjsModule=z.module(a):void 0===c?f.values[d]=void 0:ea(g,e,f,d)}),f.depending=!1,f.depCount===f.depMax&&ba(f)):a&&C(a,f,c),ja=(new Date).getTime(),a||ia(f),f.promise},t=B(null,!0),t.config=function(a){if(a.context&&a.context!==g){var b=p(R,a.context);return b?b.req.config(a):aa(a.context).config(a)}if(P=
h(),a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/"),"string"==typeof a.urlArgs){var c=a.urlArgs;a.urlArgs=function(a,b){return(-1===b.indexOf("?")?"?":"&")+c}}var d=k.shim,e={paths:!0,bundles:!0,config:!0,map:!0};return M(a,function(a,b){e[b]?(!k[b]&&(k[b]={}),Z(k[b],a,!0,!0)):k[b]=a}),a.bundles&&M(a.bundles,function(a,b){a.forEach(function(a){a!==b&&(U[a]=b)})}),a.shim&&(M(a.shim,function(a,b){Array.isArray(a)&&(a={deps:a});(a.exports||a.init)&&!a.exportsFn&&(a.exportsFn=
r(a));d[b]=a}),k.shim=d),a.packages&&a.packages.forEach(function(a){a="string"==typeof a?{name:a}:a;var b=a.name;a.location&&(k.paths[b]=a.location);k.pkgs[b]=a.name+"/"+(a.main||"main").replace(za,"").replace(N,"")}),(a.deps||a.callback)&&t(a.deps,a.callback),t},t.onError=function(a){throw a;},O={id:g,defined:q,waiting:G,config:k,deferreds:y,req:t,execCb:function(a,b,c,d){return b.apply(d,c)}},R[g]=O,t}if(!L)throw Error("No Promise implementation available");var u,r,B,S,C=requirejs||require,E=Object.prototype.hasOwnProperty,
R={},x=[],za=/^\.\//,ra=/^\/|:|\?|\.js$/,xa=/\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,ya=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,N=/\.js$/,T=Array.prototype.slice;if("function"!=typeof requirejs){var wa=L.resolve(void 0);requirejs=u=aa("_");"function"!=typeof require&&(require=u);u.exec=function(g){return eval(g)};u.contexts=R;define=function(){x.push(T.call(arguments,0))};define.amd={jQuery:!0};C&&u.config(C);u.isBrowser&&!R._.config.skipDataMain&&(r=document.querySelectorAll("script[data-main]")[0],
r=r&&r.getAttribute("data-main"),r&&(r=r.replace(N,""),(!C||!C.baseUrl)&&-1===r.indexOf("!")&&(B=r.split("/"),r=B.pop(),S=B.length?B.join("/")+"/":"./",u.config({baseUrl:S})),u([r])))}})(this,"undefined"==typeof Promise?void 0:Promise);
|
var Config = require("../config");
var Photos = require("../models/photos");
var Users = require("../models/users");
var Aws = require("aws-sdk");
module.exports = {
view: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
var profile = request.auth.credentials;
Photos.findGallery(profile.id, function(err, data){
if (data === null) {
reply.view("profile", {profile: profile});
}
else {
var photos = data.photos;
reply.view("profile", {
profile: profile,
photos: photos
});
}
});
}
else {
reply.redirect("/");
}
}
},
publicView: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
var id = request.params.id;
var profile;
Users.findUser(id, function (err, data) {
if (data === null) {
reply.redirect("/");
}
else {
profile = data;
Photos.findGallery(profile.id, function(err, data){
if (data === null) {
reply.view("publicProfile", { profile: profile });
}
else {
var photos = data.photos;
reply.view("publicProfile", {
profile: profile,
photos: photos
});
}
});
}
});
}
else {
reply.redirect("/");
}
}
},
publicPost: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
var viewing = Object.keys(request.payload)[0];
reply.redirect("/profile/" + viewing);
}
},
edit: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
var profile = request.auth.credentials;
reply.view("profileEdit", {profile: profile});
}
else {
reply.redirect("/");
}
}
},
post: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
var profile = request.auth.credentials;
var update = request.payload;
profile.firstName = update.firstName;
profile.lastName = update.lastName;
profile.website = update.website;
request.auth.session.set(profile);
Users.updateUser(profile.id, update, function (err, data) {
reply.redirect("/profile");
});
}
},
deletePhoto: {
auth: {
mode: "optional"
},
handler: function (request, reply) {
var id = request.auth.credentials.id;
//Big mess to get url from input
var mess = Object.keys(request.payload)[0];
var filename = mess.split(" ")[0];
var ext = mess.split(" ")[1];
var path = id + "/" + filename + "." + ext;
var url = "https://camunity.s3.amazonaws.com/" + path;
Aws.config.update({
accessKeyId: Config.s3.key,
secretAccessKey: Config.s3.secret
});
var s3 = new Aws.S3();
var params = {
Bucket: Config.s3.bucket,
Key: path,
};
s3.deleteObject(params, function(err, data) {
if (err) {
console.log("Error deleting from S3", err, err.stack);
}
else {
console.log("Successfully deleted from S3");
}
});
Photos.deletePhoto(id, url, function (err, data) {
reply.redirect("/profile");
});
}
},
};
|
define(['../time/now'], function (now) {
/**
*/
/**
* Description
* @method throttle
* @param {} fn
* @param {} delay
* @return throttled
*/
function throttle(fn, delay){
var context, timeout, result, args,
cur, diff, prev = 0;
/**
* Description
* @method delayed
* @return
*/
function delayed(){
prev = now();
timeout = null;
result = fn.apply(context, args);
}
/**
* Description
* @method throttled
* @return result
*/
function throttled(){
context = this;
args = arguments;
cur = now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (! timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
return throttled;
}
return throttle;
});
|
/**
* @ignore
* KISSY.Popup
* @author qiaohua@taobao.com, yiminghe@gmail.com
*/
KISSY.add('overlay/popup', function (S, Overlay, undefined) {
/**
* @class KISSY.Overlay.Popup
* KISSY Popup Component.
* xclass: 'popup'.
* @extends KISSY.Overlay
*/
return Overlay.extend({
initializer: function () {
var self = this,
// 获取相关联的 Dom 节点
trigger = self.get("trigger");
if (trigger) {
if (self.get("triggerType") === 'mouse') {
self._bindTriggerMouse();
self.on('afterRenderUI', function () {
self._bindContainerMouse();
});
} else {
self._bindTriggerClick();
}
}
},
_bindTriggerMouse: function () {
var self = this,
trigger = self.get("trigger"),
timer;
self.__mouseEnterPopup = function (ev) {
self._clearHiddenTimer();
timer = S.later(function () {
self._showing(ev);
timer = undefined;
}, self.get('mouseDelay') * 1000);
};
trigger.on('mouseenter', self.__mouseEnterPopup);
self._mouseLeavePopup = function () {
if (timer) {
timer.cancel();
timer = undefined;
}
self._setHiddenTimer();
};
trigger.on('mouseleave', self._mouseLeavePopup);
},
_bindContainerMouse: function () {
var self = this;
self.$el
.on('mouseleave', self._setHiddenTimer, self)
.on('mouseenter', self._clearHiddenTimer, self);
},
_setHiddenTimer: function () {
var self = this;
self._hiddenTimer = S.later(function () {
self._hiding();
}, self.get('mouseDelay') * 1000);
},
_clearHiddenTimer: function () {
var self = this;
if (self._hiddenTimer) {
self._hiddenTimer.cancel();
self._hiddenTimer = undefined;
}
},
_bindTriggerClick: function () {
var self = this;
self.__clickPopup = function (ev) {
ev.halt();
if (self.get('toggle')) {
self[self.get('visible') ? '_hiding' : '_showing'](ev);
} else {
self._showing(ev);
}
};
self.get("trigger").on('click', self.__clickPopup);
},
_showing: function (ev) {
var self = this;
self.set('currentTrigger', S.one(ev.target));
self.show();
},
_hiding: function () {
this.set('currentTrigger', undefined);
this.hide();
},
destructor: function () {
var self = this,
$el = self.$el,
t = self.get("trigger");
if (t) {
if (self.__clickPopup) {
t.detach('click', self.__clickPopup);
}
if (self.__mouseEnterPopup) {
t.detach('mouseenter', self.__mouseEnterPopup);
}
if (self._mouseLeavePopup) {
t.detach('mouseleave', self._mouseLeavePopup);
}
}
$el.detach('mouseleave', self._setHiddenTimer, self)
.detach('mouseenter', self._clearHiddenTimer, self);
}
}, {
ATTRS: {
/**
* Trigger elements to show popup.
* @cfg {KISSY.NodeList} trigger
*/
/**
* @ignore
*/
trigger: {
setter: function (v) {
return S.all(v);
}
},
/**
* How to activate trigger element, "click" or "mouse".
*
* Defaults to: "click".
*
* @cfg {String} triggerType
*/
/**
* @ignore
*/
triggerType: {
value: 'click'
},
currentTrigger: {},
/**
* When trigger type is mouse, the delayed time to show popup.
*
* Defaults to: 0.1, in seconds.
*
* @cfg {Number} mouseDelay
*/
/**
* @ignore
*/
mouseDelay: {
// triggerType 为 mouse 时, Popup 显示的延迟时间, 默认为 100ms
value: 0.1
},
/**
* When trigger type is click, whether support toggle.
*
* Defaults to: false
*
* @cfg {Boolean} toggle
*/
/**
* @ignore
*/
toggle: {
// triggerType 为 click 时, Popup 是否有toggle功能
value: false
}
},
xclass: 'popup'
});
}, {
requires: ["./control"]
});
/**
* @ignore
* 2011-05-17
* - yiminghe@gmail.com:利用 initializer , destructor ,ATTRS
**/
|
// LICENSE : MIT
"use strict";
/*
1.1.3.箇条書き
基本的に本文の文体に合わせます。
ただし、本文が「敬体」である場合、箇条書きに「常体」または「体言止め」も使う場合があります。
一般読者向け の文書で、本文が敬体である場合、多くの場合、箇条書きでも敬体を使います。
本文が「常体」である場合、箇条書きには「常体」または「体言止め」を使います。「敬体」は使いません。
いずれの場合も、ひとまとまりの箇条書きでは、敬体と常体を混在させません。文末に句点(。)を付けるかどうかも統一します。
*/
import { analyzeDesumasu, analyzeDearu } from "analyze-desumasu-dearu";
module.exports = function (context) {
let { Syntax, RuleError, report, getSource } = context;
let desumasuList = [];
let dearuList = [];
// 。付きのListItem
let withPointList = [];
// 。なしのListItem
let withoutPointList = [];
function resetList() {
dearuList = [];
desumasuList = [];
withPointList = [];
withoutPointList = [];
}
function reportPointResult(nodeList, { shouldUsePoint }) {
nodeList.forEach((node) => {
let message;
if (shouldUsePoint) {
message = `箇条書きの文末に句点(。)を付けて下さい。\n箇条書きの文末に句点(。)を付けるかを統一します。`;
} else {
message = `箇条書きの文末から句点(。)を外して下さい。\n箇条書きの文末に句点(。)を付けるかを統一します。`;
}
report(node, new RuleError(message));
});
}
function reportDesumaruDearuResult(list, { desumasu, dearu }) {
list.forEach(({ node, matches }) => {
matches.forEach((match) => {
let message;
if (desumasu) {
message = `箇条書きを敬体(ですます調)に統一して下さい。\nひとまとまりの箇条書きでは、敬体と常体を混在させません。\n"${match.value}"が常体(である調)です。`;
} else if (dearu) {
message = `箇条書きを常体(である調)に統一して下さい。\nひとまとまりの箇条書きでは、敬体と常体を混在させません。\n"${match.value}"が敬体(ですます調)です。`;
}
report(
node,
new RuleError(message, {
line: match.lineNumber - 1,
column: match.columnIndex
})
);
});
});
}
// 末尾に。があるかが統一されているのチェック
function countingPoint(withPointList, withoutPointList) {
if (withPointList.length === 0 || withoutPointList.length === 0) {
return;
}
if (withPointList.length > withoutPointList.length) {
// 。ありに統一
reportPointResult(withoutPointList, {
shouldUsePoint: true
});
} else if (withPointList.length < withoutPointList.length) {
// 。なしに統一
reportPointResult(withPointList, {
shouldUsePoint: false
});
} else {
// 。ありに統一
reportPointResult(withoutPointList, {
shouldUsePoint: true
});
}
}
// 敬体(ですます調)あるいは常体(である調)なのかのチェック
function countingDesumasuDearu(desumasuList, dearuList) {
let desumasuCount = desumasuList.reduce((count, { matches }) => count + matches.length, 0);
let dearuCount = dearuList.reduce((count, { matches }) => count + matches.length, 0);
if (desumasuCount === 0 || dearuCount === 0) {
return;
}
// ですます優先
if (desumasuCount > dearuCount) {
reportDesumaruDearuResult(dearuList, {
desumasu: true
});
} else if (desumasuCount < dearuCount) {
// である優先
reportDesumaruDearuResult(desumasuList, {
dearu: true
});
} else {
// 同等の場合はですます優先
reportDesumaruDearuResult(dearuList, {
desumasu: true
});
}
}
return {
[Syntax.List](node) {
resetList();
},
[Syntax.ListItem](node) {
let text = getSource(node);
// 末尾に。があるかが統一されているのチェック
let matchPointReg = /。(\s*?)$/;
if (matchPointReg.test(text)) {
// 。あり
withPointList.push(node);
} else {
// 。なし
withoutPointList.push(node);
}
// 敬体(ですます調)あるいは常体(である調)なのかのチェック
let retDesumasu = analyzeDesumasu(text);
if (retDesumasu.length > 0) {
desumasuList.push({
node: node,
matches: retDesumasu
});
}
let retDearu = analyzeDearu(text);
if (retDearu.length > 0) {
dearuList.push({
node: node,
matches: retDearu
});
}
},
[`${Syntax.List}:exit`](node) {
countingPoint(withPointList, withoutPointList);
countingDesumasuDearu(desumasuList, dearuList);
}
};
};
|
import React, { PropTypes } from 'react';
import * as m from 'material-ui';
import TodoAdd from './Todo/ToDoAdd';
import TodoEdit from './Todo/ToDoEdit';
export default class NoteDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleOpen() {
this.setState({open: true});
}
handleClose() {
this.setState({open: false});
}
toggleDialog() {
this.setState({
show: !this.state.show
});
}
//改变todoAdd的状态
changeAddTodoState(state) {
//获取todoAdd内部变量
const todoAddItem = this.refs.todoAdd.getWrappedInstance();
todoAddItem.changeAddTodoState(state);
}
render() {
const { todo } = this.props;
const actions = [
<m.FlatButton
label="关闭"
secondary={true}
onTouchTap={this.handleClose.bind(this)}/>,
<m.FlatButton
label="确认"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleClose.bind(this)}/>,
];
return (
<m.Dialog
title='编辑番茄任务'
titleClassName="dialog-title"
className="dialog"
//actions={actions}
modal={false}
open={this.state.open}
autoScrollBodyContent={true}
bodyClassName="dialog-body"
contentStyle={{width: '95%'}}
onRequestClose={this.handleClose.bind(this)}
>
<div style={{minHeight: '300px'}}>
{/* Todo add */}
<TodoAdd ref="todoAdd" todo={todo} />
{/* TOdo edit & show */}
<div className="todo-edit">
<TodoEdit todo={todo} changeAddTodoState={this.changeAddTodoState.bind(this)} />
</div>
</div>
</m.Dialog>
);
}
}
NoteDialog.propTypes = {
todo: PropTypes.object.isRequired,
};
|
#!/usr/bin/env node
'use strict';
var cli = require('../dist/cli');
var exitCode = cli.execute(process.argv);
/*eslint no-process-exit:0*/
process.exit(exitCode);
|
var ManagerUsers;
Meteor.startup(function() {
ManagerUsers = new Mongo.Collection('managerUsers');
});
Template.livechatUsers.helpers({
managers() {
return ManagerUsers.find({}, { sort: { name: 1 } });
},
agents() {
return AgentUsers.find({}, { sort: { name: 1 } });
},
emailAddress() {
if (this.emails && this.emails.length > 0) {
return this.emails[0].address;
}
},
agentAutocompleteSettings() {
return {
limit: 10,
// inputDelay: 300
rules: [{
// @TODO maybe change this 'collection' and/or template
collection: 'UserAndRoom',
subscription: 'userAutocomplete',
field: 'username',
template: Template.userSearch,
noMatchTemplate: Template.userSearchEmpty,
matchAll: true,
filter: {
exceptions: _.map(AgentUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; })
},
selector(match) {
return { username: match };
},
sort: 'username'
}]
};
},
managerAutocompleteSettings() {
return {
limit: 10,
// inputDelay: 300
rules: [{
// @TODO maybe change this 'collection' and/or template
collection: 'UserAndRoom',
subscription: 'userAutocomplete',
field: 'username',
template: Template.userSearch,
noMatchTemplate: Template.userSearchEmpty,
matchAll: true,
filter: {
exceptions: _.map(ManagerUsers.find({}, { fields: { username: 1 } }).fetch(), user => { return user.username; })
},
selector(match) {
return { username: match };
},
sort: 'username'
}]
};
}
});
Template.livechatUsers.events({
'click .remove-manager'(e/*, instance*/) {
e.preventDefault();
swal({
title: t('Are_you_sure'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: t('Yes'),
cancelButtonText: t('Cancel'),
closeOnConfirm: false,
html: false
}, () => {
Meteor.call('livechat:removeManager', this.username, function(error/*, result*/) {
if (error) {
return handleError(error);
}
swal({
title: t('Removed'),
text: t('Manager_removed'),
type: 'success',
timer: 1000,
showConfirmButton: false
});
});
});
},
'click .remove-agent'(e/*, instance*/) {
e.preventDefault();
swal({
title: t('Are_you_sure'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: t('Yes'),
cancelButtonText: t('Cancel'),
closeOnConfirm: false,
html: false
}, () => {
Meteor.call('livechat:removeAgent', this.username, function(error/*, result*/) {
if (error) {
return handleError(error);
}
swal({
title: t('Removed'),
text: t('Agent_removed'),
type: 'success',
timer: 1000,
showConfirmButton: false
});
});
});
},
'submit #form-manager'(e/*, instance*/) {
e.preventDefault();
if (e.currentTarget.elements.username.value.trim() === '') {
return toastr.error(t('Please_fill_a_username'));
}
var oldBtnValue = e.currentTarget.elements.add.value;
e.currentTarget.elements.add.value = t('Saving');
Meteor.call('livechat:addManager', e.currentTarget.elements.username.value, function(error/*, result*/) {
e.currentTarget.elements.add.value = oldBtnValue;
if (error) {
return handleError(error);
}
toastr.success(t('Manager_added'));
e.currentTarget.reset();
});
},
'submit #form-agent'(e/*, instance*/) {
e.preventDefault();
if (e.currentTarget.elements.username.value.trim() === '') {
return toastr.error(t('Please_fill_a_username'));
}
var oldBtnValue = e.currentTarget.elements.add.value;
e.currentTarget.elements.add.value = t('Saving');
Meteor.call('livechat:addAgent', e.currentTarget.elements.username.value, function(error/*, result*/) {
e.currentTarget.elements.add.value = oldBtnValue;
if (error) {
return handleError(error);
}
toastr.success(t('Agent_added'));
e.currentTarget.reset();
});
}
});
Template.livechatUsers.onCreated(function() {
this.subscribe('livechat:agents');
this.subscribe('livechat:managers');
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:6aec0f265ad214ab8d54fb2d12181a5faf383c121d2e44a53a947d301c0ef51b
size 39503
|
/**
* @fileOverview Uploader上传类
*/
define([
'./base',
'./mediator'
], function( Base, Mediator ) {
var $ = Base.$;
/**
* 上传入口类。
* @class Uploader
* @constructor
* @grammar new Uploader( opts ) => Uploader
* @example
* var uploader = WebUploader.Uploader({
* swf: 'path_of_swf/Uploader.swf',
*
* // 开起分片上传。
* chunked: true
* });
*/
function Uploader( opts ) {
this.options = $.extend( true, {}, Uploader.options, opts );
this._init( this.options );
}
// default Options
// widgets中有相应扩展
Uploader.options = {};
Mediator.installTo( Uploader.prototype );
// 批量添加纯命令式方法。
$.each({
upload: 'start-upload',
stop: 'stop-upload',
getFile: 'get-file',
getFiles: 'get-files',
// addFile: 'add-file',
// addFiles: 'add-file',
removeFile: 'remove-file',
skipFile: 'skip-file',
retry: 'retry',
isInProgress: 'is-in-progress',
makeThumb: 'make-thumb',
getDimension: 'get-dimension',
addButton: 'add-btn',
getRuntimeType: 'get-runtime-type',
refresh: 'refresh',
disable: 'disable',
enable: 'enable'
}, function( fn, command ) {
Uploader.prototype[ fn ] = function() {
return this.request( command, arguments );
};
});
$.extend( Uploader.prototype, {
state: 'pending',
_init: function( opts ) {
var me = this;
me.request( 'init', opts, function() {
me.state = 'ready';
me.trigger('ready');
});
},
/**
* 获取或者设置Uploader配置项。
* @method option
* @grammar option( key ) => *
* @grammar option( key, val ) => self
* @example
*
* // 初始状态图片上传前不会压缩
* var uploader = new WebUploader.Uploader({
* resize: null;
* });
*
* // 修改后图片上传前,尝试将图片压缩到1600 * 1600
* uploader.options( 'resize', {
* width: 1600,
* height: 1600
* });
*/
option: function( key, val ) {
var opts = this.options;
// setter
if ( arguments.length > 1 ) {
if ( $.isPlainObject( val ) &&
$.isPlainObject( opts[ key ] ) ) {
$.extend( opts[ key ], val );
} else {
opts[ key ] = val;
}
} else { // getter
return key ? opts[ key ] : opts;
}
},
/**
* 获取文件统计信息。返回一个包含一下信息的对象。
* * `successNum` 上传成功的文件数
* * `uploadFailNum` 上传失败的文件数
* * `cancelNum` 被删除的文件数
* * `invalidNum` 无效的文件数
* * `queueNum` 还在队列中的文件数
* @method getStats
* @grammar getStats() => Object
*/
getStats: function() {
// return this._mgr.getStats.apply( this._mgr, arguments );
var stats = this.request('get-stats');
return {
successNum: stats.numOfSuccess,
// who care?
// queueFailNum: 0,
cancelNum: stats.numOfCancel,
invalidNum: stats.numOfInvalid,
uploadFailNum: stats.numOfUploadFailed,
queueNum: stats.numOfQueue
};
},
// 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器
trigger: function( type/*, args...*/ ) {
var args = [].slice.call( arguments, 1 ),
opts = this.options,
name = 'on' + type.substring( 0, 1 ).toUpperCase() +
type.substring( 1 );
if ( Mediator.trigger.apply( this, arguments ) === false ) {
return false;
}
if ( $.isFunction( opts[ name ] ) &&
opts[ name ].apply( this, args ) === false ) {
return false;
}
if ( $.isFunction( this[ name ] ) &&
this[ name ].apply( this, args ) === false ) {
return false;
}
return true;
},
// widgets/widget.js将补充此方法的详细文档。
request: Base.noop,
reset: function() {
// @todo
}
});
/**
* 创建Uploader实例,等同于new Uploader( opts );
* @method create
* @class Base
* @static
* @grammar Base.create( opts ) => Uploader
*/
Base.create = function( opts ) {
return new Uploader( opts );
};
// 暴露Uploader,可以通过它来扩展业务逻辑。
Base.Uploader = Uploader;
return Uploader;
});
|
// prettier.config.js or .prettierrc.js
module.exports = {
printWidth: 120,
tabWidth: 2,
semi: true,
singleQuote: true,
bracketSpacing: true,
arrowParens: 'avoid',
endOfLine: 'lf'
};
|
var n = 15;
console.log (n.toLocaleString());
console.log (Object.prototype.toLocaleString.call(n));
|
/* jshint esversion: 6 */
let urlSelect = 'clients/select';
let urlInsert = 'clients/insert';
let urlUpdate = 'clients/update';
let urlDelete = 'clients/delete';
let dataTable;
$(function() {
'use strict';
if (!$.fn.DataTable.isDataTable('.dataTable')) {
dataTable = buildDataTable();
}
});
function buildDataTable() {
'use strict';
return $('.dataTable').DataTable({
ajax: {
url: urlSelect,
type: 'GET',
dataType: 'json',
dataSrc: '',
timeout: 10000,
error: function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, dataTable);
},
},
columnDefs: [
{
targets: 0,
orderable: false,
className: 'select-checkbox',
width: '1%',
data: null,
defaultContent: '',
},
{targets: 1, name: 'last_name', data: 'last_name'},
{targets: 2, name: 'first_name', data: 'first_name'},
{targets: 3, name: 'phone', data: 'phone', type: 'phoneNumber',
render: function(data, type, full, meta) {
data = JSON.parse(data);
let phonesString = '';
for (let i = 0; i < data.length; i++) {
if (i !== 0) {
phonesString += ', ' + data[i].phone;
} else {
phonesString += data[i].phone;
}
}
return phonesString;
},
},
{targets: 4, name: 'email', data: 'email'},
{targets: 5, name: 'skype', data: 'skype'},
],
rowId: 'client_id',
initComplete: function(settings, json) {
this.DataTable().columns().every(function(settings, json) {
let col = this;
$('input[type="text"]', col.footer()).on('keyup change', function() {
if (col.search() !== this.value) {
col.search(this.value).draw();
}
});
});
initDataTablesButtons(
this.DataTable(),
'.row-btns',
{
'actionAdd': btnAdd,
'actionEdit': btnEdit,
'actionDelete': btnDelete,
}
);
}
});
}
function btnAdd() {
'use strict';
$(':not(#modal-add)').modal('hide');
$('#modal-add').modal('toggle');
}
function btnEdit() {
'use strict';
$(':not(#modal-edit)').modal('hide');
$('#modal-edit').modal('toggle');
let selectedClientData = dataTable.rows({selected: true}).data().toArray();
let selectedClientPhoneData = JSON.parse(dataTable.rows({selected: true}).data()[0].phone);
let clientId = selectedClientData[0].client_id;
let clientLastName = selectedClientData[0].last_name;
let clientFirstName = selectedClientData[0].first_name;
let clientPhones = [];
for (let i = 0; i < selectedClientPhoneData.length; i++) {
clientPhones.push(selectedClientPhoneData[i].phone);
}
let clientEmail = selectedClientData[0].email;
let clientSkype = selectedClientData[0].skype;
$('#modal-edit #clientIdEdit').val(clientId);
$('#modal-edit #lastNameEdit').val($.parseHTML(clientLastName)[0].textContent);
$('#modal-edit #firstNameEdit').val($.parseHTML(clientFirstName)[0].textContent);
$('#modal-edit .phoneEdit').each(function(i, el) {
if (clientPhones[i]) {
$(this).val($.parseHTML(clientPhones[i])[0].textContent);
}
});
$('#modal-edit #emailEdit').val($.parseHTML(clientEmail)[0].textContent);
$('#modal-edit #skypeEdit').val($.parseHTML(clientSkype)[0].textContent);
}
function btnDelete() {
'use strict';
$(':not(#modal-delete)').modal('hide');
$('#modal-delete').modal('toggle');
}
function btnSubmitAdd(event) {
'use strict';
event.preventDefault();
let data = $('#formAdd :input').serializeArray();
$.ajax({
url: urlInsert,
type: 'POST',
data: data,
})
.done(function(data, textStatus, jqXHR) {
let addedRowId = '#' + data.last_insert_id;
dataTable.ajax.reload(function(json) {
dataTable.row(addedRowId).show().draw(false);
}, true);
})
.fail(function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, dataTable);
});
$('#modal-add').modal('toggle');
}
function btnSubmitEdit(event) {
'use strict';
event.preventDefault();
let data = $('#formEdit :input').serializeArray();
$.ajax({
url: urlUpdate,
type: 'PATCH',
data: data,
})
.done(function(data, textStatus, jqXHR) {
let updatedRowId = '#' + data.last_update_id;
dataTable.rows().deselect();
dataTable.ajax.reload(function(json) {
dataTable.row(updatedRowId).show().draw(false);
}, true);
})
.fail(function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, dataTable);
});
$('#modal-edit').modal('toggle');
}
function btnSubmitDelete(event) {
'use strict';
event.preventDefault();
let data = {
'clientId': dataTable.rows({selected: true}).ids().toArray(),
};
$.ajax({
url: urlDelete,
type: 'DELETE',
data: data,
})
.done(function(data, textStatus, jqXHR) {
let deletedRowsIds = data.deleted_ids;
for (let i = 0; i < deletedRowsIds.length; i++) {
deletedRowsIds[i] = '#' + deletedRowsIds[i];
}
dataTable.rows(deletedRowsIds).remove().draw('page');
dataTable.rows().deselect();
})
.fail(function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, dataTable);
});
$('#modal-delete').modal('toggle');
}
|
class Template {
constructor() {
// if you want to have global vars in your plugin youd put them here
this.somear = 'xd';
}
default (command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);;
self.disnode.bot.SendEmbed(command.msg.channel_id, {
color: embed,
thumbnail: {
url: "https://cdn.discordapp.com/attachments/346789645700562974/348606333223960586/giphy.gif"
},
author: {},
fields: [{
name: "Prefix",
inline: false,
value: `The prefix for Zolbot is ~ and for Apotheosis is =`,
},
{
name: "~z yt",
inline: false,
value: `Displays links to the youtube accounts of the owners`,
},
{
name: "~z invite",
inline: false,
value: "Displays a link that invites Apotheosis to your own server",
},
{
name: "~z donate",
inline: false,
value: "Displays a link to Zolfe's paypal",
},
{
name: "~z url",
inline: false,
value: "Displays a link to Zolfe's website",
},
{
name: "~z twitter",
inline: false,
value: "Displays links to the twitter accounts of the owners ====================================",
}
],
footer: {
text: `${command.msg.author.username} | These are how to correctly input commands.`
},
timestamp: new Date(),
})
}
commandinvite(command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);
self.disnode.bot.SendCompactEmbed(command.msg.channel_id, "INVITE APOTHEOSIS TO YOUR SERVER:", "https://discordapp.com/oauth2/authorize?permissions=1341643971&scope=bot&client_id=332385757668835328" , embed)
}
commandyt(command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);
self.disnode.bot.SendEmbed(command.msg.channel_id, {
color: embed,
thumbnail: {
url: "https://cdn.discordapp.com/attachments/346789645700562974/347890380857016332/6-2-youtube-png-picture.png"
},
author: {},
fields: [{
name: "Zolfe's Youtube:",
inline: true,
value: `https://www.youtube.com/channel/UC-8bGtCppF9SMwfL7hD1uLQ`,
},
{
name: "Aiir's Youtube:",
inline: true,
value: `https://www.youtube.com/channel/UCpG9K0EoyTNZl97Yw6nmHEg`,
},
{
name: "Xynf's Youtube",
inline: true,
value: 'https://www.youtube.com/channel/UC85edk9m1tRgncjVRFEdtAA',
}
],
footer: {}
})
}
commandwebsite(command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);
self.disnode.bot.SendEmbed(command.msg.channel_id, {
color: embed,
thumbnail: {
url: ""
},
author: {},
fields: [{
name: "Zolfe's Website:",
inline: false,
value: `============
https://Zolfe.us`,
}],
footer: {}
});
}
commandpaypal(command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);
self.disnode.bot.SendEmbed(command.msg.channel_id, {
color: embed,
thumbnail: {
url: "https://cdn.discordapp.com/attachments/346789645700562974/348032812454117376/paypal_PNG7.png"
},
author: {},
fields: [{
name: "DONATE HERE:",
inline: false,
value: `============
https://www.paypal.me/Zolfe`,
}],
footer: {}
});
}
commandtwitter(command) {
var self = this;
var embed = Math.floor(Math.random() * 0x999099);
self.disnode.bot.DeleteMessage(command.msg.channel_id, command.msg.id);
self.disnode.bot.SendEmbed(command.msg.channel_id, {
color: embed,
thumbnail: {
url: "https://cdn.discordapp.com/attachments/346789645700562974/347892662663249922/Twitter.png"
},
author: {},
fields: [{
name: "Zolfe's Twitter:",
inline: false,
value: `https://www.twitter.com/ZolfeYT`,
},
{
name: "Aiir's Twitter:",
inline: false,
value: `https://www.twitter.com/XBLAiir`,
},
{
name: "Xynf's Twitter:",
inline: false,
value: `https://www.twitter.com/XBLXynf`,
}
],
footer: {}
})
}
}
module.exports = Template;
// this is the base of every plugin
|
/**
* Check and return true if an object not undefined or null
*/
export function isPresent(obj) {
return obj !== undefined && obj !== null;
}
|
{
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
|
/**
* @author Ed Spencer
*
* Fields are used to define what a Model is. They aren't instantiated directly - instead, when we create a class that
* extends {@link Ext.data.Model}, it will automatically create a Field instance for each field configured in a {@link
* Ext.data.Model Model}. For example, we might set up a model like this:
*
* Ext.define('User', {
* extend: 'Ext.data.Model',
* fields: [
* 'name', 'email',
* {name: 'age', type: 'int'},
* {name: 'gender', type: 'string', defaultValue: 'Unknown'}
* ]
* });
*
* Four fields will have been created for the User Model - name, email, age and gender. Note that we specified a couple
* of different formats here; if we only pass in the string name of the field (as with name and email), the field is set
* up with the 'auto' type. It's as if we'd done this instead:
*
* Ext.define('User', {
* extend: 'Ext.data.Model',
* fields: [
* {name: 'name', type: 'auto'},
* {name: 'email', type: 'auto'},
* {name: 'age', type: 'int'},
* {name: 'gender', type: 'string', defaultValue: 'Unknown'}
* ]
* });
*
* # Types and conversion
*
* The {@link #type} is important - it's used to automatically convert data passed to the field into the correct format.
* In our example above, the name and email fields used the 'auto' type and will just accept anything that is passed
* into them. The 'age' field had an 'int' type however, so if we passed 25.4 this would be rounded to 25.
*
* Sometimes a simple type isn't enough, or we want to perform some processing when we load a Field's data. We can do
* this using a {@link #convert} function. Here, we're going to create a new field based on another:
*
* Ext.define('User', {
* extend: 'Ext.data.Model',
* fields: [
* {
* name: 'firstName',
* convert: function(value, record) {
* var fullName = record.get('name'),
* splits = fullName.split(" "),
* firstName = splits[0];
*
* return firstName;
* }
* },
* 'name', 'email',
* {name: 'age', type: 'int'},
* {name: 'gender', type: 'string', defaultValue: 'Unknown'}
* ]
* });
*
* Now when we create a new User, the firstName is populated automatically based on the name:
*
* var ed = Ext.create('User', {name: 'Ed Spencer'});
*
* console.log(ed.get('firstName')); //logs 'Ed', based on our convert function
*
* Fields which are configured with a custom ```convert``` function are read *after* all other fields
* when constructing and reading records, so that if convert functions rely on other, non-converted fields
* (as in this example), they can be sure of those fields being present.
*
* In fact, if we log out all of the data inside ed, we'll see this:
*
* console.log(ed.data);
*
* //outputs this:
* {
* age: 0,
* email: "",
* firstName: "Ed",
* gender: "Unknown",
* name: "Ed Spencer"
* }
*
* The age field has been given a default of zero because we made it an int type. As an auto field, email has defaulted
* to an empty string. When we registered the User model we set gender's {@link #defaultValue} to 'Unknown' so we see
* that now. Let's correct that and satisfy ourselves that the types work as we expect:
*
* ed.set('gender', 'Male');
* ed.get('gender'); //returns 'Male'
*
* ed.set('age', 25.4);
* ed.get('age'); //returns 25 - we wanted an int, not a float, so no decimal places allowed
*/
Ext.define('Ext.data.Field', {
requires: ['Ext.data.Types', 'Ext.data.SortTypes'],
alias: 'data.field',
isField: true,
constructor : function(config) {
var me = this,
types = Ext.data.Types,
st;
if (Ext.isString(config)) {
config = {name: config};
}
Ext.apply(me, config);
st = me.sortType;
if (me.type) {
if (Ext.isString(me.type)) {
me.type = types[me.type.toUpperCase()] || types.AUTO;
}
} else {
me.type = types.AUTO;
}
// named sortTypes are supported, here we look them up
if (Ext.isString(st)) {
me.sortType = Ext.data.SortTypes[st];
} else if(Ext.isEmpty(st)) {
me.sortType = me.type.sortType;
}
// Reference this type's default converter if we did not recieve one in configuration.
if (!config.hasOwnProperty('convert')) {
me.convert = me.type.convert; // this may be undefined (e.g., AUTO)
} else if (!me.convert && me.type.convert && !config.hasOwnProperty('defaultValue')) {
// If the converter has been nulled out, and we have not been configured
// with a field-specific defaultValue, then coerce the inherited defaultValue into our data type.
me.defaultValue = me.type.convert(me.defaultValue);
}
if (config.convert) {
me.hasCustomConvert = true;
}
},
/**
* @cfg {String} name
*
* The name by which the field is referenced within the Model. This is referenced by, for example, the `dataIndex`
* property in column definition objects passed to {@link Ext.grid.property.HeaderContainer}.
*
* Note: In the simplest case, if no properties other than `name` are required, a field definition may consist of
* just a String for the field name.
*/
/**
* @cfg {String/Object} type
*
* The data type for automatic conversion from received data to the *stored* value if
* `{@link Ext.data.Field#convert convert}` has not been specified. This may be specified as a string value.
* Possible values are
*
* - auto (Default, implies no conversion)
* - string
* - int
* - float
* - boolean
* - date
*
* This may also be specified by referencing a member of the {@link Ext.data.Types} class.
*
* Developers may create their own application-specific data types by defining new members of the {@link
* Ext.data.Types} class.
*/
/**
* @cfg {Function} [convert]
*
* A function which converts the value provided by the Reader into an object that will be stored in the Model.
*
* If configured as `null`, then no conversion will be applied to the raw data property when this Field
* is read. This will increase performance. but you must ensure that the data is of the correct type and does
* not *need* converting.
*
* It is passed the following parameters:
*
* - **v** : Mixed
*
* The data value as read by the Reader, if undefined will use the configured `{@link Ext.data.Field#defaultValue
* defaultValue}`.
*
* - **rec** : Ext.data.Model
*
* The data object containing the Model as read so far by the Reader. Note that the Model may not be fully populated
* at this point as the fields are read in the order that they are defined in your
* {@link Ext.data.Model#cfg-fields fields} array.
*
* Example of convert functions:
*
* function fullName(v, record){
* return record.data.last + ', ' + record.data.first;
* }
*
* function location(v, record){
* return !record.data.city ? '' : (record.data.city + ', ' + record.data.state);
* }
*
* Ext.define('Dude', {
* extend: 'Ext.data.Model',
* fields: [
* {name: 'fullname', convert: fullName},
* {name: 'firstname', mapping: 'name.first'},
* {name: 'lastname', mapping: 'name.last'},
* {name: 'city', defaultValue: 'homeless'},
* 'state',
* {name: 'location', convert: location}
* ]
* });
*
* // create the data store
* var store = Ext.create('Ext.data.Store', {
* reader: {
* type: 'json',
* model: 'Dude',
* idProperty: 'key',
* root: 'daRoot',
* totalProperty: 'total'
* }
* });
*
* var myData = [
* { key: 1,
* name: { first: 'Fat', last: 'Albert' }
* // notice no city, state provided in data object
* },
* { key: 2,
* name: { first: 'Barney', last: 'Rubble' },
* city: 'Bedrock', state: 'Stoneridge'
* },
* { key: 3,
* name: { first: 'Cliff', last: 'Claven' },
* city: 'Boston', state: 'MA'
* }
* ];
*/
/**
* @cfg {Function} [serialize]
* A function which converts the Model's value for this Field into a form which can be used by whatever {@link Ext.data.writer.Writer Writer}
* is being used to sync data with the server.
*
* The function should return a string which represents the Field's value.
*
* It is passed the following parameters:
*
* - **v** : Mixed
*
* The Field's value - the value to be serialized.
*
* - **rec** : Ext.data.Model
*
* The record being serialized.
*
*/
/**
* @cfg {String} dateFormat
*
* Serves as a default for the {@link #dateReadFormat} and {@link #dateWriteFormat} config options. This
* will be used in place of those other configurations if not specified.
*
* A format string for the {@link Ext.Date#parse Ext.Date.parse} function, or "timestamp" if the value provided by
* the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a javascript millisecond
* timestamp. See {@link Ext.Date}.
*
* It is quite important to note that while this config is optional, it will default to using the base
* JavaScript Date object's `parse` function if not specified, rather than {@link Ext.Date#parse Ext.Date.parse}.
* This can cause unexpected issues, especially when converting between timezones, or when converting dates that
* do not have a timezone specified. The behavior of the native `Date.parse` is implementation-specific, and
* depending on the value of the date string, it might return the UTC date or the local date. For this reason
* it is strongly recommended that you always specify an explicit date format when parsing dates.
*/
dateFormat: null,
/**
* @cfg {String} dateReadFormat
* Used when converting received data into a Date when the {@link #type} is specified as `"date"`.
* This configuration takes precedence over {@link #dateFormat}.
* See {@link #dateFormat} for more information.
*/
dateReadFormat: null,
/**
* @cfg {String} dateWriteFormat
* Used to provide a custom format when serializing dates with a {@link Ext.data.writer.Writer}.
* If this is not specified, the {@link #dateFormat} will be used. See the {@link Ext.data.writer.Writer}
* docs for more information on writing dates.
*/
dateWriteFormat: null,
/**
* @cfg {Boolean} useNull
*
* Use when converting received data into a INT, FLOAT, BOOL or STRING type. If the value cannot be
* parsed, `null` will be used if useNull is true, otherwise a default value for that type will be used:
*
* - for INT and FLOAT - `0`.
* - for STRING - `""`.
* - for BOOL - `false`.
*
* Note that when parsing of DATE type fails, the value will be `null` regardless of this setting.
*/
useNull: false,
/**
* @cfg {Object} [defaultValue=""]
*
* The default value used when the creating an instance from a raw data object, and the property referenced by the
* `{@link Ext.data.Field#mapping mapping}` does not exist in that data object.
*
* May be specified as `undefined` to prevent defaulting in a value.
*/
defaultValue: "",
/**
* @cfg {String/Number} mapping
*
* (Optional) A path expression for use by the {@link Ext.data.reader.Reader} implementation that is creating the
* {@link Ext.data.Model Model} to extract the Field value from the data object. If the path expression is the same
* as the field name, the mapping may be omitted.
*
* The form of the mapping expression depends on the Reader being used.
*
* - {@link Ext.data.reader.Json}
*
* The mapping is a string containing the javascript expression to reference the data from an element of the data
* item's {@link Ext.data.reader.Json#cfg-root root} Array. Defaults to the field name.
*
* - {@link Ext.data.reader.Xml}
*
* The mapping is an {@link Ext.DomQuery} path to the data item relative to the DOM element that represents the
* {@link Ext.data.reader.Xml#record record}. Defaults to the field name.
*
* - {@link Ext.data.reader.Array}
*
* The mapping is a number indicating the Array index of the field's value. Defaults to the field specification's
* Array position.
*
* If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
* function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
* return the desired data.
*/
mapping: null,
/**
* @cfg {Function/String} sortType
*
* A function which converts a Field's value to a comparable value in order to ensure correct sort ordering.
* Predefined functions are provided in {@link Ext.data.SortTypes}. A custom sort example:
*
* // current sort after sort we want
* // +-+------+ +-+------+
* // |1|First | |1|First |
* // |2|Last | |3|Second|
* // |3|Second| |2|Last |
* // +-+------+ +-+------+
*
* sortType: function(value) {
* switch (value.toLowerCase()) // native toLowerCase():
* {
* case 'first': return 1;
* case 'second': return 2;
* default: return 3;
* }
* }
*
* May also be set to a String value, corresponding to one of the named sort types in {@link Ext.data.SortTypes}.
*/
sortType : null,
/**
* @cfg {String} sortDir
*
* Initial direction to sort (`"ASC"` or `"DESC"`). Defaults to `"ASC"`.
*/
sortDir : "ASC",
/**
* @cfg {Boolean} allowBlank
* @private
*
* Used for validating a {@link Ext.data.Model model}. Defaults to true. An empty value here will cause
* {@link Ext.data.Model}.{@link Ext.data.Model#isValid isValid} to evaluate to false.
*/
allowBlank : true,
/**
* @cfg {Boolean} persist
*
* False to exclude this field from the {@link Ext.data.Model#modified} fields in a model. This will also exclude
* the field from being written using a {@link Ext.data.writer.Writer}. This option is useful when model fields are
* used to keep state on the client but do not need to be persisted to the server. Defaults to true.
*/
persist: true
});
|
(function() {
var _ = require('lodash');
var ID = require('./ID');
var Request = require('./Request');
var Entry = require('./Entry');
var Utils = require('./Utils');
var Node = function(nodeInfo, localId, nodeFactory, connectionFactory, requestHandler, config) {
if (!Node.isValidNodeInfo(nodeInfo)) {
throw new Error("Invalid arguments.");
}
if (!Utils.isZeroOrPositiveNumber(config.requestTimeout)) {
config.requestTimeout = 180000;
}
if (!Utils.isZeroOrPositiveNumber(config.maxRoundCount)) {
config.maxRoundCount = 1;
}
this._peerId = nodeInfo.peerId;
this.nodeId = ID.create(nodeInfo.peerId);
this._localId = localId;
this._nodeFactory = nodeFactory;
this._connectionFactory = connectionFactory;
this._requestHandler = requestHandler;
this._config = config;
};
Node.isValidNodeInfo = function(nodeInfo) {
if (!_.isObject(nodeInfo)) {
return false;
}
if (!Utils.isNonemptyString(nodeInfo.peerId)) {
return false;
}
return true;
};
Node.prototype = {
findSuccessor: function(key, callback) {
var self = this;
if (!(key instanceof ID)) {
callback(null);
return;
}
var roundCount = 0;
(function _findSuccessor(node) {
node.findSuccessorIterative(key, function(status, successor, error) {
if (status === 'SUCCESS') {
callback(successor);
} else if (status === 'REDIRECT') {
if (self.nodeId.isInInterval(node.nodeId, successor.nodeId)) {
roundCount++;
if (roundCount > self._config.maxRoundCount) {
callback(null, new Error("FIND_SUCCESSOR request circulates in the network."));
return;
}
}
Utils.debug("[findSuccessor] redirected to " + successor.getPeerId());
_findSuccessor(successor);
} else if (status === 'FAILED') {
callback(null, error);
} else {
callback(null, new Error("Got unknown status:", status));
}
});
})(this);
},
findSuccessorIterative: function(key, callback) {
var self = this;
this._sendRequest('FIND_SUCCESSOR', {
key: key.toHexString()
}, {
success: function(result) {
var nodeInfo = result.successorNodeInfo;
self._nodeFactory.create(nodeInfo, function(successor, error) {
if (error) {
callback('FAILED', null, error);
return;
}
callback('SUCCESS', successor);
});
},
redirect: function(result) {
self._nodeFactory.create(result.redirectNodeInfo, function(nextNode, error) {
if (error) {
callback('FAILED', null, error);
return;
}
callback('REDIRECT', nextNode);
});
},
error: function(error) {
callback('FAILED', null, error);
}
});
},
notifyAndCopyEntries: function(potentialPredecessor, callback) {
var self = this;
this._sendRequest('NOTIFY_AND_COPY', {
potentialPredecessorNodeInfo: potentialPredecessor.toNodeInfo()
}, {
success: function(result) {
if (!_.isArray(result.referencesNodeInfo) || !_.isArray(result.entries)) {
callback(null, null);
return;
}
self._nodeFactory.createAll(result.referencesNodeInfo, function(references) {
var entries = _.chain(result.entries)
.map(function(entry) {
try {
return Entry.fromJson(entry);
} catch (e) {
return null;
}
})
.reject(function(entry) { return _.isNull(entry); })
.value();
callback(references, entries);
});
},
error: function(error) {
callback(null, null, error);
}
});
},
notify: function(potentialPredecessor, callback) {
var self = this;
this._sendRequest('NOTIFY', {
potentialPredecessorNodeInfo: potentialPredecessor.toNodeInfo()
}, {
success: function(result) {
if (!_.isArray(result.referencesNodeInfo)) {
callback(null);
return;
}
self._nodeFactory.createAll(result.referencesNodeInfo, function(references) {
callback(references);
});
},
error: function(error) {
callback(null, error);
}
});
},
notifyAsSuccessor: function(potentialSuccessor, callback) {
var self = this;
this._sendRequest('NOTIFY_AS_SUCCESSOR', {
potentialSuccessorNodeInfo: potentialSuccessor.toNodeInfo()
}, {
success: function(result) {
self._nodeFactory.create(result.successorNodeInfo, function(successor, error) {
if (error) {
callback(null, error);
return;
}
callback(successor);
});
},
error: function(error) {
callback(null, error);
}
});
},
leavesNetwork: function(predecessor) {
var self = this;
if (_.isNull(predecessor)) {
throw new Error("Invalid argument.");
}
this._sendRequest('LEAVES_NETWORK', {
predecessorNodeInfo: predecessor.toNodeInfo()
});
},
ping: function(callback) {
this._sendRequest('PING', {}, {
success: function(result) {
callback();
},
error: function(error) {
callback(error);
}
});
},
insertReplicas: function(replicas) {
this._sendRequest('INSERT_REPLICAS', {replicas: _.invoke(replicas, 'toJson')});
},
removeReplicas: function(sendingNodeId, replicas) {
this._sendRequest('REMOVE_REPLICAS', {
sendingNodeId: sendingNodeId.toHexString(),
replicas: _.invoke(replicas, 'toJson')
});
},
insertEntry: function(entry, callback) {
var self = this;
this._sendRequest('INSERT_ENTRY', {
entry: entry.toJson()
}, {
success: function(result) {
callback();
},
redirect: function(result) {
self._nodeFactory.create(result.redirectNodeInfo, function(node, error) {
if (error) {
callback(error);
return;
}
Utils.debug("[insertEntry] redirected to " + node.getPeerId());
node.insertEntry(entry, callback);
});
},
error: function(error) {
callback(error);
}
});
},
retrieveEntries: function(id, callback) {
var self = this;
this._sendRequest('RETRIEVE_ENTRIES', {
id: id.toHexString()
}, {
success: function(result) {
if (!_.isArray(result.entries)) {
callback(null, new Error("Received invalid data from " + self._peerId));
return;
}
var entries = _.chain(result.entries)
.map(function(entry) {
try {
return Entry.fromJson(entry);
} catch (e) {
return null;
}
})
.reject(function(entry) { return _.isNull(entry); })
.value();
callback(entries);
},
redirect: function(result) {
self._nodeFactory.create(result.redirectNodeInfo, function(node, error) {
if (error) {
callback(null, error);
return;
}
Utils.debug("[retrieveEntries] redirected to " + node.getPeerId());
node.retrieveEntries(id, callback);
});
},
error: function(error) {
callback(null, error);
}
});
},
removeEntry: function(entry, callback) {
var self = this;
this._sendRequest('REMOVE_ENTRY', {
entry: entry.toJson()
}, {
success: function(result) {
callback();
},
redirect: function(result) {
self._nodeFactory.create(result.redirectNodeInfo, function(node, error) {
if (error) {
callback(error);
return;
}
Utils.debug("[removeEntry] redirected to " + node.getPeerId());
node.removeEntry(entry, callback);
});
},
error: function(error) {
callback(error);
}
});
},
_sendRequest: function(method, params, callbacks) {
var self = this;
this._connectionFactory.create(this._peerId, function(connection, error) {
if (error) {
if (callbacks && callbacks.error) {
callbacks.error(error);
}
return;
}
self._nodeFactory.setListenersToConnection(connection);
var request = Request.create(method, params);
if (callbacks) {
callbacks = _.defaults(callbacks, {
success: function() {}, redirect: function() {}, error: function() {}
});
var timer = setTimeout(function() {
self._nodeFactory.deregisterCallback(request.requestId);
callbacks.error(new Error(method + " request to " + self._peerId + " timed out."));
}, self._config.requestTimeout);
self._nodeFactory.registerCallback(request.requestId, _.once(function(response) {
clearTimeout(timer);
switch (response.status) {
case 'SUCCESS': callbacks.success(response.result); break;
case 'REDIRECT': callbacks.redirect(response.result); break;
case 'FAILED':
callbacks.error(new Error(
"Request to " + self._peerId + " failed: " + response.result.message));
break;
default:
callback.error(new Error("Received unknown status response:", response.status));
}
}));
}
Utils.debug("Sending request to", self._peerId, ":", request.method);
connection.send(request.toJson());
});
},
onRequestReceived: function(request) {
var self = this;
Utils.debug("Received request from", this._peerId, ":", request.method);
this._requestHandler.handle(request, function(response) {
self._connectionFactory.create(self._peerId, function(connection, error) {
if (error) {
console.log(error);
return;
}
self._nodeFactory.setListenersToConnection(connection);
Utils.debug("Sending response to", self._peerId, ":", response.method);
connection.send(response.toJson());
});
});
},
onResponseReceived: function(response) {
Utils.debug("Received response from", this._peerId, ":", response.method, "(", response.status, ")");
var callback = this._nodeFactory.deregisterCallback(response.requestId);
if (!_.isNull(callback)) {
callback(response);
}
},
disconnect: function() {
this._connectionFactory.removeConnection(this._peerId);
},
getPeerId: function() {
return this._peerId;
},
toNodeInfo: function() {
return {
nodeId: this.nodeId.toHexString(),
peerId: this._peerId
};
},
equals: function(node) {
if (_.isNull(node)) {
return false;
}
return this.nodeId.equals(node.nodeId);
},
toString: function() {
return this.nodeId.toHexString() + " (" + this._peerId + ")";
}
};
module.exports = Node;
})();
|
/// <binding ProjectOpened='watch' />
// all gulp tasks are located in the ./build/tasks directory
// gulp configuration is in files in ./build directory
require('require-dir')('build/tasks');
|
#!/usr/bin/env node
'use strict';
/*eslint no-console: 0, no-sync: 0*/
// System.js bundler
// simple and yet reusable system.js bundler
// bundles, minifies and gzips
const fs = require('fs');
const del = require('del');
const path = require('path');
const zlib = require('zlib');
const async = require('async');
const Builder = require('systemjs-builder');
const pkg = require('../package.json');
const name = pkg.name;
const targetFolder = path.resolve('./bundles');
async.waterfall([
cleanBundlesFolder,
getSystemJsBundleConfig,
buildSystemJs({minify: false, sourceMaps: true, mangle: false}),
getSystemJsBundleConfig,
buildSystemJs({minify: true, sourceMaps: true, mangle: false}),
gzipSystemJsBundle
], err => {
if (err) {
throw err;
}
});
function getSystemJsBundleConfig(cb) {
const config = {
baseURL: '..',
transpiler: 'typescript',
typescriptOptions: {
module: 'cjs'
},
map: {
typescript: path.resolve('node_modules/typescript/lib/typescript.js'),
'@angular/core': path.resolve('node_modules/@angular/core/index.js'),
'@angular/common': path.resolve('node_modules/@angular/common/index.js'),
'@angular/compiler': path.resolve('node_modules/@angular/compiler/index.js'),
'@angular/platform-browser': path.resolve('node_modules/@angular/platform-browser/index.js'),
'@angular/platform-browser-dynamic': path.resolve('node_modules/@angular/platform-browser-dynamic/'),
rxjs: path.resolve('node_modules/rxjs')
},
paths: {
'*': '*.js'
}
};
config.meta = ['@angular/common','@angular/compiler','@angular/core',
'@angular/platform-browser','@angular/platform-browser-dynamic', 'rxjs'].reduce((memo, currentValue) => {
memo[path.resolve(`node_modules/${currentValue}/*`)] = {build: false};
return memo;
}, {});
config.meta.moment = {build: false};
return cb(null, config);
}
function cleanBundlesFolder(cb) {
return del(targetFolder)
.then(paths => {
console.log('Deleted files and folders:\n', paths.join('\n'));
cb();
});
}
function buildSystemJs(options) {
return (config, cb) => {
const minPostFix = options && options.minify ? '.min' : '';
const fileName = `${name}${minPostFix}.js`;
const dest = path.resolve(__dirname, targetFolder, fileName);
const builder = new Builder();
console.log('Bundling system.js file:', fileName, options);
builder.config(config);
return builder
.bundle([name, name].join('/'), dest, options)
.then(() => cb())
.catch(cb);
};
}
function gzipSystemJsBundle(cb) {
const files = fs
.readdirSync(path.resolve(targetFolder))
.map(file => path.resolve(targetFolder, file))
.filter(file => fs.statSync(file).isFile())
.filter(file => path.extname(file) !== 'gz');
return async.eachSeries(files, (file, gzipcb) => {
process.nextTick(() => {
console.log('Gzipping ', file);
const gzip = zlib.createGzip({level: 9});
const inp = fs.createReadStream(file);
const out = fs.createWriteStream(`${file}.gz`);
inp.on('end', () => gzipcb());
inp.on('error', err => gzipcb(err));
return inp.pipe(gzip).pipe(out);
});
}, cb);
}
|
import BendpointRules from './BendpointRules';
export default {
__init__: [ 'bendpointRules' ],
bendpointRules: [ 'type', BendpointRules ]
};
|
describe('assessment: headerH1', function () {
var client, assessments, quailResults, cases;
// Evaluate the test page with Quail.
before('load webdrivers and run evaluations with Quail', function () {
return quailTestRunner.setup({
url: 'http://localhost:9999/headerH1/headerH1.html',
assessments: [
'headerH1'
]
})
.spread(function (_client_, _assessments_, _quailResults_) {
client = _client_;
assessments = _assessments_;
quailResults = _quailResults_;
});
});
after('end the webdriver session', function () {
return quailTestRunner.teardown(client);
});
it('should return the correct number of tests', function () {
expect(quailResults.stats.tests).to.equal(1);
});
it('should return the correct number of cases', function () {
expect(quailResults.stats.cases).to.equal(4);
});
it('should have correct key under the test results', function () {
expect(quailResults.tests).to.include.keys('headerH1');
});
it('should return the proper assessment for assert-1', function () {
cases = quailResults.tests.headerH1.cases;
expect(cases).quailGetById('assert-1').to.have.quailStatus('failed');
});
it('should return the proper assessment for assert-2', function () {
cases = quailResults.tests.headerH1.cases;
expect(cases).quailGetById('assert-2').to.have.quailStatus('passed');
});
});
|
/*!
* Piwik - free/libre analytics platform
*
* JavaScript tracking client
*
* @link http://piwik.org
* @source https://github.com/piwik/piwik/blob/master/js/piwik.js
* @license http://piwik.org/free-software/bsd/ BSD-3 Clause (also in js/LICENSE.txt)
* @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause
*/
// NOTE: if you change this above Piwik comment block, you must also change `$byteStart` in js/tracker.php
// Refer to README.md for build instructions when minifying this file for distribution.
/*
* Browser [In]Compatibility
* - minimum required ECMAScript: ECMA-262, edition 3
*
* Incompatible with these (and earlier) versions of:
* - IE4 - try..catch and for..in introduced in IE5
* - IE5 - named anonymous functions, array.push, encodeURIComponent, decodeURIComponent, and getElementsByTagName introduced in IE5.5
* - Firefox 1.0 and Netscape 8.x - FF1.5 adds array.indexOf, among other things
* - Mozilla 1.7 and Netscape 6.x-7.x
* - Netscape 4.8
* - Opera 6 - Error object (and Presto) introduced in Opera 7
* - Opera 7
*/
/************************************************************
* JSON - public domain reference implementation by Douglas Crockford
* @version 2012-10-08
* @link http://www.JSON.org/js.html
************************************************************/
/*jslint evil: true, regexp: false, bitwise: true, white: true */
/*global JSON2:true */
/*global window:true */
/*property JSON:true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, sort, slice, stringify,
test, toJSON, toString, valueOf,
objectToJSON
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON2 !== 'object') {
JSON2 = window.JSON || {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
function objectToJSON(value, key) {
var objectType = Object.prototype.toString.apply(value);
if (objectType === '[object Date]') {
return isFinite(value.valueOf())
? value.getUTCFullYear() + '-' +
f(value.getUTCMonth() + 1) + '-' +
f(value.getUTCDate()) + 'T' +
f(value.getUTCHours()) + ':' +
f(value.getUTCMinutes()) + ':' +
f(value.getUTCSeconds()) + 'Z'
: null;
}
if (objectType === '[object String]' ||
objectType === '[object Number]' ||
objectType === '[object Boolean]') {
return value.valueOf();
}
if (objectType !== '[object Array]' &&
typeof value.toJSON === 'function') {
return value.toJSON(key);
}
return value;
}
var cx = new RegExp('[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', 'g'),
// hack: workaround Snort false positive (sid 8443)
pattern = '\\\\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]',
escapable = new RegExp('[' + pattern, 'g'),
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object') {
value = objectToJSON(value, key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON2.stringify !== 'function') {
JSON2.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON2.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON2.parse !== 'function') {
JSON2.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if ((new RegExp('^[\\],:{}\\s]*$'))
.test(text.replace(new RegExp('\\\\(?:["\\\\/bfnrt]|u[0-9a-fA-F]{4})', 'g'), '@')
.replace(new RegExp('"[^"\\\\\n\r]*"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?', 'g'), ']')
.replace(new RegExp('(?:^|:|,)(?:\\s*\\[)+', 'g'), ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON2.parse');
};
}
}());
/************************************************************
* end JSON
************************************************************/
/*jslint browser:true, plusplus:true, vars:true, nomen:true, evil:true */
/*global window */
/*global unescape */
/*global ActiveXObject */
/*members encodeURIComponent, decodeURIComponent, getElementsByTagName,
shift, unshift, piwikAsyncInit,
createElement, appendChild, characterSet, charset,
addEventListener, attachEvent, removeEventListener, detachEvent, disableCookies,
cookie, domain, readyState, documentElement, doScroll, title, text,
location, top, onerror, document, referrer, parent, links, href, protocol, name, GearsFactory,
performance, mozPerformance, msPerformance, webkitPerformance, timing, requestStart,
responseEnd, event, which, button, srcElement, type, target,
parentNode, tagName, hostname, className,
userAgent, cookieEnabled, platform, mimeTypes, enabledPlugin, javaEnabled,
XMLHttpRequest, ActiveXObject, open, setRequestHeader, onreadystatechange, send, readyState, status,
getTime, getTimeAlias, setTime, toGMTString, getHours, getMinutes, getSeconds,
toLowerCase, toUpperCase, charAt, indexOf, lastIndexOf, split, slice,
onload, src,
round, random,
exec,
res, width, height, devicePixelRatio,
pdf, qt, realp, wma, dir, fla, java, gears, ag,
hook, getHook, getVisitorId, getVisitorInfo, setUserId, getUserId, setSiteId, getSiteId, setTrackerUrl, getTrackerUrl, appendToTrackingUrl, getRequest, addPlugin,
getAttributionInfo, getAttributionCampaignName, getAttributionCampaignKeyword,
getAttributionReferrerTimestamp, getAttributionReferrerUrl,
setCustomData, getCustomData,
setCustomRequestProcessing,
setCustomVariable, getCustomVariable, deleteCustomVariable, storeCustomVariablesInCookie,
setDownloadExtensions, addDownloadExtensions, removeDownloadExtensions,
setDomains, setIgnoreClasses, setRequestMethod, setRequestContentType,
setReferrerUrl, setCustomUrl, setAPIUrl, setDocumentTitle,
setDownloadClasses, setLinkClasses,
setCampaignNameKey, setCampaignKeywordKey,
discardHashTag,
setCookieNamePrefix, setCookieDomain, setCookiePath, setVisitorIdCookie,
setVisitorCookieTimeout, setSessionCookieTimeout, setReferralCookieTimeout,
setConversionAttributionFirstReferrer,
disablePerformanceTracking, setGenerationTimeMs,
doNotTrack, setDoNotTrack, msDoNotTrack, getValuesFromVisitorIdCookie,
addListener, enableLinkTracking, enableJSErrorTracking, setLinkTrackingTimer,
setHeartBeatTimer, killFrame, redirectFile, setCountPreRendered,
trackGoal, trackLink, trackPageView, trackSiteSearch, trackEvent,
setEcommerceView, addEcommerceItem, trackEcommerceOrder, trackEcommerceCartUpdate,
deleteCookie, deleteCookies, offsetTop, offsetLeft, offsetHeight, offsetWidth, nodeType, defaultView,
innerHTML, scrollLeft, scrollTop, currentStyle, getComputedStyle, querySelectorAll, splice,
getAttribute, hasAttribute, attributes, nodeName, findContentNodes, findContentNodes, findContentNodesWithinNode,
findPieceNode, findTargetNodeNoDefault, findTargetNode, findContentPiece, children, hasNodeCssClass,
getAttributeValueFromNode, hasNodeAttributeWithValue, hasNodeAttribute, findNodesByTagName, findMultiple,
makeNodesUnique, concat, find, htmlCollectionToArray, offsetParent, value, nodeValue, findNodesHavingAttribute,
findFirstNodeHavingAttribute, findFirstNodeHavingAttributeWithValue, getElementsByClassName,
findNodesHavingCssClass, findFirstNodeHavingClass, isLinkElement, findParentContentNode, removeDomainIfIsInLink,
findContentName, findMediaUrlInNode, toAbsoluteUrl, findContentTarget, getLocation, origin, host, isSameDomain,
search, trim, getBoundingClientRect, bottom, right, left, innerWidth, innerHeight, clientWidth, clientHeight,
isOrWasNodeInViewport, isNodeVisible, buildInteractionRequestParams, buildImpressionRequestParams,
shouldIgnoreInteraction, setHrefAttribute, setAttribute, buildContentBlock, collectContent, setLocation,
CONTENT_ATTR, CONTENT_CLASS, CONTENT_NAME_ATTR, CONTENT_PIECE_ATTR, CONTENT_PIECE_CLASS,
CONTENT_TARGET_ATTR, CONTENT_TARGET_CLASS, CONTENT_IGNOREINTERACTION_ATTR, CONTENT_IGNOREINTERACTION_CLASS,
trackCallbackOnLoad, trackCallbackOnReady, buildContentImpressionsRequests, wasContentImpressionAlreadyTracked,
getQuery, getContent, getContentImpressionsRequestsFromNodes, buildContentInteractionTrackingRedirectUrl,
buildContentInteractionRequestNode, buildContentInteractionRequest, buildContentImpressionRequest,
appendContentInteractionToRequestIfPossible, setupInteractionsTracking, trackContentImpressionClickInteraction,
internalIsNodeVisible, clearTrackedContentImpressions, getTrackerUrl, trackAllContentImpressions,
getTrackedContentImpressions, getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet,
contentInteractionTrackingSetupDone, contains, match, pathname, piece, trackContentInteractionNode,
trackContentInteractionNode, trackContentImpressionsWithinNode, trackContentImpression,
enableTrackOnlyVisibleContent, trackContentInteraction, clearEnableTrackOnlyVisibleContent,
trackVisibleContentImpressions, isTrackOnlyVisibleContentEnabled, port, isUrlToCurrentDomain,
isNodeAuthorizedToTriggerInteraction, replaceHrefIfInternalLink, getConfigDownloadExtensions, disableLinkTracking,
substr, setAnyAttribute, wasContentTargetAttrReplaced, max, abs, childNodes, compareDocumentPosition, body,
getConfigVisitorCookieTimeout, getRemainingVisitorCookieTimeout,
newVisitor, uuid, createTs, visitCount, currentVisitTs, lastVisitTs, lastEcommerceOrderTs
*/
/*global _paq:true */
/*members push */
/*global Piwik:true */
/*members addPlugin, getTracker, getAsyncTracker */
/*global Piwik_Overlay_Client */
/*global AnalyticsTracker:true */
/*members initialize */
/*global define */
/*members amd */
/*global console:true */
/*members error */
// asynchronous tracker (or proxy)
if (typeof _paq !== 'object') {
_paq = [];
}
// Piwik singleton and namespace
if (typeof Piwik !== 'object') {
Piwik = (function () {
'use strict';
/************************************************************
* Private data
************************************************************/
var expireDateTime,
/* plugins */
plugins = {},
/* alias frequently used globals for added minification */
documentAlias = document,
navigatorAlias = navigator,
screenAlias = screen,
windowAlias = window,
/* performance timing */
performanceAlias = windowAlias.performance || windowAlias.mozPerformance || windowAlias.msPerformance || windowAlias.webkitPerformance,
/* DOM Ready */
hasLoaded = false,
registeredOnLoadHandlers = [],
/* encode */
encodeWrapper = windowAlias.encodeURIComponent,
/* decode */
decodeWrapper = windowAlias.decodeURIComponent,
/* urldecode */
urldecode = unescape,
/* asynchronous tracker */
asyncTracker,
/* iterator */
iterator,
/* local Piwik */
Piwik;
/************************************************************
* Private methods
************************************************************/
/*
* Is property defined?
*/
function isDefined(property) {
// workaround https://github.com/douglascrockford/JSLint/commit/24f63ada2f9d7ad65afc90e6d949f631935c2480
var propertyType = typeof property;
return propertyType !== 'undefined';
}
/*
* Is property a function?
*/
function isFunction(property) {
return typeof property === 'function';
}
/*
* Is property an object?
*
* @return bool Returns true if property is null, an Object, or subclass of Object (i.e., an instanceof String, Date, etc.)
*/
function isObject(property) {
return typeof property === 'object';
}
/*
* Is property a string?
*/
function isString(property) {
return typeof property === 'string' || property instanceof String;
}
/*
* apply wrapper
*
* @param array parameterArray An array comprising either:
* [ 'methodName', optional_parameters ]
* or:
* [ functionObject, optional_parameters ]
*/
function apply() {
var i, f, parameterArray;
for (i = 0; i < arguments.length; i += 1) {
parameterArray = arguments[i];
f = parameterArray.shift();
if (isString(f)) {
asyncTracker[f].apply(asyncTracker, parameterArray);
} else {
f.apply(asyncTracker, parameterArray);
}
}
}
/*
* Cross-browser helper function to add event handler
*/
function addEventListener(element, eventType, eventHandler, useCapture) {
if (element.addEventListener) {
element.addEventListener(eventType, eventHandler, useCapture);
return true;
}
if (element.attachEvent) {
return element.attachEvent('on' + eventType, eventHandler);
}
element['on' + eventType] = eventHandler;
}
/*
* Call plugin hook methods
*/
function executePluginMethod(methodName, callback) {
var result = '',
i,
pluginMethod;
for (i in plugins) {
if (Object.prototype.hasOwnProperty.call(plugins, i)) {
pluginMethod = plugins[i][methodName];
if (isFunction(pluginMethod)) {
result += pluginMethod(callback);
}
}
}
return result;
}
/*
* Handle beforeunload event
*
* Subject to Safari's "Runaway JavaScript Timer" and
* Chrome V8 extension that terminates JS that exhibits
* "slow unload", i.e., calling getTime() > 1000 times
*/
function beforeUnloadHandler() {
var now;
executePluginMethod('unload');
/*
* Delay/pause (blocks UI)
*/
if (expireDateTime) {
// the things we do for backwards compatibility...
// in ECMA-262 5th ed., we could simply use:
// while (Date.now() < expireDateTime) { }
do {
now = new Date();
} while (now.getTimeAlias() < expireDateTime);
}
}
/*
* Handler for onload event
*/
function loadHandler() {
var i;
if (!hasLoaded) {
hasLoaded = true;
executePluginMethod('load');
for (i = 0; i < registeredOnLoadHandlers.length; i++) {
registeredOnLoadHandlers[i]();
}
}
return true;
}
/*
* Add onload or DOM ready handler
*/
function addReadyListener() {
var _timer;
if (documentAlias.addEventListener) {
addEventListener(documentAlias, 'DOMContentLoaded', function ready() {
documentAlias.removeEventListener('DOMContentLoaded', ready, false);
loadHandler();
});
} else if (documentAlias.attachEvent) {
documentAlias.attachEvent('onreadystatechange', function ready() {
if (documentAlias.readyState === 'complete') {
documentAlias.detachEvent('onreadystatechange', ready);
loadHandler();
}
});
if (documentAlias.documentElement.doScroll && windowAlias === windowAlias.top) {
(function ready() {
if (!hasLoaded) {
try {
documentAlias.documentElement.doScroll('left');
} catch (error) {
setTimeout(ready, 0);
return;
}
loadHandler();
}
}());
}
}
// sniff for older WebKit versions
if ((new RegExp('WebKit')).test(navigatorAlias.userAgent)) {
_timer = setInterval(function () {
if (hasLoaded || /loaded|complete/.test(documentAlias.readyState)) {
clearInterval(_timer);
loadHandler();
}
}, 10);
}
// fallback
addEventListener(windowAlias, 'load', loadHandler, false);
}
/*
* Load JavaScript file (asynchronously)
*/
function loadScript(src, onLoad) {
var script = documentAlias.createElement('script');
script.type = 'text/javascript';
script.src = src;
if (script.readyState) {
script.onreadystatechange = function () {
var state = this.readyState;
if (state === 'loaded' || state === 'complete') {
script.onreadystatechange = null;
onLoad();
}
};
} else {
script.onload = onLoad;
}
documentAlias.getElementsByTagName('head')[0].appendChild(script);
}
/*
* Get page referrer
*/
function getReferrer() {
var referrer = '';
try {
referrer = windowAlias.top.document.referrer;
} catch (e) {
if (windowAlias.parent) {
try {
referrer = windowAlias.parent.document.referrer;
} catch (e2) {
referrer = '';
}
}
}
if (referrer === '') {
referrer = documentAlias.referrer;
}
return referrer;
}
/*
* Extract scheme/protocol from URL
*/
function getProtocolScheme(url) {
var e = new RegExp('^([a-z]+):'),
matches = e.exec(url);
return matches ? matches[1] : null;
}
/*
* Extract hostname from URL
*/
function getHostName(url) {
// scheme : // [username [: password] @] hostame [: port] [/ [path] [? query] [# fragment]]
var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'),
matches = e.exec(url);
return matches ? matches[1] : url;
}
/*
* Extract parameter from URL
*/
function getParameter(url, name) {
var regexSearch = "[\\?&#]" + name + "=([^&#]*)";
var regex = new RegExp(regexSearch);
var results = regex.exec(url);
return results ? decodeWrapper(results[1]) : '';
}
/*
* UTF-8 encoding
*/
function utf8_encode(argString) {
return urldecode(encodeWrapper(argString));
}
/************************************************************
* sha1
* - based on sha1 from http://phpjs.org/functions/sha1:512 (MIT / GPL v2)
************************************************************/
function sha1(str) {
// + original by: Webtoolkit.info (http://www.webtoolkit.info/)
// + namespaced by: Michael White (http://getsprink.com)
// + input by: Brett Zamir (http://brett-zamir.me)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + jslinted by: Anthon Pang (http://piwik.org)
var
rotate_left = function (n, s) {
return (n << s) | (n >>> (32 - s));
},
cvt_hex = function (val) {
var strout = '',
i,
v;
for (i = 7; i >= 0; i--) {
v = (val >>> (i * 4)) & 0x0f;
strout += v.toString(16);
}
return strout;
},
blockstart,
i,
j,
W = [],
H0 = 0x67452301,
H1 = 0xEFCDAB89,
H2 = 0x98BADCFE,
H3 = 0x10325476,
H4 = 0xC3D2E1F0,
A,
B,
C,
D,
E,
temp,
str_len,
word_array = [];
str = utf8_encode(str);
str_len = str.length;
for (i = 0; i < str_len - 3; i += 4) {
j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 |
str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
word_array.push(j);
}
switch (str_len & 3) {
case 0:
i = 0x080000000;
break;
case 1:
i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
break;
case 2:
i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
break;
case 3:
i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << 8 | 0x80;
break;
}
word_array.push(i);
while ((word_array.length & 15) !== 14) {
word_array.push(0);
}
word_array.push(str_len >>> 29);
word_array.push((str_len << 3) & 0x0ffffffff);
for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
for (i = 0; i < 16; i++) {
W[i] = word_array[blockstart + i];
}
for (i = 16; i <= 79; i++) {
W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
}
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for (i = 0; i <= 19; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 20; i <= 39; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 40; i <= 59; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 60; i <= 79; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
}
/************************************************************
* end sha1
************************************************************/
/*
* Fix-up URL when page rendered from search engine cache or translated page
*/
function urlFixup(hostName, href, referrer) {
if (hostName === 'translate.googleusercontent.com') { // Google
if (referrer === '') {
referrer = href;
}
href = getParameter(href, 'u');
hostName = getHostName(href);
} else if (hostName === 'cc.bingj.com' || // Bing
hostName === 'webcache.googleusercontent.com' || // Google
hostName.slice(0, 5) === '74.6.') { // Yahoo (via Inktomi 74.6.0.0/16)
href = documentAlias.links[0].href;
hostName = getHostName(href);
}
return [hostName, href, referrer];
}
/*
* Fix-up domain
*/
function domainFixup(domain) {
var dl = domain.length;
// remove trailing '.'
if (domain.charAt(--dl) === '.') {
domain = domain.slice(0, dl);
}
// remove leading '*'
if (domain.slice(0, 2) === '*.') {
domain = domain.slice(1);
}
return domain;
}
/*
* Title fixup
*/
function titleFixup(title) {
title = title && title.text ? title.text : title;
if (!isString(title)) {
var tmp = documentAlias.getElementsByTagName('title');
if (tmp && isDefined(tmp[0])) {
title = tmp[0].text;
}
}
return title;
}
function getChildrenFromNode(node)
{
if (!node) {
return [];
}
if (!isDefined(node.children) && isDefined(node.childNodes)) {
return node.children;
}
if (isDefined(node.children)) {
return node.children;
}
return [];
}
function containsNodeElement(node, containedNode)
{
if (!node || !containedNode) {
return false;
}
if (node.contains) {
return node.contains(containedNode);
}
if (node === containedNode) {
return true;
}
if (node.compareDocumentPosition) {
return !!(node.compareDocumentPosition(containedNode) & 16);
}
return false;
}
// Polyfill for IndexOf for IE6-IE8
function indexOfArray(theArray, searchElement)
{
if (theArray && theArray.indexOf) {
return theArray.indexOf(searchElement);
}
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (!isDefined(theArray) || theArray === null) {
return -1;
}
if (!theArray.length) {
return -1;
}
var len = theArray.length;
if (len === 0) {
return -1;
}
var k = 0;
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (theArray[k] === searchElement) {
return k;
}
k++;
}
return -1;
}
/************************************************************
* Element Visiblility
************************************************************/
/**
* Author: Jason Farrell
* Author URI: http://useallfive.com/
*
* Description: Checks if a DOM element is truly visible.
* Package URL: https://github.com/UseAllFive/true-visibility
* License: MIT (https://github.com/UseAllFive/true-visibility/blob/master/LICENSE.txt)
*/
function isVisible(node) {
if (!node) {
return false;
}
//-- Cross browser method to get style properties:
function _getStyle(el, property) {
if (windowAlias.getComputedStyle) {
return documentAlias.defaultView.getComputedStyle(el,null)[property];
}
if (el.currentStyle) {
return el.currentStyle[property];
}
}
function _elementInDocument(element) {
element = element.parentNode;
while (element) {
if (element === documentAlias) {
return true;
}
element = element.parentNode;
}
return false;
}
/**
* Checks if a DOM element is visible. Takes into
* consideration its parents and overflow.
*
* @param (el) the DOM element to check if is visible
*
* These params are optional that are sent in recursively,
* you typically won't use these:
*
* @param (t) Top corner position number
* @param (r) Right corner position number
* @param (b) Bottom corner position number
* @param (l) Left corner position number
* @param (w) Element width number
* @param (h) Element height number
*/
function _isVisible(el, t, r, b, l, w, h) {
var p = el.parentNode,
VISIBLE_PADDING = 1; // has to be visible at least one px of the element
if (!_elementInDocument(el)) {
return false;
}
//-- Return true for document node
if (9 === p.nodeType) {
return true;
}
//-- Return false if our element is invisible
if (
'0' === _getStyle(el, 'opacity') ||
'none' === _getStyle(el, 'display') ||
'hidden' === _getStyle(el, 'visibility')
) {
return false;
}
if (!isDefined(t) ||
!isDefined(r) ||
!isDefined(b) ||
!isDefined(l) ||
!isDefined(w) ||
!isDefined(h)) {
t = el.offsetTop;
l = el.offsetLeft;
b = t + el.offsetHeight;
r = l + el.offsetWidth;
w = el.offsetWidth;
h = el.offsetHeight;
}
if (node === el && (0 === h || 0 === w) && 'hidden' === _getStyle(el, 'overflow')) {
return false;
}
//-- If we have a parent, let's continue:
if (p) {
//-- Check if the parent can hide its children.
if (('hidden' === _getStyle(p, 'overflow') || 'scroll' === _getStyle(p, 'overflow'))) {
//-- Only check if the offset is different for the parent
if (
//-- If the target element is to the right of the parent elm
l + VISIBLE_PADDING > p.offsetWidth + p.scrollLeft ||
//-- If the target element is to the left of the parent elm
l + w - VISIBLE_PADDING < p.scrollLeft ||
//-- If the target element is under the parent elm
t + VISIBLE_PADDING > p.offsetHeight + p.scrollTop ||
//-- If the target element is above the parent elm
t + h - VISIBLE_PADDING < p.scrollTop
) {
//-- Our target element is out of bounds:
return false;
}
}
//-- Add the offset parent's left/top coords to our element's offset:
if (el.offsetParent === p) {
l += p.offsetLeft;
t += p.offsetTop;
}
//-- Let's recursively check upwards:
return _isVisible(p, t, r, b, l, w, h);
}
return true;
}
return _isVisible(node);
}
/************************************************************
* Query
************************************************************/
var query = {
htmlCollectionToArray: function (foundNodes)
{
var nodes = [], index;
if (!foundNodes || !foundNodes.length) {
return nodes;
}
for (index = 0; index < foundNodes.length; index++) {
nodes.push(foundNodes[index]);
}
return nodes;
},
find: function (selector)
{
// we use querySelectorAll only on document, not on nodes because of its unexpected behavior. See for
// instance http://stackoverflow.com/questions/11503534/jquery-vs-document-queryselectorall and
// http://jsfiddle.net/QdMc5/ and http://ejohn.org/blog/thoughts-on-queryselectorall
if (!document.querySelectorAll || !selector) {
return []; // we do not support all browsers
}
var foundNodes = document.querySelectorAll(selector);
return this.htmlCollectionToArray(foundNodes);
},
findMultiple: function (selectors)
{
if (!selectors || !selectors.length) {
return [];
}
var index, foundNodes;
var nodes = [];
for (index = 0; index < selectors.length; index++) {
foundNodes = this.find(selectors[index]);
nodes = nodes.concat(foundNodes);
}
nodes = this.makeNodesUnique(nodes);
return nodes;
},
findNodesByTagName: function (node, tagName)
{
if (!node || !tagName || !node.getElementsByTagName) {
return [];
}
var foundNodes = node.getElementsByTagName(tagName);
return this.htmlCollectionToArray(foundNodes);
},
makeNodesUnique: function (nodes)
{
var copy = [].concat(nodes);
nodes.sort(function(n1, n2){
if (n1 === n2) {
return 0;
}
var index1 = indexOfArray(copy, n1);
var index2 = indexOfArray(copy, n2);
if (index1 === index2) {
return 0;
}
return index1 > index2 ? -1 : 1;
});
if (nodes.length <= 1) {
return nodes;
}
var index = 0;
var numDuplicates = 0;
var duplicates = [];
var node;
node = nodes[index++];
while (node) {
if (node === nodes[index]) {
numDuplicates = duplicates.push(index);
}
node = nodes[index++] || null;
}
while (numDuplicates--) {
nodes.splice(duplicates[numDuplicates], 1);
}
return nodes;
},
getAttributeValueFromNode: function (node, attributeName)
{
if (!this.hasNodeAttribute(node, attributeName)) {
return;
}
if (node && node.getAttribute) {
return node.getAttribute(attributeName);
}
if (!node || !node.attributes) {
return;
}
var typeOfAttr = (typeof node.attributes[attributeName]);
if ('undefined' === typeOfAttr) {
return;
}
if (node.attributes[attributeName].value) {
return node.attributes[attributeName].value; // nodeValue is deprecated ie Chrome
}
if (node.attributes[attributeName].nodeValue) {
return node.attributes[attributeName].nodeValue;
}
var index;
var attrs = node.attributes;
if (!attrs) {
return;
}
for (index = 0; index < attrs.length; index++) {
if (attrs[index].nodeName === attributeName) {
return attrs[index].nodeValue;
}
}
return null;
},
hasNodeAttributeWithValue: function (node, attributeName)
{
var value = this.getAttributeValueFromNode(node, attributeName);
return !!value;
},
hasNodeAttribute: function (node, attributeName)
{
if (node && node.hasAttribute) {
return node.hasAttribute(attributeName);
}
if (node && node.attributes) {
var typeOfAttr = (typeof node.attributes[attributeName]);
return 'undefined' !== typeOfAttr;
}
return false;
},
hasNodeCssClass: function (node, className)
{
if (node && className && node.className) {
var classes = node.className.split(' ');
if (-1 !== indexOfArray(classes, className)) {
return true;
}
}
return false;
},
findNodesHavingAttribute: function (nodeToSearch, attributeName, nodes)
{
if (!nodes) {
nodes = [];
}
if (!nodeToSearch || !attributeName) {
return nodes;
}
var children = getChildrenFromNode(nodeToSearch);
if (!children || !children.length) {
return nodes;
}
var index, child;
for (index = 0; index < children.length; index++) {
child = children[index];
if (this.hasNodeAttribute(child, attributeName)) {
nodes.push(child);
}
nodes = this.findNodesHavingAttribute(child, attributeName, nodes);
}
return nodes;
},
findFirstNodeHavingAttribute: function (node, attributeName)
{
if (!node || !attributeName) {
return;
}
if (this.hasNodeAttribute(node, attributeName)) {
return node;
}
var nodes = this.findNodesHavingAttribute(node, attributeName);
if (nodes && nodes.length) {
return nodes[0];
}
},
findFirstNodeHavingAttributeWithValue: function (node, attributeName)
{
if (!node || !attributeName) {
return;
}
if (this.hasNodeAttributeWithValue(node, attributeName)) {
return node;
}
var nodes = this.findNodesHavingAttribute(node, attributeName);
if (!nodes || !nodes.length) {
return;
}
var index;
for (index = 0; index < nodes.length; index++) {
if (this.getAttributeValueFromNode(nodes[index], attributeName)) {
return nodes[index];
}
}
},
findNodesHavingCssClass: function (nodeToSearch, className, nodes)
{
if (!nodes) {
nodes = [];
}
if (!nodeToSearch || !className) {
return nodes;
}
if (nodeToSearch.getElementsByClassName) {
var foundNodes = nodeToSearch.getElementsByClassName(className);
return this.htmlCollectionToArray(foundNodes);
}
var children = getChildrenFromNode(nodeToSearch);
if (!children || !children.length) {
return [];
}
var index, child;
for (index = 0; index < children.length; index++) {
child = children[index];
if (this.hasNodeCssClass(child, className)) {
nodes.push(child);
}
nodes = this.findNodesHavingCssClass(child, className, nodes);
}
return nodes;
},
findFirstNodeHavingClass: function (node, className)
{
if (!node || !className) {
return;
}
if (this.hasNodeCssClass(node, className)) {
return node;
}
var nodes = this.findNodesHavingCssClass(node, className);
if (nodes && nodes.length) {
return nodes[0];
}
},
isLinkElement: function (node)
{
if (!node) {
return false;
}
var elementName = String(node.nodeName).toLowerCase();
var linkElementNames = ['a', 'area'];
var pos = indexOfArray(linkElementNames, elementName);
return pos !== -1;
},
setAnyAttribute: function (node, attrName, attrValue)
{
if (!node || !attrName) {
return;
}
if (node.setAttribute) {
node.setAttribute(attrName, attrValue);
} else {
node[attrName] = attrValue;
}
}
};
/************************************************************
* Content Tracking
************************************************************/
var content = {
CONTENT_ATTR: 'data-track-content',
CONTENT_CLASS: 'piwikTrackContent',
CONTENT_NAME_ATTR: 'data-content-name',
CONTENT_PIECE_ATTR: 'data-content-piece',
CONTENT_PIECE_CLASS: 'piwikContentPiece',
CONTENT_TARGET_ATTR: 'data-content-target',
CONTENT_TARGET_CLASS: 'piwikContentTarget',
CONTENT_IGNOREINTERACTION_ATTR: 'data-content-ignoreinteraction',
CONTENT_IGNOREINTERACTION_CLASS: 'piwikContentIgnoreInteraction',
location: undefined,
findContentNodes: function ()
{
var cssSelector = '.' + this.CONTENT_CLASS;
var attrSelector = '[' + this.CONTENT_ATTR + ']';
var contentNodes = query.findMultiple([cssSelector, attrSelector]);
return contentNodes;
},
findContentNodesWithinNode: function (node)
{
if (!node) {
return [];
}
// NOTE: we do not use query.findMultiple here as querySelectorAll would most likely not deliver the result we want
var nodes1 = query.findNodesHavingCssClass(node, this.CONTENT_CLASS);
var nodes2 = query.findNodesHavingAttribute(node, this.CONTENT_ATTR);
if (nodes2 && nodes2.length) {
var index;
for (index = 0; index < nodes2.length; index++) {
nodes1.push(nodes2[index]);
}
}
if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) {
nodes1.push(node);
} else if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) {
nodes1.push(node);
}
nodes1 = query.makeNodesUnique(nodes1);
return nodes1;
},
findParentContentNode: function (anyNode)
{
if (!anyNode) {
return;
}
var node = anyNode;
var counter = 0;
while (node && node !== documentAlias && node.parentNode) {
if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) {
return node;
}
if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) {
return node;
}
node = node.parentNode;
if (counter > 1000) {
break; // prevent loop, should not happen anyway but better we do this
}
counter++;
}
},
findPieceNode: function (node)
{
var contentPiece;
contentPiece = query.findFirstNodeHavingAttribute(node, this.CONTENT_PIECE_ATTR);
if (!contentPiece) {
contentPiece = query.findFirstNodeHavingClass(node, this.CONTENT_PIECE_CLASS);
}
if (contentPiece) {
return contentPiece;
}
return node;
},
findTargetNodeNoDefault: function (node)
{
if (!node) {
return;
}
var target = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_TARGET_ATTR);
if (target) {
return target;
}
target = query.findFirstNodeHavingAttribute(node, this.CONTENT_TARGET_ATTR);
if (target) {
return target;
}
target = query.findFirstNodeHavingClass(node, this.CONTENT_TARGET_CLASS);
if (target) {
return target;
}
},
findTargetNode: function (node)
{
var target = this.findTargetNodeNoDefault(node);
if (target) {
return target;
}
return node;
},
findContentName: function (node)
{
if (!node) {
return;
}
var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_NAME_ATTR);
if (nameNode) {
return query.getAttributeValueFromNode(nameNode, this.CONTENT_NAME_ATTR);
}
var contentPiece = this.findContentPiece(node);
if (contentPiece) {
return this.removeDomainIfIsInLink(contentPiece);
}
if (query.hasNodeAttributeWithValue(node, 'title')) {
return query.getAttributeValueFromNode(node, 'title');
}
var clickUrlNode = this.findPieceNode(node);
if (query.hasNodeAttributeWithValue(clickUrlNode, 'title')) {
return query.getAttributeValueFromNode(clickUrlNode, 'title');
}
var targetNode = this.findTargetNode(node);
if (query.hasNodeAttributeWithValue(targetNode, 'title')) {
return query.getAttributeValueFromNode(targetNode, 'title');
}
},
findContentPiece: function (node)
{
if (!node) {
return;
}
var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_PIECE_ATTR);
if (nameNode) {
return query.getAttributeValueFromNode(nameNode, this.CONTENT_PIECE_ATTR);
}
var contentNode = this.findPieceNode(node);
var media = this.findMediaUrlInNode(contentNode);
if (media) {
return this.toAbsoluteUrl(media);
}
},
findContentTarget: function (node)
{
if (!node) {
return;
}
var targetNode = this.findTargetNode(node);
if (query.hasNodeAttributeWithValue(targetNode, this.CONTENT_TARGET_ATTR)) {
return query.getAttributeValueFromNode(targetNode, this.CONTENT_TARGET_ATTR);
}
var href;
if (query.hasNodeAttributeWithValue(targetNode, 'href')) {
href = query.getAttributeValueFromNode(targetNode, 'href');
return this.toAbsoluteUrl(href);
}
var contentNode = this.findPieceNode(node);
if (query.hasNodeAttributeWithValue(contentNode, 'href')) {
href = query.getAttributeValueFromNode(contentNode, 'href');
return this.toAbsoluteUrl(href);
}
},
isSameDomain: function (url)
{
if (!url || !url.indexOf) {
return false;
}
if (0 === url.indexOf(this.getLocation().origin)) {
return true;
}
var posHost = url.indexOf(this.getLocation().host);
if (8 >= posHost && 0 <= posHost) {
return true;
}
return false;
},
removeDomainIfIsInLink: function (text)
{
// we will only remove if domain === location.origin meaning is not an outlink
var regexContainsProtocol = '^https?:\/\/[^\/]+';
var regexReplaceDomain = '^.*\/\/[^\/]+';
if (text &&
text.search &&
-1 !== text.search(new RegExp(regexContainsProtocol))
&& this.isSameDomain(text)) {
text = text.replace(new RegExp(regexReplaceDomain), '');
if (!text) {
text = '/';
}
}
return text;
},
findMediaUrlInNode: function (node)
{
if (!node) {
return;
}
var mediaElements = ['img', 'embed', 'video', 'audio'];
var elementName = node.nodeName.toLowerCase();
if (-1 !== indexOfArray(mediaElements, elementName) &&
query.findFirstNodeHavingAttributeWithValue(node, 'src')) {
var sourceNode = query.findFirstNodeHavingAttributeWithValue(node, 'src');
return query.getAttributeValueFromNode(sourceNode, 'src');
}
if (elementName === 'object' &&
query.hasNodeAttributeWithValue(node, 'data')) {
return query.getAttributeValueFromNode(node, 'data');
}
if (elementName === 'object') {
var params = query.findNodesByTagName(node, 'param');
if (params && params.length) {
var index;
for (index = 0; index < params.length; index++) {
if ('movie' === query.getAttributeValueFromNode(params[index], 'name') &&
query.hasNodeAttributeWithValue(params[index], 'value')) {
return query.getAttributeValueFromNode(params[index], 'value');
}
}
}
var embed = query.findNodesByTagName(node, 'embed');
if (embed && embed.length) {
return this.findMediaUrlInNode(embed[0]);
}
}
},
trim: function (text)
{
if (text && String(text) === text) {
return text.replace(/^\s+|\s+$/g, '');
}
return text;
},
isOrWasNodeInViewport: function (node)
{
if (!node || !node.getBoundingClientRect || node.nodeType !== 1) {
return true;
}
var rect = node.getBoundingClientRect();
var html = documentAlias.documentElement || {};
var wasVisible = rect.top < 0;
if (wasVisible && node.offsetTop) {
wasVisible = (node.offsetTop + rect.height) > 0;
}
var docWidth = html.clientWidth; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar
if (windowAlias.innerWidth && docWidth > windowAlias.innerWidth) {
docWidth = windowAlias.innerWidth; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar
}
var docHeight = html.clientHeight; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar
if (windowAlias.innerHeight && docHeight > windowAlias.innerHeight) {
docHeight = windowAlias.innerHeight; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar
}
return (
(rect.bottom > 0 || wasVisible) &&
rect.right > 0 &&
rect.left < docWidth &&
((rect.top < docHeight) || wasVisible) // rect.top < 0 we assume user has seen all the ones that are above the current viewport
);
},
isNodeVisible: function (node)
{
var isItVisible = isVisible(node);
var isInViewport = this.isOrWasNodeInViewport(node);
return isItVisible && isInViewport;
},
buildInteractionRequestParams: function (interaction, name, piece, target)
{
var params = '';
if (interaction) {
params += 'c_i='+ encodeWrapper(interaction);
}
if (name) {
if (params) {
params += '&';
}
params += 'c_n='+ encodeWrapper(name);
}
if (piece) {
if (params) {
params += '&';
}
params += 'c_p='+ encodeWrapper(piece);
}
if (target) {
if (params) {
params += '&';
}
params += 'c_t='+ encodeWrapper(target);
}
return params;
},
buildImpressionRequestParams: function (name, piece, target)
{
var params = 'c_n=' + encodeWrapper(name) +
'&c_p=' + encodeWrapper(piece);
if (target) {
params += '&c_t=' + encodeWrapper(target);
}
return params;
},
buildContentBlock: function (node)
{
if (!node) {
return;
}
var name = this.findContentName(node);
var piece = this.findContentPiece(node);
var target = this.findContentTarget(node);
name = this.trim(name);
piece = this.trim(piece);
target = this.trim(target);
return {
name: name || 'Unknown',
piece: piece || 'Unknown',
target: target || ''
};
},
collectContent: function (contentNodes)
{
if (!contentNodes || !contentNodes.length) {
return [];
}
var contents = [];
var index, contentBlock;
for (index = 0; index < contentNodes.length; index++) {
contentBlock = this.buildContentBlock(contentNodes[index]);
if (isDefined(contentBlock)) {
contents.push(contentBlock);
}
}
return contents;
},
setLocation: function (location)
{
this.location = location;
},
getLocation: function ()
{
var locationAlias = this.location || windowAlias.location;
if (!locationAlias.origin) {
locationAlias.origin = locationAlias.protocol + "//" + locationAlias.hostname + (locationAlias.port ? ':' + locationAlias.port: '');
}
return locationAlias;
},
toAbsoluteUrl: function (url)
{
if ((!url || String(url) !== url) && url !== '') {
// we only handle strings
return url;
}
if ('' === url) {
return this.getLocation().href;
}
// Eg //example.com/test.jpg
if (url.search(/^\/\//) !== -1) {
return this.getLocation().protocol + url;
}
// Eg http://example.com/test.jpg
if (url.search(/:\/\//) !== -1) {
return url;
}
// Eg #test.jpg
if (0 === url.indexOf('#')) {
return this.getLocation().origin + this.getLocation().pathname + url;
}
// Eg ?x=5
if (0 === url.indexOf('?')) {
return this.getLocation().origin + this.getLocation().pathname + url;
}
// Eg mailto:x@y.z tel:012345, ... market:... sms:..., javasript:... ecmascript: ... and many more
if (0 === url.search('^[a-zA-Z]{2,11}:')) {
return url;
}
// Eg /test.jpg
if (url.search(/^\//) !== -1) {
return this.getLocation().origin + url;
}
// Eg test.jpg
var regexMatchDir = '(.*\/)';
var base = this.getLocation().origin + this.getLocation().pathname.match(new RegExp(regexMatchDir))[0];
return base + url;
},
isUrlToCurrentDomain: function (url) {
var absoluteUrl = this.toAbsoluteUrl(url);
if (!absoluteUrl) {
return false;
}
var origin = this.getLocation().origin;
if (origin === absoluteUrl) {
return true;
}
if (0 === String(absoluteUrl).indexOf(origin)) {
if (':' === String(absoluteUrl).substr(origin.length, 1)) {
return false; // url has port whereas origin has not => different URL
}
return true;
}
return false;
},
setHrefAttribute: function (node, url)
{
if (!node || !url) {
return;
}
query.setAnyAttribute(node, 'href', url);
},
shouldIgnoreInteraction: function (targetNode)
{
var hasAttr = query.hasNodeAttribute(targetNode, this.CONTENT_IGNOREINTERACTION_ATTR);
var hasClass = query.hasNodeCssClass(targetNode, this.CONTENT_IGNOREINTERACTION_CLASS);
return hasAttr || hasClass;
}
};
/************************************************************
* Page Overlay
************************************************************/
function getPiwikUrlForOverlay(trackerUrl, apiUrl) {
if (apiUrl) {
return apiUrl;
}
if (trackerUrl.slice(-9) === 'piwik.php') {
trackerUrl = trackerUrl.slice(0, trackerUrl.length - 9);
}
return trackerUrl;
}
/*
* Check whether this is a page overlay session
*
* @return boolean
*
* {@internal side-effect: modifies window.name }}
*/
function isOverlaySession(configTrackerSiteId) {
var windowName = 'Piwik_Overlay';
// check whether we were redirected from the piwik overlay plugin
var referrerRegExp = new RegExp('index\\.php\\?module=Overlay&action=startOverlaySession'
+ '&idSite=([0-9]+)&period=([^&]+)&date=([^&]+)$');
var match = referrerRegExp.exec(documentAlias.referrer);
if (match) {
// check idsite
var idsite = match[1];
if (idsite !== String(configTrackerSiteId)) {
return false;
}
// store overlay session info in window name
var period = match[2],
date = match[3];
windowAlias.name = windowName + '###' + period + '###' + date;
}
// retrieve and check data from window name
var windowNameParts = windowAlias.name.split('###');
return windowNameParts.length === 3 && windowNameParts[0] === windowName;
}
/*
* Inject the script needed for page overlay
*/
function injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId) {
var windowNameParts = windowAlias.name.split('###'),
period = windowNameParts[1],
date = windowNameParts[2],
piwikUrl = getPiwikUrlForOverlay(configTrackerUrl, configApiUrl);
loadScript(
piwikUrl + 'plugins/Overlay/client/client.js?v=1',
function () {
Piwik_Overlay_Client.initialize(piwikUrl, configTrackerSiteId, period, date);
}
);
}
/************************************************************
* End Page Overlay
************************************************************/
/*
* Piwik Tracker class
*
* trackerUrl and trackerSiteId are optional arguments to the constructor
*
* See: Tracker.setTrackerUrl() and Tracker.setSiteId()
*/
function Tracker(trackerUrl, siteId) {
/************************************************************
* Private members
************************************************************/
var
/*<DEBUG>*/
/*
* registered test hooks
*/
registeredHooks = {},
/*</DEBUG>*/
// Current URL and Referrer URL
locationArray = urlFixup(documentAlias.domain, windowAlias.location.href, getReferrer()),
domainAlias = domainFixup(locationArray[0]),
locationHrefAlias = decodeWrapper(locationArray[1]),
configReferrerUrl = decodeWrapper(locationArray[2]),
enableJSErrorTracking = false,
defaultRequestMethod = 'GET',
// Request method (GET or POST)
configRequestMethod = defaultRequestMethod,
defaultRequestContentType = 'application/x-www-form-urlencoded; charset=UTF-8',
// Request Content-Type header value; applicable when POST request method is used for submitting tracking events
configRequestContentType = defaultRequestContentType,
// Tracker URL
configTrackerUrl = trackerUrl || '',
// API URL (only set if it differs from the Tracker URL)
configApiUrl = '',
// This string is appended to the Tracker URL Request (eg. to send data that is not handled by the existing setters/getters)
configAppendToTrackingUrl = '',
// Site ID
configTrackerSiteId = siteId || '',
// User ID
configUserId = '',
// Visitor UUID
visitorUUID = '',
// Document URL
configCustomUrl,
// Document title
configTitle = documentAlias.title,
// Extensions to be treated as download links
configDownloadExtensions = ['7z','aac','apk','arc','arj','asf','asx','avi','azw3','bin','csv','deb','dmg','doc','docx','epub','exe','flv','gif','gz','gzip','hqx','ibooks','jar','jpg','jpeg','js','mobi','mp2','mp3','mp4','mpg','mpeg','mov','movie','msi','msp','odb','odf','odg','ods','odt','ogg','ogv','pdf','phps','png','ppt','pptx','qt','qtm','ra','ram','rar','rpm','sea','sit','tar','tbz','tbz2','bz','bz2','tgz','torrent','txt','wav','wma','wmv','wpd','xls','xlsx','xml','z','zip'],
// Hosts or alias(es) to not treat as outlinks
configHostsAlias = [domainAlias],
// HTML anchor element classes to not track
configIgnoreClasses = [],
// HTML anchor element classes to treat as downloads
configDownloadClasses = [],
// HTML anchor element classes to treat at outlinks
configLinkClasses = [],
// Maximum delay to wait for web bug image to be fetched (in milliseconds)
configTrackerPause = 500,
// Minimum visit time after initial page view (in milliseconds)
configMinimumVisitTime,
// Recurring heart beat after initial ping (in milliseconds)
configHeartBeatTimer,
// Disallow hash tags in URL
configDiscardHashTag,
// Custom data
configCustomData,
// Campaign names
configCampaignNameParameters = [ 'pk_campaign', 'piwik_campaign', 'utm_campaign', 'utm_source', 'utm_medium' ],
// Campaign keywords
configCampaignKeywordParameters = [ 'pk_kwd', 'piwik_kwd', 'utm_term' ],
// First-party cookie name prefix
configCookieNamePrefix = '_pk_',
// First-party cookie domain
// User agent defaults to origin hostname
configCookieDomain,
// First-party cookie path
// Default is user agent defined.
configCookiePath,
// Cookies are disabled
configCookiesDisabled = false,
// Do Not Track
configDoNotTrack,
// Count sites which are pre-rendered
configCountPreRendered,
// Do we attribute the conversion to the first referrer or the most recent referrer?
configConversionAttributionFirstReferrer,
// Life of the visitor cookie (in milliseconds)
configVisitorCookieTimeout = 33955200000, // 13 months (365 days + 28days)
// Life of the session cookie (in milliseconds)
configSessionCookieTimeout = 1800000, // 30 minutes
// Life of the referral cookie (in milliseconds)
configReferralCookieTimeout = 15768000000, // 6 months
// Is performance tracking enabled
configPerformanceTrackingEnabled = true,
// Generation time set from the server
configPerformanceGenerationTime = 0,
// Whether Custom Variables scope "visit" should be stored in a cookie during the time of the visit
configStoreCustomVariablesInCookie = false,
// Custom Variables read from cookie, scope "visit"
customVariables = false,
configCustomRequestContentProcessing,
// Custom Variables, scope "page"
customVariablesPage = {},
// Custom Variables, scope "event"
customVariablesEvent = {},
// Custom Variables names and values are each truncated before being sent in the request or recorded in the cookie
customVariableMaximumLength = 200,
// Ecommerce items
ecommerceItems = {},
// Browser features via client-side data collection
browserFeatures = {},
// Keeps track of previously tracked content impressions
trackedContentImpressions = [],
isTrackOnlyVisibleContentEnabled = false,
// Guard to prevent empty visits see #6415. If there is a new visitor and the first 2 (or 3 or 4)
// tracking requests are at nearly same time (eg trackPageView and trackContentImpression) 2 or more
// visits will be created
timeNextTrackingRequestCanBeExecutedImmediately = false,
// Guard against installing the link tracker more than once per Tracker instance
linkTrackingInstalled = false,
linkTrackingEnabled = false,
// Guard against installing the activity tracker more than once per Tracker instance
activityTrackingInstalled = false,
// Last activity timestamp
lastActivityTime,
// Internal state of the pseudo click handler
lastButton,
lastTarget,
// Hash function
hash = sha1,
// Domain hash value
domainHash;
/*
* Set cookie value
*/
function setCookie(cookieName, value, msToExpire, path, domain, secure) {
if (configCookiesDisabled) {
return;
}
var expiryDate;
// relative time to expire in milliseconds
if (msToExpire) {
expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + msToExpire);
}
documentAlias.cookie = cookieName + '=' + encodeWrapper(value) +
(msToExpire ? ';expires=' + expiryDate.toGMTString() : '') +
';path=' + (path || '/') +
(domain ? ';domain=' + domain : '') +
(secure ? ';secure' : '');
}
/*
* Get cookie value
*/
function getCookie(cookieName) {
if (configCookiesDisabled) {
return 0;
}
var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'),
cookieMatch = cookiePattern.exec(documentAlias.cookie);
return cookieMatch ? decodeWrapper(cookieMatch[2]) : 0;
}
/*
* Removes hash tag from the URL
*
* URLs are purified before being recorded in the cookie,
* or before being sent as GET parameters
*/
function purify(url) {
var targetPattern;
if (configDiscardHashTag) {
targetPattern = new RegExp('#.*');
return url.replace(targetPattern, '');
}
return url;
}
/*
* Resolve relative reference
*
* Note: not as described in rfc3986 section 5.2
*/
function resolveRelativeReference(baseUrl, url) {
var protocol = getProtocolScheme(url),
i;
if (protocol) {
return url;
}
if (url.slice(0, 1) === '/') {
return getProtocolScheme(baseUrl) + '://' + getHostName(baseUrl) + url;
}
baseUrl = purify(baseUrl);
i = baseUrl.indexOf('?');
if (i >= 0) {
baseUrl = baseUrl.slice(0, i);
}
i = baseUrl.lastIndexOf('/');
if (i !== baseUrl.length - 1) {
baseUrl = baseUrl.slice(0, i + 1);
}
return baseUrl + url;
}
/*
* Is the host local? (i.e., not an outlink)
*/
function isSiteHostName(hostName) {
var i,
alias,
offset;
for (i = 0; i < configHostsAlias.length; i++) {
alias = domainFixup(configHostsAlias[i].toLowerCase());
if (hostName === alias) {
return true;
}
if (alias.slice(0, 1) === '.') {
if (hostName === alias.slice(1)) {
return true;
}
offset = hostName.length - alias.length;
if ((offset > 0) && (hostName.slice(offset) === alias)) {
return true;
}
}
}
return false;
}
/*
* Send image request to Piwik server using GET.
* The infamous web bug (or beacon) is a transparent, single pixel (1x1) image
*/
function getImage(request, callback) {
var image = new Image(1, 1);
image.onload = function () {
iterator = 0; // To avoid JSLint warning of empty block
if (typeof callback === 'function') { callback(); }
};
image.src = configTrackerUrl + (configTrackerUrl.indexOf('?') < 0 ? '?' : '&') + request;
}
/*
* POST request to Piwik server using XMLHttpRequest.
*/
function sendXmlHttpRequest(request, callback, fallbackToGet) {
if (!isDefined(fallbackToGet) || null === fallbackToGet) {
fallbackToGet = true;
}
try {
// we use the progid Microsoft.XMLHTTP because
// IE5.5 included MSXML 2.5; the progid MSXML2.XMLHTTP
// is pinned to MSXML2.XMLHTTP.3.0
var xhr = windowAlias.XMLHttpRequest
? new windowAlias.XMLHttpRequest()
: windowAlias.ActiveXObject
? new ActiveXObject('Microsoft.XMLHTTP')
: null;
xhr.open('POST', configTrackerUrl, true);
// fallback on error
xhr.onreadystatechange = function () {
if (this.readyState === 4 && !(this.status >= 200 && this.status < 300) && fallbackToGet) {
getImage(request, callback);
} else {
if (typeof callback === 'function') { callback(); }
}
};
xhr.setRequestHeader('Content-Type', configRequestContentType);
xhr.send(request);
} catch (e) {
if (fallbackToGet) {
// fallback
getImage(request, callback);
}
}
}
function setExpireDateTime(delay) {
var now = new Date();
var time = now.getTime() + delay;
if (!expireDateTime || time > expireDateTime) {
expireDateTime = time;
}
}
function makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(callback)
{
var now = new Date();
var timeNow = now.getTime();
if (timeNextTrackingRequestCanBeExecutedImmediately && timeNow < timeNextTrackingRequestCanBeExecutedImmediately) {
// we are in the time frame shortly after the first request. we have to delay this request a bit to make sure
// a visitor has been created meanwhile.
var timeToWait = timeNextTrackingRequestCanBeExecutedImmediately - timeNow;
setTimeout(callback, timeToWait);
setExpireDateTime(timeToWait + 50); // set timeout is not necessarily executed at timeToWait so delay a bit more
timeNextTrackingRequestCanBeExecutedImmediately += 50; // delay next tracking request by further 50ms to next execute them at same time
return;
}
if (timeNextTrackingRequestCanBeExecutedImmediately === false) {
// it is the first request, we want to execute this one directly and delay all the next one(s) within a delay.
// All requests after this delay can be executed as usual again
var delayInMs = 800;
timeNextTrackingRequestCanBeExecutedImmediately = timeNow + delayInMs;
}
callback();
}
/*
* Send request
*/
function sendRequest(request, delay, callback) {
if (!configDoNotTrack && request) {
makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () {
if (configRequestMethod === 'POST') {
sendXmlHttpRequest(request, callback);
} else {
getImage(request, callback);
}
setExpireDateTime(delay);
});
}
}
function canSendBulkRequest(requests)
{
if (configDoNotTrack) {
return false;
}
return (requests && requests.length);
}
/*
* Send requests using bulk
*/
function sendBulkRequest(requests, delay)
{
if (!canSendBulkRequest(requests)) {
return;
}
var bulk = '{"requests":["?' + requests.join('","?') + '"]}';
makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () {
sendXmlHttpRequest(bulk, null, false);
setExpireDateTime(delay);
});
}
/*
* Get cookie name with prefix and domain hash
*/
function getCookieName(baseName) {
// NOTE: If the cookie name is changed, we must also update the PiwikTracker.php which
// will attempt to discover first party cookies. eg. See the PHP Client method getVisitorId()
return configCookieNamePrefix + baseName + '.' + configTrackerSiteId + '.' + domainHash;
}
/*
* Does browser have cookies enabled (for this site)?
*/
function hasCookies() {
if (configCookiesDisabled) {
return '0';
}
if (!isDefined(navigatorAlias.cookieEnabled)) {
var testCookieName = getCookieName('testcookie');
setCookie(testCookieName, '1');
return getCookie(testCookieName) === '1' ? '1' : '0';
}
return navigatorAlias.cookieEnabled ? '1' : '0';
}
/*
* Update domain hash
*/
function updateDomainHash() {
domainHash = hash((configCookieDomain || domainAlias) + (configCookiePath || '/')).slice(0, 4); // 4 hexits = 16 bits
}
/*
* Inits the custom variables object
*/
function getCustomVariablesFromCookie() {
var cookieName = getCookieName('cvar'),
cookie = getCookie(cookieName);
if (cookie.length) {
cookie = JSON2.parse(cookie);
if (isObject(cookie)) {
return cookie;
}
}
return {};
}
/*
* Lazy loads the custom variables from the cookie, only once during this page view
*/
function loadCustomVariables() {
if (customVariables === false) {
customVariables = getCustomVariablesFromCookie();
}
}
/*
* Process all "activity" events.
* For performance, this function must have low overhead.
*/
function activityHandler() {
var now = new Date();
lastActivityTime = now.getTime();
}
/*
* Generate a pseudo-unique ID to fingerprint this user
* 16 hexits = 64 bits
* note: this isn't a RFC4122-compliant UUID
*/
function generateRandomUuid() {
return hash(
(navigatorAlias.userAgent || '') +
(navigatorAlias.platform || '') +
JSON2.stringify(browserFeatures) +
(new Date()).getTime() +
Math.random()
).slice(0, 16);
}
/*
* Load visitor ID cookie
*/
function loadVisitorIdCookie() {
var now = new Date(),
nowTs = Math.round(now.getTime() / 1000),
visitorIdCookieName = getCookieName('id'),
id = getCookie(visitorIdCookieName),
cookieValue,
uuid;
// Visitor ID cookie found
if (id) {
cookieValue = id.split('.');
// returning visitor flag
cookieValue.unshift('0');
if(visitorUUID.length) {
cookieValue[1] = visitorUUID;
}
return cookieValue;
}
if(visitorUUID.length) {
uuid = visitorUUID;
} else if ('0' === hasCookies()){
uuid = '';
} else {
uuid = generateRandomUuid();
}
// No visitor ID cookie, let's create a new one
cookieValue = [
// new visitor
'1',
// uuid
uuid,
// creation timestamp - seconds since Unix epoch
nowTs,
// visitCount - 0 = no previous visit
0,
// current visit timestamp
nowTs,
// last visit timestamp - blank = no previous visit
'',
// last ecommerce order timestamp
''
];
return cookieValue;
}
/**
* Loads the Visitor ID cookie and returns a named array of values
*/
function getValuesFromVisitorIdCookie() {
var cookieVisitorIdValue = loadVisitorIdCookie(),
newVisitor = cookieVisitorIdValue[0],
uuid = cookieVisitorIdValue[1],
createTs = cookieVisitorIdValue[2],
visitCount = cookieVisitorIdValue[3],
currentVisitTs = cookieVisitorIdValue[4],
lastVisitTs = cookieVisitorIdValue[5];
// case migrating from pre-1.5 cookies
if (!isDefined(cookieVisitorIdValue[6])) {
cookieVisitorIdValue[6] = "";
}
var lastEcommerceOrderTs = cookieVisitorIdValue[6];
return {
newVisitor: newVisitor,
uuid: uuid,
createTs: createTs,
visitCount: visitCount,
currentVisitTs: currentVisitTs,
lastVisitTs: lastVisitTs,
lastEcommerceOrderTs: lastEcommerceOrderTs
};
}
function getRemainingVisitorCookieTimeout() {
var now = new Date(),
nowTs = now.getTime(),
cookieCreatedTs = getValuesFromVisitorIdCookie().createTs;
var createTs = parseInt(cookieCreatedTs, 10);
var originalTimeout = (createTs * 1000) + configVisitorCookieTimeout - nowTs;
return originalTimeout;
}
/*
* Sets the Visitor ID cookie
*/
function setVisitorIdCookie(visitorIdCookieValues) {
if(!configTrackerSiteId) {
// when called before Site ID was set
return;
}
var now = new Date(),
nowTs = Math.round(now.getTime() / 1000);
if(!isDefined(visitorIdCookieValues)) {
visitorIdCookieValues = getValuesFromVisitorIdCookie();
}
var cookieValue = visitorIdCookieValues.uuid + '.' +
visitorIdCookieValues.createTs + '.' +
visitorIdCookieValues.visitCount + '.' +
nowTs + '.' +
visitorIdCookieValues.lastVisitTs + '.' +
visitorIdCookieValues.lastEcommerceOrderTs;
setCookie(getCookieName('id'), cookieValue, getRemainingVisitorCookieTimeout(), configCookiePath, configCookieDomain);
}
/*
* Loads the referrer attribution information
*
* @returns array
* 0: campaign name
* 1: campaign keyword
* 2: timestamp
* 3: raw URL
*/
function loadReferrerAttributionCookie() {
// NOTE: if the format of the cookie changes,
// we must also update JS tests, PHP tracker, System tests,
// and notify other tracking clients (eg. Java) of the changes
var cookie = getCookie(getCookieName('ref'));
if (cookie.length) {
try {
cookie = JSON2.parse(cookie);
if (isObject(cookie)) {
return cookie;
}
} catch (ignore) {
// Pre 1.3, this cookie was not JSON encoded
}
}
return [
'',
'',
0,
''
];
}
function deleteCookie(cookieName, path, domain) {
setCookie(cookieName, '', -86400, path, domain);
}
function isPossibleToSetCookieOnDomain(domainToTest)
{
var valueToSet = 'testvalue';
setCookie('test', valueToSet, 10000, null, domainToTest);
if (getCookie('test') === valueToSet) {
deleteCookie('test', null, domainToTest);
return true;
}
return false;
}
function deleteCookies() {
var savedConfigCookiesDisabled = configCookiesDisabled;
// Temporarily allow cookies just to delete the existing ones
configCookiesDisabled = false;
deleteCookie(getCookieName('id'), configCookiePath, configCookieDomain);
deleteCookie(getCookieName('ses'), configCookiePath, configCookieDomain);
deleteCookie(getCookieName('cvar'), configCookiePath, configCookieDomain);
deleteCookie(getCookieName('ref'), configCookiePath, configCookieDomain);
configCookiesDisabled = savedConfigCookiesDisabled;
}
function setSiteId(siteId) {
configTrackerSiteId = siteId;
setVisitorIdCookie();
}
function sortObjectByKeys(value) {
if (!value || !isObject(value)) {
return;
}
// Object.keys(value) is not supported by all browsers, we get the keys manually
var keys = [];
var key;
for (key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
keys.push(key);
}
}
var normalized = {};
keys.sort();
var len = keys.length;
var i;
for (i = 0; i < len; i++) {
normalized[keys[i]] = value[keys[i]];
}
return normalized;
}
/**
* Creates the session cookie
*/
function setSessionCookie() {
setCookie(getCookieName('ses'), '*', configSessionCookieTimeout, configCookiePath, configCookieDomain);
}
/**
* Returns the URL to call piwik.php,
* with the standard parameters (plugins, resolution, url, referrer, etc.).
* Sends the pageview and browser settings with every request in case of race conditions.
*/
function getRequest(request, customData, pluginMethod, currentEcommerceOrderTs) {
var i,
now = new Date(),
nowTs = Math.round(now.getTime() / 1000),
referralTs,
referralUrl,
referralUrlMaxLength = 1024,
currentReferrerHostName,
originalReferrerHostName,
customVariablesCopy = customVariables,
cookieSessionName = getCookieName('ses'),
cookieReferrerName = getCookieName('ref'),
cookieCustomVariablesName = getCookieName('cvar'),
cookieSessionValue = getCookie(cookieSessionName),
attributionCookie = loadReferrerAttributionCookie(),
currentUrl = configCustomUrl || locationHrefAlias,
campaignNameDetected,
campaignKeywordDetected;
if (configCookiesDisabled) {
deleteCookies();
}
if (configDoNotTrack) {
return '';
}
var cookieVisitorIdValues = getValuesFromVisitorIdCookie();
if (!isDefined(currentEcommerceOrderTs)) {
currentEcommerceOrderTs = "";
}
// send charset if document charset is not utf-8. sometimes encoding
// of urls will be the same as this and not utf-8, which will cause problems
// do not send charset if it is utf8 since it's assumed by default in Piwik
var charSet = documentAlias.characterSet || documentAlias.charset;
if (!charSet || charSet.toLowerCase() === 'utf-8') {
charSet = null;
}
campaignNameDetected = attributionCookie[0];
campaignKeywordDetected = attributionCookie[1];
referralTs = attributionCookie[2];
referralUrl = attributionCookie[3];
if (!cookieSessionValue) {
// cookie 'ses' was not found: we consider this the start of a 'session'
// here we make sure that if 'ses' cookie is deleted few times within the visit
// and so this code path is triggered many times for one visit,
// we only increase visitCount once per Visit window (default 30min)
var visitDuration = configSessionCookieTimeout / 1000;
if (!cookieVisitorIdValues.lastVisitTs
|| (nowTs - cookieVisitorIdValues.lastVisitTs) > visitDuration) {
cookieVisitorIdValues.visitCount++;
cookieVisitorIdValues.lastVisitTs = cookieVisitorIdValues.currentVisitTs;
}
// Detect the campaign information from the current URL
// Only if campaign wasn't previously set
// Or if it was set but we must attribute to the most recent one
// Note: we are working on the currentUrl before purify() since we can parse the campaign parameters in the hash tag
if (!configConversionAttributionFirstReferrer
|| !campaignNameDetected.length) {
for (i in configCampaignNameParameters) {
if (Object.prototype.hasOwnProperty.call(configCampaignNameParameters, i)) {
campaignNameDetected = getParameter(currentUrl, configCampaignNameParameters[i]);
if (campaignNameDetected.length) {
break;
}
}
}
for (i in configCampaignKeywordParameters) {
if (Object.prototype.hasOwnProperty.call(configCampaignKeywordParameters, i)) {
campaignKeywordDetected = getParameter(currentUrl, configCampaignKeywordParameters[i]);
if (campaignKeywordDetected.length) {
break;
}
}
}
}
// Store the referrer URL and time in the cookie;
// referral URL depends on the first or last referrer attribution
currentReferrerHostName = getHostName(configReferrerUrl);
originalReferrerHostName = referralUrl.length ? getHostName(referralUrl) : '';
if (currentReferrerHostName.length && // there is a referrer
!isSiteHostName(currentReferrerHostName) && // domain is not the current domain
(!configConversionAttributionFirstReferrer || // attribute to last known referrer
!originalReferrerHostName.length || // previously empty
isSiteHostName(originalReferrerHostName))) { // previously set but in current domain
referralUrl = configReferrerUrl;
}
// Set the referral cookie if we have either a Referrer URL, or detected a Campaign (or both)
if (referralUrl.length
|| campaignNameDetected.length) {
referralTs = nowTs;
attributionCookie = [
campaignNameDetected,
campaignKeywordDetected,
referralTs,
purify(referralUrl.slice(0, referralUrlMaxLength))
];
setCookie(cookieReferrerName, JSON2.stringify(attributionCookie), configReferralCookieTimeout, configCookiePath, configCookieDomain);
}
}
// build out the rest of the request
request += '&idsite=' + configTrackerSiteId +
'&rec=1' +
'&r=' + String(Math.random()).slice(2, 8) + // keep the string to a minimum
'&h=' + now.getHours() + '&m=' + now.getMinutes() + '&s=' + now.getSeconds() +
'&url=' + encodeWrapper(purify(currentUrl)) +
(configReferrerUrl.length ? '&urlref=' + encodeWrapper(purify(configReferrerUrl)) : '') +
((configUserId && configUserId.length) ? '&uid=' + encodeWrapper(configUserId) : '') +
'&_id=' + cookieVisitorIdValues.uuid + '&_idts=' + cookieVisitorIdValues.createTs + '&_idvc=' + cookieVisitorIdValues.visitCount +
'&_idn=' + cookieVisitorIdValues.newVisitor + // currently unused
(campaignNameDetected.length ? '&_rcn=' + encodeWrapper(campaignNameDetected) : '') +
(campaignKeywordDetected.length ? '&_rck=' + encodeWrapper(campaignKeywordDetected) : '') +
'&_refts=' + referralTs +
'&_viewts=' + cookieVisitorIdValues.lastVisitTs +
(String(cookieVisitorIdValues.lastEcommerceOrderTs).length ? '&_ects=' + cookieVisitorIdValues.lastEcommerceOrderTs : '') +
(String(referralUrl).length ? '&_ref=' + encodeWrapper(purify(referralUrl.slice(0, referralUrlMaxLength))) : '') +
(charSet ? '&cs=' + encodeWrapper(charSet) : '') +
'&send_image=0';
// browser features
for (i in browserFeatures) {
if (Object.prototype.hasOwnProperty.call(browserFeatures, i)) {
request += '&' + i + '=' + browserFeatures[i];
}
}
// custom data
if (customData) {
request += '&data=' + encodeWrapper(JSON2.stringify(customData));
} else if (configCustomData) {
request += '&data=' + encodeWrapper(JSON2.stringify(configCustomData));
}
// Custom Variables, scope "page"
function appendCustomVariablesToRequest(customVariables, parameterName) {
var customVariablesStringified = JSON2.stringify(customVariables);
if (customVariablesStringified.length > 2) {
return '&' + parameterName + '=' + encodeWrapper(customVariablesStringified);
}
return '';
}
var sortedCustomVarPage = sortObjectByKeys(customVariablesPage);
var sortedCustomVarEvent = sortObjectByKeys(customVariablesEvent);
request += appendCustomVariablesToRequest(sortedCustomVarPage, 'cvar');
request += appendCustomVariablesToRequest(sortedCustomVarEvent, 'e_cvar');
// Custom Variables, scope "visit"
if (customVariables) {
request += appendCustomVariablesToRequest(customVariables, '_cvar');
// Don't save deleted custom variables in the cookie
for (i in customVariablesCopy) {
if (Object.prototype.hasOwnProperty.call(customVariablesCopy, i)) {
if (customVariables[i][0] === '' || customVariables[i][1] === '') {
delete customVariables[i];
}
}
}
if (configStoreCustomVariablesInCookie) {
setCookie(cookieCustomVariablesName, JSON2.stringify(customVariables), configSessionCookieTimeout, configCookiePath, configCookieDomain);
}
}
// performance tracking
if (configPerformanceTrackingEnabled) {
if (configPerformanceGenerationTime) {
request += '>_ms=' + configPerformanceGenerationTime;
} else if (performanceAlias && performanceAlias.timing
&& performanceAlias.timing.requestStart && performanceAlias.timing.responseEnd) {
request += '>_ms=' + (performanceAlias.timing.responseEnd - performanceAlias.timing.requestStart);
}
}
// update cookies
cookieVisitorIdValues.lastEcommerceOrderTs = isDefined(currentEcommerceOrderTs) && String(currentEcommerceOrderTs).length ? currentEcommerceOrderTs : cookieVisitorIdValues.lastEcommerceOrderTs;
setVisitorIdCookie(cookieVisitorIdValues);
setSessionCookie();
// tracker plugin hook
request += executePluginMethod(pluginMethod);
if (configAppendToTrackingUrl.length) {
request += '&' + configAppendToTrackingUrl;
}
if (isFunction(configCustomRequestContentProcessing)) {
request = configCustomRequestContentProcessing(request);
}
return request;
}
function logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount) {
var request = 'idgoal=0',
lastEcommerceOrderTs,
now = new Date(),
items = [],
sku;
if (String(orderId).length) {
request += '&ec_id=' + encodeWrapper(orderId);
// Record date of order in the visitor cookie
lastEcommerceOrderTs = Math.round(now.getTime() / 1000);
}
request += '&revenue=' + grandTotal;
if (String(subTotal).length) {
request += '&ec_st=' + subTotal;
}
if (String(tax).length) {
request += '&ec_tx=' + tax;
}
if (String(shipping).length) {
request += '&ec_sh=' + shipping;
}
if (String(discount).length) {
request += '&ec_dt=' + discount;
}
if (ecommerceItems) {
// Removing the SKU index in the array before JSON encoding
for (sku in ecommerceItems) {
if (Object.prototype.hasOwnProperty.call(ecommerceItems, sku)) {
// Ensure name and category default to healthy value
if (!isDefined(ecommerceItems[sku][1])) {
ecommerceItems[sku][1] = "";
}
if (!isDefined(ecommerceItems[sku][2])) {
ecommerceItems[sku][2] = "";
}
// Set price to zero
if (!isDefined(ecommerceItems[sku][3])
|| String(ecommerceItems[sku][3]).length === 0) {
ecommerceItems[sku][3] = 0;
}
// Set quantity to 1
if (!isDefined(ecommerceItems[sku][4])
|| String(ecommerceItems[sku][4]).length === 0) {
ecommerceItems[sku][4] = 1;
}
items.push(ecommerceItems[sku]);
}
}
request += '&ec_items=' + encodeWrapper(JSON2.stringify(items));
}
request = getRequest(request, configCustomData, 'ecommerce', lastEcommerceOrderTs);
sendRequest(request, configTrackerPause);
}
function logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount) {
if (String(orderId).length
&& isDefined(grandTotal)) {
logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount);
}
}
function logEcommerceCartUpdate(grandTotal) {
if (isDefined(grandTotal)) {
logEcommerce("", grandTotal, "", "", "", "");
}
}
/*
* Log the page view / visit
*/
function logPageView(customTitle, customData) {
var now = new Date(),
request = getRequest('action_name=' + encodeWrapper(titleFixup(customTitle || configTitle)), customData, 'log');
sendRequest(request, configTrackerPause);
// send ping
if (configMinimumVisitTime && configHeartBeatTimer && !activityTrackingInstalled) {
activityTrackingInstalled = true;
// add event handlers; cross-browser compatibility here varies significantly
// @see http://quirksmode.org/dom/events
addEventListener(documentAlias, 'click', activityHandler);
addEventListener(documentAlias, 'mouseup', activityHandler);
addEventListener(documentAlias, 'mousedown', activityHandler);
addEventListener(documentAlias, 'mousemove', activityHandler);
addEventListener(documentAlias, 'mousewheel', activityHandler);
addEventListener(windowAlias, 'DOMMouseScroll', activityHandler);
addEventListener(windowAlias, 'scroll', activityHandler);
addEventListener(documentAlias, 'keypress', activityHandler);
addEventListener(documentAlias, 'keydown', activityHandler);
addEventListener(documentAlias, 'keyup', activityHandler);
addEventListener(windowAlias, 'resize', activityHandler);
addEventListener(windowAlias, 'focus', activityHandler);
addEventListener(windowAlias, 'blur', activityHandler);
// periodic check for activity
lastActivityTime = now.getTime();
setTimeout(function heartBeat() {
var requestPing;
now = new Date();
// there was activity during the heart beat period;
// on average, this is going to overstate the visitDuration by configHeartBeatTimer/2
if ((lastActivityTime + configHeartBeatTimer) > now.getTime()) {
// send ping if minimum visit time has elapsed
if (configMinimumVisitTime < now.getTime()) {
requestPing = getRequest('ping=1', customData, 'ping');
sendRequest(requestPing, configTrackerPause);
}
// resume heart beat
setTimeout(heartBeat, configHeartBeatTimer);
}
// else heart beat cancelled due to inactivity
}, configHeartBeatTimer);
}
}
/*
* Construct regular expression of classes
*/
function getClassesRegExp(configClasses, defaultClass) {
var i,
classesRegExp = '(^| )(piwik[_-]' + defaultClass;
if (configClasses) {
for (i = 0; i < configClasses.length; i++) {
classesRegExp += '|' + configClasses[i];
}
}
classesRegExp += ')( |$)';
return new RegExp(classesRegExp);
}
function startsUrlWithTrackerUrl(url) {
return (configTrackerUrl && url && 0 === String(url).indexOf(configTrackerUrl));
}
/*
* Link or Download?
*/
function getLinkType(className, href, isInLink, hasDownloadAttribute) {
if (startsUrlWithTrackerUrl(href)) {
return 0;
}
// does class indicate whether it is an (explicit/forced) outlink or a download?
var downloadPattern = getClassesRegExp(configDownloadClasses, 'download'),
linkPattern = getClassesRegExp(configLinkClasses, 'link'),
// does file extension indicate that it is a download?
downloadExtensionsPattern = new RegExp('\\.(' + configDownloadExtensions.join('|') + ')([?&#]|$)', 'i');
if (linkPattern.test(className)) {
return 'link';
}
if (hasDownloadAttribute || downloadPattern.test(className) || downloadExtensionsPattern.test(href)) {
return 'download';
}
if (isInLink) {
return 0;
}
return 'link';
}
function getSourceElement(sourceElement)
{
var parentElement;
parentElement = sourceElement.parentNode;
while (parentElement !== null &&
/* buggy IE5.5 */
isDefined(parentElement)) {
if (query.isLinkElement(sourceElement)) {
break;
}
sourceElement = parentElement;
parentElement = sourceElement.parentNode;
}
return sourceElement;
}
function getLinkIfShouldBeProcessed(sourceElement)
{
sourceElement = getSourceElement(sourceElement);
if (!query.hasNodeAttribute(sourceElement, 'href')) {
return;
}
if (!isDefined(sourceElement.href)) {
return;
}
var href = query.getAttributeValueFromNode(sourceElement, 'href');
if (startsUrlWithTrackerUrl(href)) {
return;
}
// browsers, such as Safari, don't downcase hostname and href
var originalSourceHostName = sourceElement.hostname || getHostName(sourceElement.href);
var sourceHostName = originalSourceHostName.toLowerCase();
var sourceHref = sourceElement.href.replace(originalSourceHostName, sourceHostName);
// browsers, such as Safari, don't downcase hostname and href
var scriptProtocol = new RegExp('^(javascript|vbscript|jscript|mocha|livescript|ecmascript|mailto):', 'i');
if (!scriptProtocol.test(sourceHref)) {
// track outlinks and all downloads
var linkType = getLinkType(sourceElement.className, sourceHref, isSiteHostName(sourceHostName), query.hasNodeAttribute(sourceElement, 'download'));
if (linkType) {
return {
type: linkType,
href: sourceHref
};
}
}
}
function buildContentInteractionRequest(interaction, name, piece, target)
{
var params = content.buildInteractionRequestParams(interaction, name, piece, target);
if (!params) {
return;
}
return getRequest(params, null, 'contentInteraction');
}
function buildContentInteractionTrackingRedirectUrl(url, contentInteraction, contentName, contentPiece, contentTarget)
{
if (!isDefined(url)) {
return;
}
if (startsUrlWithTrackerUrl(url)) {
return url;
}
var redirectUrl = content.toAbsoluteUrl(url);
var request = 'redirecturl=' + encodeWrapper(redirectUrl) + '&';
request += buildContentInteractionRequest(contentInteraction, contentName, contentPiece, (contentTarget || url));
var separator = '&';
if (configTrackerUrl.indexOf('?') < 0) {
separator = '?';
}
return configTrackerUrl + separator + request;
}
function isNodeAuthorizedToTriggerInteraction(contentNode, interactedNode)
{
if (!contentNode || !interactedNode) {
return false;
}
var targetNode = content.findTargetNode(contentNode);
if (content.shouldIgnoreInteraction(targetNode)) {
// interaction should be ignored
return false;
}
targetNode = content.findTargetNodeNoDefault(contentNode);
if (targetNode && !containsNodeElement(targetNode, interactedNode)) {
/**
* There is a target node defined but the clicked element is not within the target node. example:
* <div data-track-content><a href="Y" data-content-target>Y</a><img src=""/><a href="Z">Z</a></div>
*
* The user clicked in this case on link Z and not on target Y
*/
return false;
}
return true;
}
function getContentInteractionToRequestIfPossible (anyNode, interaction, fallbackTarget)
{
if (!anyNode) {
return;
}
var contentNode = content.findParentContentNode(anyNode);
if (!contentNode) {
// we are not within a content block
return;
}
if (!isNodeAuthorizedToTriggerInteraction(contentNode, anyNode)) {
return;
}
var contentBlock = content.buildContentBlock(contentNode);
if (!contentBlock) {
return;
}
if (!contentBlock.target && fallbackTarget) {
contentBlock.target = fallbackTarget;
}
return content.buildInteractionRequestParams(interaction, contentBlock.name, contentBlock.piece, contentBlock.target);
}
function wasContentImpressionAlreadyTracked(contentBlock)
{
if (!trackedContentImpressions || !trackedContentImpressions.length) {
return false;
}
var index, trackedContent;
for (index = 0; index < trackedContentImpressions.length; index++) {
trackedContent = trackedContentImpressions[index];
if (trackedContent &&
trackedContent.name === contentBlock.name &&
trackedContent.piece === contentBlock.piece &&
trackedContent.target === contentBlock.target) {
return true;
}
}
return false;
}
function replaceHrefIfInternalLink(contentBlock)
{
if (!contentBlock) {
return false;
}
var targetNode = content.findTargetNode(contentBlock);
if (!targetNode || content.shouldIgnoreInteraction(targetNode)) {
return false;
}
var link = getLinkIfShouldBeProcessed(targetNode);
if (linkTrackingEnabled && link && link.type) {
return false; // will be handled via outlink or download.
}
if (query.isLinkElement(targetNode) &&
query.hasNodeAttributeWithValue(targetNode, 'href')) {
var url = String(query.getAttributeValueFromNode(targetNode, 'href'));
if (0 === url.indexOf('#')) {
return false;
}
if (startsUrlWithTrackerUrl(url)) {
return true;
}
if (!content.isUrlToCurrentDomain(url)) {
return false;
}
var block = content.buildContentBlock(contentBlock);
if (!block) {
return;
}
var contentName = block.name;
var contentPiece = block.piece;
var contentTarget = block.target;
if (!query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR) || targetNode.wasContentTargetAttrReplaced) {
// make sure we still track the correct content target when an interaction is happening
targetNode.wasContentTargetAttrReplaced = true;
contentTarget = content.toAbsoluteUrl(url);
query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, contentTarget);
}
var targetUrl = buildContentInteractionTrackingRedirectUrl(url, 'click', contentName, contentPiece, contentTarget);
// location.href does not respect target=_blank so we prefer to use this
content.setHrefAttribute(targetNode, targetUrl);
return true;
}
return false;
}
function replaceHrefsIfInternalLink(contentNodes)
{
if (!contentNodes || !contentNodes.length) {
return;
}
var index;
for (index = 0; index < contentNodes.length; index++) {
replaceHrefIfInternalLink(contentNodes[index]);
}
}
function trackContentImpressionClickInteraction (targetNode)
{
return function (event) {
if (!targetNode) {
return;
}
var contentBlock = content.findParentContentNode(targetNode);
var interactedElement;
if (event) {
interactedElement = event.target || event.srcElement;
}
if (!interactedElement) {
interactedElement = targetNode;
}
if (!isNodeAuthorizedToTriggerInteraction(contentBlock, interactedElement)) {
return;
}
setExpireDateTime(configTrackerPause);
if (query.isLinkElement(targetNode) &&
query.hasNodeAttributeWithValue(targetNode, 'href') &&
query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR)) {
// there is a href attribute, the link was replaced with piwik.php but later the href was changed again by the application.
var href = query.getAttributeValueFromNode(targetNode, 'href');
if (!startsUrlWithTrackerUrl(href) && targetNode.wasContentTargetAttrReplaced) {
query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, '');
}
}
var link = getLinkIfShouldBeProcessed(targetNode);
if (linkTrackingInstalled && link && link.type) {
// click ignore, will be tracked via processClick, we do not want to track it twice
return link.type;
}
if (replaceHrefIfInternalLink(contentBlock)) {
return 'href';
}
var block = content.buildContentBlock(contentBlock);
if (!block) {
return;
}
var contentName = block.name;
var contentPiece = block.piece;
var contentTarget = block.target;
// click on any non link element, or on a link element that has not an href attribute or on an anchor
var request = buildContentInteractionRequest('click', contentName, contentPiece, contentTarget);
sendRequest(request, configTrackerPause);
return request;
};
}
function setupInteractionsTracking(contentNodes)
{
if (!contentNodes || !contentNodes.length) {
return;
}
var index, targetNode;
for (index = 0; index < contentNodes.length; index++) {
targetNode = content.findTargetNode(contentNodes[index]);
if (targetNode && !targetNode.contentInteractionTrackingSetupDone) {
targetNode.contentInteractionTrackingSetupDone = true;
addEventListener(targetNode, 'click', trackContentImpressionClickInteraction(targetNode));
}
}
}
/*
* Log all content pieces
*/
function buildContentImpressionsRequests(contents, contentNodes)
{
if (!contents || !contents.length) {
return [];
}
var index, request;
for (index = 0; index < contents.length; index++) {
if (wasContentImpressionAlreadyTracked(contents[index])) {
contents.splice(index, 1);
index--;
} else {
trackedContentImpressions.push(contents[index]);
}
}
if (!contents || !contents.length) {
return [];
}
replaceHrefsIfInternalLink(contentNodes);
setupInteractionsTracking(contentNodes);
var requests = [];
for (index = 0; index < contents.length; index++) {
request = getRequest(
content.buildImpressionRequestParams(contents[index].name, contents[index].piece, contents[index].target),
undefined,
'contentImpressions'
);
requests.push(request);
}
return requests;
}
/*
* Log all content pieces
*/
function getContentImpressionsRequestsFromNodes(contentNodes)
{
var contents = content.collectContent(contentNodes);
return buildContentImpressionsRequests(contents, contentNodes);
}
/*
* Log currently visible content pieces
*/
function getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes)
{
if (!contentNodes || !contentNodes.length) {
return [];
}
var index;
for (index = 0; index < contentNodes.length; index++) {
if (!content.isNodeVisible(contentNodes[index])) {
contentNodes.splice(index, 1);
index--;
}
}
if (!contentNodes || !contentNodes.length) {
return [];
}
return getContentImpressionsRequestsFromNodes(contentNodes);
}
function buildContentImpressionRequest(contentName, contentPiece, contentTarget)
{
var params = content.buildImpressionRequestParams(contentName, contentPiece, contentTarget);
return getRequest(params, null, 'contentImpression');
}
function buildContentInteractionRequestNode(node, contentInteraction)
{
if (!node) {
return;
}
var contentNode = content.findParentContentNode(node);
var contentBlock = content.buildContentBlock(contentNode);
if (!contentBlock) {
return;
}
if (!contentInteraction) {
contentInteraction = 'Unknown';
}
return buildContentInteractionRequest(contentInteraction, contentBlock.name, contentBlock.piece, contentBlock.target);
}
function buildEventRequest(category, action, name, value)
{
return 'e_c=' + encodeWrapper(category)
+ '&e_a=' + encodeWrapper(action)
+ (isDefined(name) ? '&e_n=' + encodeWrapper(name) : '')
+ (isDefined(value) ? '&e_v=' + encodeWrapper(value) : '');
}
/*
* Log the event
*/
function logEvent(category, action, name, value, customData)
{
// Category and Action are required parameters
if (String(category).length === 0 || String(action).length === 0) {
return false;
}
var request = getRequest(
buildEventRequest(category, action, name, value),
customData,
'event'
);
sendRequest(request, configTrackerPause);
}
/*
* Log the site search request
*/
function logSiteSearch(keyword, category, resultsCount, customData) {
var request = getRequest('search=' + encodeWrapper(keyword)
+ (category ? '&search_cat=' + encodeWrapper(category) : '')
+ (isDefined(resultsCount) ? '&search_count=' + resultsCount : ''), customData, 'sitesearch');
sendRequest(request, configTrackerPause);
}
/*
* Log the goal with the server
*/
function logGoal(idGoal, customRevenue, customData) {
var request = getRequest('idgoal=' + idGoal + (customRevenue ? '&revenue=' + customRevenue : ''), customData, 'goal');
sendRequest(request, configTrackerPause);
}
/*
* Log the link or click with the server
*/
function logLink(url, linkType, customData, callback, sourceElement) {
var linkParams = linkType + '=' + encodeWrapper(purify(url));
var interaction = getContentInteractionToRequestIfPossible(sourceElement, 'click', url);
if (interaction) {
linkParams += '&' + interaction;
}
var request = getRequest(linkParams, customData, 'link');
sendRequest(request, (callback ? 0 : configTrackerPause), callback);
}
/*
* Browser prefix
*/
function prefixPropertyName(prefix, propertyName) {
if (prefix !== '') {
return prefix + propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
}
return propertyName;
}
/*
* Check for pre-rendered web pages, and log the page view/link/goal
* according to the configuration and/or visibility
*
* @see http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html
*/
function trackCallback(callback) {
var isPreRendered,
i,
// Chrome 13, IE10, FF10
prefixes = ['', 'webkit', 'ms', 'moz'],
prefix;
if (!configCountPreRendered) {
for (i = 0; i < prefixes.length; i++) {
prefix = prefixes[i];
// does this browser support the page visibility API?
if (Object.prototype.hasOwnProperty.call(documentAlias, prefixPropertyName(prefix, 'hidden'))) {
// if pre-rendered, then defer callback until page visibility changes
if (documentAlias[prefixPropertyName(prefix, 'visibilityState')] === 'prerender') {
isPreRendered = true;
}
break;
}
}
}
if (isPreRendered) {
// note: the event name doesn't follow the same naming convention as vendor properties
addEventListener(documentAlias, prefix + 'visibilitychange', function ready() {
documentAlias.removeEventListener(prefix + 'visibilitychange', ready, false);
callback();
});
return;
}
// configCountPreRendered === true || isPreRendered === false
callback();
}
function trackCallbackOnLoad(callback)
{
if (documentAlias.readyState === 'complete') {
callback();
} else if (windowAlias.addEventListener) {
windowAlias.addEventListener('load', callback);
} else if (windowAlias.attachEvent) {
windowAlias.attachEvent('onLoad', callback);
}
}
function trackCallbackOnReady(callback)
{
var loaded = false;
if (documentAlias.attachEvent) {
loaded = documentAlias.readyState === "complete";
} else {
loaded = documentAlias.readyState !== "loading";
}
if (loaded) {
callback();
} else if (documentAlias.addEventListener) {
documentAlias.addEventListener('DOMContentLoaded', callback);
} else if (documentAlias.attachEvent) {
documentAlias.attachEvent('onreadystatechange', callback);
}
}
/*
* Process clicks
*/
function processClick(sourceElement) {
var link = getLinkIfShouldBeProcessed(sourceElement);
if (link && link.type) {
// urldecode %xx
link.href = urldecode(link.href);
logLink(link.href, link.type, undefined, null, sourceElement);
}
}
/*
* Handle click event
*/
function clickHandler(evt) {
var button,
target;
evt = evt || windowAlias.event;
button = evt.which || evt.button;
target = evt.target || evt.srcElement;
// Using evt.type (added in IE4), we avoid defining separate handlers for mouseup and mousedown.
if (evt.type === 'click') {
if (target) {
processClick(target);
}
} else if (evt.type === 'mousedown') {
if ((button === 1 || button === 2) && target) {
lastButton = button;
lastTarget = target;
} else {
lastButton = lastTarget = null;
}
} else if (evt.type === 'mouseup') {
if (button === lastButton && target === lastTarget) {
processClick(target);
}
lastButton = lastTarget = null;
}
}
/*
* Add click listener to a DOM element
*/
function addClickListener(element, enable) {
if (enable) {
// for simplicity and performance, we ignore drag events
addEventListener(element, 'mouseup', clickHandler, false);
addEventListener(element, 'mousedown', clickHandler, false);
} else {
addEventListener(element, 'click', clickHandler, false);
}
}
/*
* Add click handlers to anchor and AREA elements, except those to be ignored
*/
function addClickListeners(enable) {
if (!linkTrackingInstalled) {
linkTrackingInstalled = true;
// iterate through anchor elements with href and AREA elements
var i,
ignorePattern = getClassesRegExp(configIgnoreClasses, 'ignore'),
linkElements = documentAlias.links;
if (linkElements) {
for (i = 0; i < linkElements.length; i++) {
if (!ignorePattern.test(linkElements[i].className)) {
addClickListener(linkElements[i], enable);
}
}
}
}
}
function enableTrackOnlyVisibleContent (checkOnSroll, timeIntervalInMs, tracker) {
if (isTrackOnlyVisibleContentEnabled) {
// already enabled, do not register intervals again
return true;
}
isTrackOnlyVisibleContentEnabled = true;
var didScroll = false;
var events, index;
function setDidScroll() { didScroll = true; }
trackCallbackOnLoad(function () {
function checkContent(intervalInMs) {
setTimeout(function () {
if (!isTrackOnlyVisibleContentEnabled) {
return; // the tests stopped tracking only visible content
}
didScroll = false;
tracker.trackVisibleContentImpressions();
checkContent(intervalInMs);
}, intervalInMs);
}
function checkContentIfDidScroll(intervalInMs) {
setTimeout(function () {
if (!isTrackOnlyVisibleContentEnabled) {
return; // the tests stopped tracking only visible content
}
if (didScroll) {
didScroll = false;
tracker.trackVisibleContentImpressions();
}
checkContentIfDidScroll(intervalInMs);
}, intervalInMs);
}
if (checkOnSroll) {
// scroll event is executed after each pixel, so we make sure not to
// execute event too often. otherwise FPS goes down a lot!
events = ['scroll', 'resize'];
for (index = 0; index < events.length; index++) {
if (documentAlias.addEventListener) {
documentAlias.addEventListener(events[index], setDidScroll);
} else {
windowAlias.attachEvent('on' + events[index], setDidScroll);
}
}
checkContentIfDidScroll(100);
}
if (timeIntervalInMs && timeIntervalInMs > 0) {
timeIntervalInMs = parseInt(timeIntervalInMs, 10);
checkContent(timeIntervalInMs);
}
});
}
/*
* Browser features (plugins, resolution, cookies)
*/
function detectBrowserFeatures() {
var i,
mimeType,
pluginMap = {
// document types
pdf: 'application/pdf',
// media players
qt: 'video/quicktime',
realp: 'audio/x-pn-realaudio-plugin',
wma: 'application/x-mplayer2',
// interactive multimedia
dir: 'application/x-director',
fla: 'application/x-shockwave-flash',
// RIA
java: 'application/x-java-vm',
gears: 'application/x-googlegears',
ag: 'application/x-silverlight'
},
devicePixelRatio = (new RegExp('Mac OS X.*Safari/')).test(navigatorAlias.userAgent) ? windowAlias.devicePixelRatio || 1 : 1;
// detect browser features except IE < 11 (IE 11 user agent is no longer MSIE)
if (!((new RegExp('MSIE')).test(navigatorAlias.userAgent))) {
// general plugin detection
if (navigatorAlias.mimeTypes && navigatorAlias.mimeTypes.length) {
for (i in pluginMap) {
if (Object.prototype.hasOwnProperty.call(pluginMap, i)) {
mimeType = navigatorAlias.mimeTypes[pluginMap[i]];
browserFeatures[i] = (mimeType && mimeType.enabledPlugin) ? '1' : '0';
}
}
}
// Safari and Opera
// IE6/IE7 navigator.javaEnabled can't be aliased, so test directly
if (typeof navigator.javaEnabled !== 'unknown' &&
isDefined(navigatorAlias.javaEnabled) &&
navigatorAlias.javaEnabled()) {
browserFeatures.java = '1';
}
// Firefox
if (isFunction(windowAlias.GearsFactory)) {
browserFeatures.gears = '1';
}
// other browser features
browserFeatures.cookie = hasCookies();
}
// screen resolution
// - only Apple reports screen.* in device-independent-pixels (dips)
// - devicePixelRatio is always 2 on MacOSX+Retina regardless of resolution set in Display Preferences
browserFeatures.res = screenAlias.width * devicePixelRatio + 'x' + screenAlias.height * devicePixelRatio;
}
/*<DEBUG>*/
/*
* Register a test hook. Using eval() permits access to otherwise
* privileged members.
*/
function registerHook(hookName, userHook) {
var hookObj = null;
if (isString(hookName) && !isDefined(registeredHooks[hookName]) && userHook) {
if (isObject(userHook)) {
hookObj = userHook;
} else if (isString(userHook)) {
try {
eval('hookObj =' + userHook);
} catch (ignore) { }
}
registeredHooks[hookName] = hookObj;
}
return hookObj;
}
/*</DEBUG>*/
/************************************************************
* Constructor
************************************************************/
/*
* initialize tracker
*/
detectBrowserFeatures();
updateDomainHash();
setVisitorIdCookie();
/*<DEBUG>*/
/*
* initialize test plugin
*/
executePluginMethod('run', registerHook);
/*</DEBUG>*/
/************************************************************
* Public data and methods
************************************************************/
return {
/*<DEBUG>*/
/*
* Test hook accessors
*/
hook: registeredHooks,
getHook: function (hookName) {
return registeredHooks[hookName];
},
getQuery: function () {
return query;
},
getContent: function () {
return content;
},
buildContentImpressionRequest: buildContentImpressionRequest,
buildContentInteractionRequest: buildContentInteractionRequest,
buildContentInteractionRequestNode: buildContentInteractionRequestNode,
buildContentInteractionTrackingRedirectUrl: buildContentInteractionTrackingRedirectUrl,
getContentImpressionsRequestsFromNodes: getContentImpressionsRequestsFromNodes,
getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet: getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet,
trackCallbackOnLoad: trackCallbackOnLoad,
trackCallbackOnReady: trackCallbackOnReady,
buildContentImpressionsRequests: buildContentImpressionsRequests,
wasContentImpressionAlreadyTracked: wasContentImpressionAlreadyTracked,
appendContentInteractionToRequestIfPossible: getContentInteractionToRequestIfPossible,
setupInteractionsTracking: setupInteractionsTracking,
trackContentImpressionClickInteraction: trackContentImpressionClickInteraction,
internalIsNodeVisible: isVisible,
isNodeAuthorizedToTriggerInteraction: isNodeAuthorizedToTriggerInteraction,
replaceHrefIfInternalLink: replaceHrefIfInternalLink,
getConfigDownloadExtensions: function () {
return configDownloadExtensions;
},
enableTrackOnlyVisibleContent: function (checkOnScroll, timeIntervalInMs) {
return enableTrackOnlyVisibleContent(checkOnScroll, timeIntervalInMs, this);
},
clearTrackedContentImpressions: function () {
trackedContentImpressions = [];
},
getTrackedContentImpressions: function () {
return trackedContentImpressions;
},
clearEnableTrackOnlyVisibleContent: function () {
isTrackOnlyVisibleContentEnabled = false;
},
disableLinkTracking: function () {
linkTrackingInstalled = false;
linkTrackingEnabled = false;
},
getConfigVisitorCookieTimeout: function () {
return configVisitorCookieTimeout;
},
getRemainingVisitorCookieTimeout: getRemainingVisitorCookieTimeout,
/*</DEBUG>*/
/**
* Get visitor ID (from first party cookie)
*
* @return string Visitor ID in hexits (or empty string, if not yet known)
*/
getVisitorId: function () {
return getValuesFromVisitorIdCookie().uuid;
},
/**
* Get the visitor information (from first party cookie)
*
* @return array
*/
getVisitorInfo: function () {
// Note: in a new method, we could return also return getValuesFromVisitorIdCookie()
// which returns named parameters rather than returning integer indexed array
return loadVisitorIdCookie();
},
/**
* Get the Attribution information, which is an array that contains
* the Referrer used to reach the site as well as the campaign name and keyword
* It is useful only when used in conjunction with Tracker API function setAttributionInfo()
* To access specific data point, you should use the other functions getAttributionReferrer* and getAttributionCampaign*
*
* @return array Attribution array, Example use:
* 1) Call JSON2.stringify(piwikTracker.getAttributionInfo())
* 2) Pass this json encoded string to the Tracking API (php or java client): setAttributionInfo()
*/
getAttributionInfo: function () {
return loadReferrerAttributionCookie();
},
/**
* Get the Campaign name that was parsed from the landing page URL when the visitor
* landed on the site originally
*
* @return string
*/
getAttributionCampaignName: function () {
return loadReferrerAttributionCookie()[0];
},
/**
* Get the Campaign keyword that was parsed from the landing page URL when the visitor
* landed on the site originally
*
* @return string
*/
getAttributionCampaignKeyword: function () {
return loadReferrerAttributionCookie()[1];
},
/**
* Get the time at which the referrer (used for Goal Attribution) was detected
*
* @return int Timestamp or 0 if no referrer currently set
*/
getAttributionReferrerTimestamp: function () {
return loadReferrerAttributionCookie()[2];
},
/**
* Get the full referrer URL that will be used for Goal Attribution
*
* @return string Raw URL, or empty string '' if no referrer currently set
*/
getAttributionReferrerUrl: function () {
return loadReferrerAttributionCookie()[3];
},
/**
* Specify the Piwik server URL
*
* @param string trackerUrl
*/
setTrackerUrl: function (trackerUrl) {
configTrackerUrl = trackerUrl;
},
/**
* Returns the Piwik server URL
* @returns string
*/
getTrackerUrl: function () {
return configTrackerUrl;
},
/**
* Returns the site ID
*
* @returns int
*/
getSiteId: function() {
return configTrackerSiteId;
},
/**
* Specify the site ID
*
* @param int|string siteId
*/
setSiteId: function (siteId) {
setSiteId(siteId);
},
/**
* Sets a User ID to this user (such as an email address or a username)
*
* @param string User ID
*/
setUserId: function (userId) {
if(!isDefined(userId) || !userId.length) {
return;
}
configUserId = userId;
visitorUUID = hash(configUserId).substr(0, 16);
},
/**
* Gets the User ID if set.
*
* @returns string User ID
*/
getUserId: function() {
return configUserId;
},
/**
* Pass custom data to the server
*
* Examples:
* tracker.setCustomData(object);
* tracker.setCustomData(key, value);
*
* @param mixed key_or_obj
* @param mixed opt_value
*/
setCustomData: function (key_or_obj, opt_value) {
if (isObject(key_or_obj)) {
configCustomData = key_or_obj;
} else {
if (!configCustomData) {
configCustomData = {};
}
configCustomData[key_or_obj] = opt_value;
}
},
/**
* Get custom data
*
* @return mixed
*/
getCustomData: function () {
return configCustomData;
},
/**
* Configure function with custom request content processing logic.
* It gets called after request content in form of query parameters string has been prepared and before request content gets sent.
*
* Examples:
* tracker.setCustomRequestProcessing(function(request){
* var pairs = request.split('&');
* var result = {};
* pairs.forEach(function(pair) {
* pair = pair.split('=');
* result[pair[0]] = decodeURIComponent(pair[1] || '');
* });
* return JSON.stringify(result);
* });
*
* @param function customRequestContentProcessingLogic
*/
setCustomRequestProcessing: function (customRequestContentProcessingLogic) {
configCustomRequestContentProcessing = customRequestContentProcessingLogic;
},
/**
* Appends the specified query string to the piwik.php?... Tracking API URL
*
* @param string queryString eg. 'lat=140&long=100'
*/
appendToTrackingUrl: function (queryString) {
configAppendToTrackingUrl = queryString;
},
/**
* Returns the query string for the current HTTP Tracking API request.
* Piwik would prepend the hostname and path to Piwik: http://example.org/piwik/piwik.php?
* prior to sending the request.
*
* @param request eg. "param=value¶m2=value2"
*/
getRequest: function (request) {
return getRequest(request);
},
/**
* Add plugin defined by a name and a callback function.
* The callback function will be called whenever a tracking request is sent.
* This can be used to append data to the tracking request, or execute other custom logic.
*
* @param string pluginName
* @param Object pluginObj
*/
addPlugin: function (pluginName, pluginObj) {
plugins[pluginName] = pluginObj;
},
/**
* Set custom variable within this visit
*
* @param int index Custom variable slot ID from 1-5
* @param string name
* @param string value
* @param string scope Scope of Custom Variable:
* - "visit" will store the name/value in the visit and will persist it in the cookie for the duration of the visit,
* - "page" will store the name/value in the next page view tracked.
* - "event" will store the name/value in the next event tracked.
*/
setCustomVariable: function (index, name, value, scope) {
var toRecord;
if (!isDefined(scope)) {
scope = 'visit';
}
if (!isDefined(name)) {
return;
}
if (!isDefined(value)) {
value = "";
}
if (index > 0) {
name = !isString(name) ? String(name) : name;
value = !isString(value) ? String(value) : value;
toRecord = [name.slice(0, customVariableMaximumLength), value.slice(0, customVariableMaximumLength)];
// numeric scope is there for GA compatibility
if (scope === 'visit' || scope === 2) {
loadCustomVariables();
customVariables[index] = toRecord;
} else if (scope === 'page' || scope === 3) {
customVariablesPage[index] = toRecord;
} else if (scope === 'event') { /* GA does not have 'event' scope but we do */
customVariablesEvent[index] = toRecord;
}
}
},
/**
* Get custom variable
*
* @param int index Custom variable slot ID from 1-5
* @param string scope Scope of Custom Variable: "visit" or "page" or "event"
*/
getCustomVariable: function (index, scope) {
var cvar;
if (!isDefined(scope)) {
scope = "visit";
}
if (scope === "page" || scope === 3) {
cvar = customVariablesPage[index];
} else if (scope === "event") {
cvar = customVariablesEvent[index];
} else if (scope === "visit" || scope === 2) {
loadCustomVariables();
cvar = customVariables[index];
}
if (!isDefined(cvar)
|| (cvar && cvar[0] === '')) {
return false;
}
return cvar;
},
/**
* Delete custom variable
*
* @param int index Custom variable slot ID from 1-5
*/
deleteCustomVariable: function (index, scope) {
// Only delete if it was there already
if (this.getCustomVariable(index, scope)) {
this.setCustomVariable(index, '', '', scope);
}
},
/**
* When called then the Custom Variables of scope "visit" will be stored (persisted) in a first party cookie
* for the duration of the visit. This is useful if you want to call getCustomVariable later in the visit.
*
* By default, Custom Variables of scope "visit" are not stored on the visitor's computer.
*/
storeCustomVariablesInCookie: function () {
configStoreCustomVariablesInCookie = true;
},
/**
* Set delay for link tracking (in milliseconds)
*
* @param int delay
*/
setLinkTrackingTimer: function (delay) {
configTrackerPause = delay;
},
/**
* Set list of file extensions to be recognized as downloads
*
* @param string|array extensions
*/
setDownloadExtensions: function (extensions) {
if(isString(extensions)) {
extensions = extensions.split('|');
}
configDownloadExtensions = extensions;
},
/**
* Specify additional file extensions to be recognized as downloads
*
* @param string|array extensions for example 'custom' or ['custom1','custom2','custom3']
*/
addDownloadExtensions: function (extensions) {
var i;
if(isString(extensions)) {
extensions = extensions.split('|');
}
for (i=0; i < extensions.length; i++) {
configDownloadExtensions.push(extensions[i]);
}
},
/**
* Removes specified file extensions from the list of recognized downloads
*
* @param string|array extensions for example 'custom' or ['custom1','custom2','custom3']
*/
removeDownloadExtensions: function (extensions) {
var i, newExtensions = [];
if(isString(extensions)) {
extensions = extensions.split('|');
}
for (i=0; i < configDownloadExtensions.length; i++) {
if (indexOfArray(extensions, configDownloadExtensions[i]) === -1) {
newExtensions.push(configDownloadExtensions[i]);
}
}
configDownloadExtensions = newExtensions;
},
/**
* Set array of domains to be treated as local
*
* @param string|array hostsAlias
*/
setDomains: function (hostsAlias) {
configHostsAlias = isString(hostsAlias) ? [hostsAlias] : hostsAlias;
configHostsAlias.push(domainAlias);
},
/**
* Set array of classes to be ignored if present in link
*
* @param string|array ignoreClasses
*/
setIgnoreClasses: function (ignoreClasses) {
configIgnoreClasses = isString(ignoreClasses) ? [ignoreClasses] : ignoreClasses;
},
/**
* Set request method
*
* @param string method GET or POST; default is GET
*/
setRequestMethod: function (method) {
configRequestMethod = method || defaultRequestMethod;
},
/**
* Set request Content-Type header value, applicable when POST request method is used for submitting tracking events.
* See XMLHttpRequest Level 2 spec, section 4.7.2 for invalid headers
* @link http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html
*
* @param string requestContentType; default is 'application/x-www-form-urlencoded; charset=UTF-8'
*/
setRequestContentType: function (requestContentType) {
configRequestContentType = requestContentType || defaultRequestContentType;
},
/**
* Override referrer
*
* @param string url
*/
setReferrerUrl: function (url) {
configReferrerUrl = url;
},
/**
* Override url
*
* @param string url
*/
setCustomUrl: function (url) {
configCustomUrl = resolveRelativeReference(locationHrefAlias, url);
},
/**
* Override document.title
*
* @param string title
*/
setDocumentTitle: function (title) {
configTitle = title;
},
/**
* Set the URL of the Piwik API. It is used for Page Overlay.
* This method should only be called when the API URL differs from the tracker URL.
*
* @param string apiUrl
*/
setAPIUrl: function (apiUrl) {
configApiUrl = apiUrl;
},
/**
* Set array of classes to be treated as downloads
*
* @param string|array downloadClasses
*/
setDownloadClasses: function (downloadClasses) {
configDownloadClasses = isString(downloadClasses) ? [downloadClasses] : downloadClasses;
},
/**
* Set array of classes to be treated as outlinks
*
* @param string|array linkClasses
*/
setLinkClasses: function (linkClasses) {
configLinkClasses = isString(linkClasses) ? [linkClasses] : linkClasses;
},
/**
* Set array of campaign name parameters
*
* @see http://piwik.org/faq/how-to/#faq_120
* @param string|array campaignNames
*/
setCampaignNameKey: function (campaignNames) {
configCampaignNameParameters = isString(campaignNames) ? [campaignNames] : campaignNames;
},
/**
* Set array of campaign keyword parameters
*
* @see http://piwik.org/faq/how-to/#faq_120
* @param string|array campaignKeywords
*/
setCampaignKeywordKey: function (campaignKeywords) {
configCampaignKeywordParameters = isString(campaignKeywords) ? [campaignKeywords] : campaignKeywords;
},
/**
* Strip hash tag (or anchor) from URL
* Note: this can be done in the Piwik>Settings>Websites on a per-website basis
*
* @deprecated
* @param bool enableFilter
*/
discardHashTag: function (enableFilter) {
configDiscardHashTag = enableFilter;
},
/**
* Set first-party cookie name prefix
*
* @param string cookieNamePrefix
*/
setCookieNamePrefix: function (cookieNamePrefix) {
configCookieNamePrefix = cookieNamePrefix;
// Re-init the Custom Variables cookie
customVariables = getCustomVariablesFromCookie();
},
/**
* Set first-party cookie domain
*
* @param string domain
*/
setCookieDomain: function (domain) {
var domainFixed = domainFixup(domain);
if (isPossibleToSetCookieOnDomain(domainFixed)) {
configCookieDomain = domainFixed;
updateDomainHash();
}
},
/**
* Set first-party cookie path
*
* @param string domain
*/
setCookiePath: function (path) {
configCookiePath = path;
updateDomainHash();
},
/**
* Set visitor cookie timeout (in seconds)
* Defaults to 13 months (timeout=33955200)
*
* @param int timeout
*/
setVisitorCookieTimeout: function (timeout) {
configVisitorCookieTimeout = timeout * 1000;
},
/**
* Set session cookie timeout (in seconds).
* Defaults to 30 minutes (timeout=1800000)
*
* @param int timeout
*/
setSessionCookieTimeout: function (timeout) {
configSessionCookieTimeout = timeout * 1000;
},
/**
* Set referral cookie timeout (in seconds).
* Defaults to 6 months (15768000000)
*
* @param int timeout
*/
setReferralCookieTimeout: function (timeout) {
configReferralCookieTimeout = timeout * 1000;
},
/**
* Set conversion attribution to first referrer and campaign
*
* @param bool if true, use first referrer (and first campaign)
* if false, use the last referrer (or campaign)
*/
setConversionAttributionFirstReferrer: function (enable) {
configConversionAttributionFirstReferrer = enable;
},
/**
* Disables all cookies from being set
*
* Existing cookies will be deleted on the next call to track
*/
disableCookies: function () {
configCookiesDisabled = true;
browserFeatures.cookie = '0';
},
/**
* One off cookies clearing. Useful to call this when you know for sure a new visitor is using the same browser,
* it maybe helps to "reset" tracking cookies to prevent data reuse for different users.
*/
deleteCookies: function () {
deleteCookies();
},
/**
* Handle do-not-track requests
*
* @param bool enable If true, don't track if user agent sends 'do-not-track' header
*/
setDoNotTrack: function (enable) {
var dnt = navigatorAlias.doNotTrack || navigatorAlias.msDoNotTrack;
configDoNotTrack = enable && (dnt === 'yes' || dnt === '1');
// do not track also disables cookies and deletes existing cookies
if (configDoNotTrack) {
this.disableCookies();
}
},
/**
* Add click listener to a specific link element.
* When clicked, Piwik will log the click automatically.
*
* @param DOMElement element
* @param bool enable If true, use pseudo click-handler (mousedown+mouseup)
*/
addListener: function (element, enable) {
addClickListener(element, enable);
},
/**
* Install link tracker
*
* The default behaviour is to use actual click events. However, some browsers
* (e.g., Firefox, Opera, and Konqueror) don't generate click events for the middle mouse button.
*
* To capture more "clicks", the pseudo click-handler uses mousedown + mouseup events.
* This is not industry standard and is vulnerable to false positives (e.g., drag events).
*
* There is a Safari/Chrome/Webkit bug that prevents tracking requests from being sent
* by either click handler. The workaround is to set a target attribute (which can't
* be "_self", "_top", or "_parent").
*
* @see https://bugs.webkit.org/show_bug.cgi?id=54783
*
* @param bool enable If true, use pseudo click-handler (mousedown+mouseup)
*/
enableLinkTracking: function (enable) {
linkTrackingEnabled = true;
if (hasLoaded) {
// the load event has already fired, add the click listeners now
addClickListeners(enable);
} else {
// defer until page has loaded
registeredOnLoadHandlers.push(function () {
addClickListeners(enable);
});
}
},
/**
* Enable tracking of uncatched JavaScript errors
*
* If enabled, uncaught JavaScript Errors will be tracked as an event by defining a
* window.onerror handler. If a window.onerror handler is already defined we will make
* sure to call this previously registered error handler after tracking the error.
*
* By default we return false in the window.onerror handler to make sure the error still
* appears in the browser's console etc. Note: Some older browsers might behave differently
* so it could happen that an actual JavaScript error will be suppressed.
* If a window.onerror handler was registered we will return the result of this handler.
*
* Make sure not to overwrite the window.onerror handler after enabling the JS error
* tracking as the error tracking won't work otherwise. To capture all JS errors we
* recommend to include the Piwik JavaScript tracker in the HTML as early as possible.
* If possible directly in <head></head> before loading any other JavaScript.
*/
enableJSErrorTracking: function () {
if (enableJSErrorTracking) {
return;
}
enableJSErrorTracking = true;
var onError = windowAlias.onerror;
windowAlias.onerror = function (message, url, linenumber, column, error) {
trackCallback(function () {
var category = 'JavaScript Errors';
var action = url + ':' + linenumber;
if (column) {
action += ':' + column;
}
logEvent(category, action, message);
});
if (onError) {
return onError(message, url, linenumber, column, error);
}
return false;
};
},
/**
* Disable automatic performance tracking
*/
disablePerformanceTracking: function () {
configPerformanceTrackingEnabled = false;
},
/**
* Set the server generation time.
* If set, the browser's performance.timing API in not used anymore to determine the time.
*
* @param int generationTime
*/
setGenerationTimeMs: function (generationTime) {
configPerformanceGenerationTime = parseInt(generationTime, 10);
},
/**
* Set heartbeat (in seconds)
*
* @param int minimumVisitLength
* @param int heartBeatDelay
*/
setHeartBeatTimer: function (minimumVisitLength, heartBeatDelay) {
var now = new Date();
configMinimumVisitTime = now.getTime() + minimumVisitLength * 1000;
configHeartBeatTimer = heartBeatDelay * 1000;
},
/**
* Frame buster
*/
killFrame: function () {
if (windowAlias.location !== windowAlias.top.location) {
windowAlias.top.location = windowAlias.location;
}
},
/**
* Redirect if browsing offline (aka file: buster)
*
* @param string url Redirect to this URL
*/
redirectFile: function (url) {
if (windowAlias.location.protocol === 'file:') {
windowAlias.location = url;
}
},
/**
* Count sites in pre-rendered state
*
* @param bool enable If true, track when in pre-rendered state
*/
setCountPreRendered: function (enable) {
configCountPreRendered = enable;
},
/**
* Trigger a goal
*
* @param int|string idGoal
* @param int|float customRevenue
* @param mixed customData
*/
trackGoal: function (idGoal, customRevenue, customData) {
trackCallback(function () {
logGoal(idGoal, customRevenue, customData);
});
},
/**
* Manually log a click from your own code
*
* @param string sourceUrl
* @param string linkType
* @param mixed customData
* @param function callback
*/
trackLink: function (sourceUrl, linkType, customData, callback) {
trackCallback(function () {
logLink(sourceUrl, linkType, customData, callback);
});
},
/**
* Log visit to this page
*
* @param string customTitle
* @param mixed customData
*/
trackPageView: function (customTitle, customData) {
trackedContentImpressions = [];
if (isOverlaySession(configTrackerSiteId)) {
trackCallback(function () {
injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId);
});
} else {
trackCallback(function () {
logPageView(customTitle, customData);
});
}
},
/**
* Scans the entire DOM for all content blocks and tracks all impressions once the DOM ready event has
* been triggered.
*
* If you only want to track visible content impressions have a look at `trackVisibleContentImpressions()`.
* We do not track an impression of the same content block twice if you call this method multiple times
* unless `trackPageView()` is called meanwhile. This is useful for single page applications.
*/
trackAllContentImpressions: function () {
if (isOverlaySession(configTrackerSiteId)) {
return;
}
trackCallback(function () {
trackCallbackOnReady(function () {
// we have to wait till DOM ready
var contentNodes = content.findContentNodes();
var requests = getContentImpressionsRequestsFromNodes(contentNodes);
sendBulkRequest(requests, configTrackerPause);
});
});
},
/**
* Scans the entire DOM for all content blocks as soon as the page is loaded. It tracks an impression
* only if a content block is actually visible. Meaning it is not hidden and the content is or was at
* some point in the viewport.
*
* If you want to track all content blocks have a look at `trackAllContentImpressions()`.
* We do not track an impression of the same content block twice if you call this method multiple times
* unless `trackPageView()` is called meanwhile. This is useful for single page applications.
*
* Once you have called this method you can no longer change `checkOnScroll` or `timeIntervalInMs`.
*
* If you do want to only track visible content blocks but not want us to perform any automatic checks
* as they can slow down your frames per second you can call `trackVisibleContentImpressions()` or
* `trackContentImpressionsWithinNode()` manually at any time to rescan the entire DOM for newly
* visible content blocks.
* o Call `trackVisibleContentImpressions(false, 0)` to initially track only visible content impressions
* o Call `trackVisibleContentImpressions()` at any time again to rescan the entire DOM for newly visible content blocks or
* o Call `trackContentImpressionsWithinNode(node)` at any time to rescan only a part of the DOM for newly visible content blocks
*
* @param boolean [checkOnScroll=true] Optional, you can disable rescanning the entire DOM automatically
* after each scroll event by passing the value `false`. If enabled,
* we check whether a previously hidden content blocks became visible
* after a scroll and if so track the impression.
* Note: If a content block is placed within a scrollable element
* (`overflow: scroll`), we can currently not detect when this block
* becomes visible.
* @param integer [timeIntervalInMs=750] Optional, you can define an interval to rescan the entire DOM
* for new impressions every X milliseconds by passing
* for instance `timeIntervalInMs=500` (rescan DOM every 500ms).
* Rescanning the entire DOM and detecting the visible state of content
* blocks can take a while depending on the browser and amount of content.
* In case your frames per second goes down you might want to increase
* this value or disable it by passing the value `0`.
*/
trackVisibleContentImpressions: function (checkOnSroll, timeIntervalInMs) {
if (isOverlaySession(configTrackerSiteId)) {
return;
}
if (!isDefined(checkOnSroll)) {
checkOnSroll = true;
}
if (!isDefined(timeIntervalInMs)) {
timeIntervalInMs = 750;
}
enableTrackOnlyVisibleContent(checkOnSroll, timeIntervalInMs, this);
trackCallback(function () {
trackCallbackOnLoad(function () {
// we have to wait till CSS parsed and applied
var contentNodes = content.findContentNodes();
var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes);
sendBulkRequest(requests, configTrackerPause);
});
});
},
/**
* Tracks a content impression using the specified values. You should not call this method too often
* as each call causes an XHR tracking request and can slow down your site or your server.
*
* @param string contentName For instance "Ad Sale".
* @param string [contentPiece='Unknown'] For instance a path to an image or the text of a text ad.
* @param string [contentTarget] For instance the URL of a landing page.
*/
trackContentImpression: function (contentName, contentPiece, contentTarget) {
if (isOverlaySession(configTrackerSiteId)) {
return;
}
if (!contentName) {
return;
}
contentPiece = contentPiece || 'Unknown';
trackCallback(function () {
var request = buildContentImpressionRequest(contentName, contentPiece, contentTarget);
sendRequest(request, configTrackerPause);
});
},
/**
* Scans the given DOM node and its children for content blocks and tracks an impression for them if
* no impression was already tracked for it. If you have called `trackVisibleContentImpressions()`
* upfront only visible content blocks will be tracked. You can use this method if you, for instance,
* dynamically add an element using JavaScript to your DOM after we have tracked the initial impressions.
*
* @param Element domNode
*/
trackContentImpressionsWithinNode: function (domNode) {
if (isOverlaySession(configTrackerSiteId) || !domNode) {
return;
}
trackCallback(function () {
if (isTrackOnlyVisibleContentEnabled) {
trackCallbackOnLoad(function () {
// we have to wait till CSS parsed and applied
var contentNodes = content.findContentNodesWithinNode(domNode);
var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes);
sendBulkRequest(requests, configTrackerPause);
});
} else {
trackCallbackOnReady(function () {
// we have to wait till DOM ready
var contentNodes = content.findContentNodesWithinNode(domNode);
var requests = getContentImpressionsRequestsFromNodes(contentNodes);
sendBulkRequest(requests, configTrackerPause);
});
}
});
},
/**
* Tracks a content interaction using the specified values. You should use this method only in conjunction
* with `trackContentImpression()`. The specified `contentName` and `contentPiece` has to be exactly the
* same as the ones that were used in `trackContentImpression()`. Otherwise the interaction will not count.
*
* @param string contentInteraction The type of interaction that happened. For instance 'click' or 'submit'.
* @param string contentName The name of the content. For instance "Ad Sale".
* @param string [contentPiece='Unknown'] The actual content. For instance a path to an image or the text of a text ad.
* @param string [contentTarget] For instance the URL of a landing page.
*/
trackContentInteraction: function (contentInteraction, contentName, contentPiece, contentTarget) {
if (isOverlaySession(configTrackerSiteId)) {
return;
}
if (!contentInteraction || !contentName) {
return;
}
contentPiece = contentPiece || 'Unknown';
trackCallback(function () {
var request = buildContentInteractionRequest(contentInteraction, contentName, contentPiece, contentTarget);
sendRequest(request, configTrackerPause);
});
},
/**
* Tracks an interaction with the given DOM node / content block.
*
* By default we track interactions on click but sometimes you might want to track interactions yourself.
* For instance you might want to track an interaction manually on a double click or a form submit.
* Make sure to disable the automatic interaction tracking in this case by specifying either the CSS
* class `piwikContentIgnoreInteraction` or the attribute `data-content-ignoreinteraction`.
*
* @param Element domNode This element itself or any of its parent elements has to be a content block
* element. Meaning one of those has to have a `piwikTrackContent` CSS class or
* a `data-track-content` attribute.
* @param string [contentInteraction='Unknown] The name of the interaction that happened. For instance
* 'click', 'formSubmit', 'DblClick', ...
*/
trackContentInteractionNode: function (domNode, contentInteraction) {
if (isOverlaySession(configTrackerSiteId) || !domNode) {
return;
}
trackCallback(function () {
var request = buildContentInteractionRequestNode(domNode, contentInteraction);
sendRequest(request, configTrackerPause);
});
},
/**
* Records an event
*
* @param string category The Event Category (Videos, Music, Games...)
* @param string action The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)
* @param string name (optional) The Event's object Name (a particular Movie name, or Song name, or File name...)
* @param float value (optional) The Event's value
*/
trackEvent: function (category, action, name, value) {
trackCallback(function () {
logEvent(category, action, name, value);
});
},
/**
* Log special pageview: Internal search
*
* @param string keyword
* @param string category
* @param int resultsCount
*/
trackSiteSearch: function (keyword, category, resultsCount) {
trackCallback(function () {
logSiteSearch(keyword, category, resultsCount);
});
},
/**
* Used to record that the current page view is an item (product) page view, or a Ecommerce Category page view.
* This must be called before trackPageView() on the product/category page.
* It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view.
* Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used.
*
* On a category page, you can set the parameter category, and set the other parameters to empty string or false
*
* Tracking Product/Category page views will allow Piwik to report on Product & Categories
* conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)
*
* @param string sku Item's SKU code being viewed
* @param string name Item's Name being viewed
* @param string category Category page being viewed. On an Item's page, this is the item's category
* @param float price Item's display price, not use in standard Piwik reports, but output in API product reports.
*/
setEcommerceView: function (sku, name, category, price) {
if (!isDefined(category) || !category.length) {
category = "";
} else if (category instanceof Array) {
category = JSON2.stringify(category);
}
customVariablesPage[5] = ['_pkc', category];
if (isDefined(price) && String(price).length) {
customVariablesPage[2] = ['_pkp', price];
}
// On a category page, do not track Product name not defined
if ((!isDefined(sku) || !sku.length)
&& (!isDefined(name) || !name.length)) {
return;
}
if (isDefined(sku) && sku.length) {
customVariablesPage[3] = ['_pks', sku];
}
if (!isDefined(name) || !name.length) {
name = "";
}
customVariablesPage[4] = ['_pkn', name];
},
/**
* Adds an item (product) that is in the current Cart or in the Ecommerce order.
* This function is called for every item (product) in the Cart or the Order.
* The only required parameter is sku.
*
* @param string sku (required) Item's SKU Code. This is the unique identifier for the product.
* @param string name (optional) Item's name
* @param string name (optional) Item's category, or array of up to 5 categories
* @param float price (optional) Item's price. If not specified, will default to 0
* @param float quantity (optional) Item's quantity. If not specified, will default to 1
*/
addEcommerceItem: function (sku, name, category, price, quantity) {
if (sku.length) {
ecommerceItems[sku] = [ sku, name, category, price, quantity ];
}
},
/**
* Tracks an Ecommerce order.
* If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order.
* All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Piwik reports.
* Parameters orderId and grandTotal are required. For others, you can set to false if you don't need to specify them.
*
* @param string|int orderId (required) Unique Order ID.
* This will be used to count this order only once in the event the order page is reloaded several times.
* orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Piwik.
* @param float grandTotal (required) Grand Total revenue of the transaction (including tax, shipping, etc.)
* @param float subTotal (optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied)
* @param float tax (optional) Tax amount for this order
* @param float shipping (optional) Shipping amount for this order
* @param float discount (optional) Discounted amount in this order
*/
trackEcommerceOrder: function (orderId, grandTotal, subTotal, tax, shipping, discount) {
logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount);
},
/**
* Tracks a Cart Update (add item, remove item, update item).
* On every Cart update, you must call addEcommerceItem() for each item (product) in the cart, including the items that haven't been updated since the last cart update.
* Then you can call this function with the Cart grandTotal (typically the sum of all items' prices)
*
* @param float grandTotal (required) Items (products) amount in the Cart
*/
trackEcommerceCartUpdate: function (grandTotal) {
logEcommerceCartUpdate(grandTotal);
}
};
}
/************************************************************
* Proxy object
* - this allows the caller to continue push()'ing to _paq
* after the Tracker has been initialized and loaded
************************************************************/
function TrackerProxy() {
return {
push: apply
};
}
/************************************************************
* Constructor
************************************************************/
// initialize the Piwik singleton
addEventListener(windowAlias, 'beforeunload', beforeUnloadHandler, false);
addReadyListener();
Date.prototype.getTimeAlias = Date.prototype.getTime;
asyncTracker = new Tracker();
var applyFirst = {setTrackerUrl: 1, setAPIUrl: 1, setUserId: 1, setSiteId: 1, disableCookies: 1, enableLinkTracking: 1};
var methodName;
// find the call to setTrackerUrl or setSiteid (if any) and call them first
for (iterator = 0; iterator < _paq.length; iterator++) {
methodName = _paq[iterator][0];
if (applyFirst[methodName]) {
apply(_paq[iterator]);
delete _paq[iterator];
if (applyFirst[methodName] > 1) {
if (console !== undefined && console && console.error) {
console.error('The method ' + methodName + ' is registered more than once in "_paq" variable. Only the last call has an effect. Please have a look at the multiple Piwik trackers documentation: http://developer.piwik.org/guides/tracking-javascript-guide#multiple-piwik-trackers');
}
}
applyFirst[methodName]++;
}
}
// apply the queue of actions
for (iterator = 0; iterator < _paq.length; iterator++) {
if (_paq[iterator]) {
apply(_paq[iterator]);
}
}
// replace initialization array with proxy object
_paq = new TrackerProxy();
/************************************************************
* Public data and methods
************************************************************/
Piwik = {
/**
* Add plugin
*
* @param string pluginName
* @param Object pluginObj
*/
addPlugin: function (pluginName, pluginObj) {
plugins[pluginName] = pluginObj;
},
/**
* Get Tracker (factory method)
*
* @param string piwikUrl
* @param int|string siteId
* @return Tracker
*/
getTracker: function (piwikUrl, siteId) {
if(!isDefined(siteId)) {
siteId = this.getAsyncTracker().getSiteId();
}
if(!isDefined(piwikUrl)) {
piwikUrl = this.getAsyncTracker().getTrackerUrl();
}
return new Tracker(piwikUrl, siteId);
},
/**
* Get internal asynchronous tracker object
*
* @return Tracker
*/
getAsyncTracker: function () {
return asyncTracker;
}
};
// Expose Piwik as an AMD module
if (typeof define === 'function' && define.amd) {
define('piwik', [], function () { return Piwik; });
}
return Piwik;
}());
}
if (window && window.piwikAsyncInit) {
window.piwikAsyncInit();
}
/*jslint sloppy: true */
(function () {
var jsTrackerType = (typeof AnalyticsTracker);
if (jsTrackerType === 'undefined') {
AnalyticsTracker = Piwik;
}
}());
/*jslint sloppy: false */
/************************************************************
* Deprecated functionality below
* Legacy piwik.js compatibility ftw
************************************************************/
/*
* Piwik globals
*
* var piwik_install_tracker, piwik_tracker_pause, piwik_download_extensions, piwik_hosts_alias, piwik_ignore_classes;
*/
/*global piwik_log:true */
/*global piwik_track:true */
/**
* Track page visit
*
* @param string documentTitle
* @param int|string siteId
* @param string piwikUrl
* @param mixed customData
*/
if (typeof piwik_log !== 'function') {
piwik_log = function (documentTitle, siteId, piwikUrl, customData) {
'use strict';
function getOption(optionName) {
try {
return eval('piwik_' + optionName);
} catch (ignore) { }
return; // undefined
}
// instantiate the tracker
var option,
piwikTracker = Piwik.getTracker(piwikUrl, siteId);
// initialize tracker
piwikTracker.setDocumentTitle(documentTitle);
piwikTracker.setCustomData(customData);
// handle Piwik globals
option = getOption('tracker_pause');
if (option) {
piwikTracker.setLinkTrackingTimer(option);
}
option = getOption('download_extensions');
if (option) {
piwikTracker.setDownloadExtensions(option);
}
option = getOption('hosts_alias');
if (option) {
piwikTracker.setDomains(option);
}
option = getOption('ignore_classes');
if (option) {
piwikTracker.setIgnoreClasses(option);
}
// track this page view
piwikTracker.trackPageView();
// default is to install the link tracker
if (getOption('install_tracker')) {
/**
* Track click manually (function is defined below)
*
* @param string sourceUrl
* @param int|string siteId
* @param string piwikUrl
* @param string linkType
*/
piwik_track = function (sourceUrl, siteId, piwikUrl, linkType) {
piwikTracker.setSiteId(siteId);
piwikTracker.setTrackerUrl(piwikUrl);
piwikTracker.trackLink(sourceUrl, linkType);
};
// set-up link tracking
piwikTracker.enableLinkTracking();
}
};
}
/*! @license-end */
|
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "1");
design.checkVersion("zrf", "3.0");
design.checkVersion("smart-moves", "from");
design.checkVersion("sliding-puzzle", "true");
design.addDirection("w");
design.addDirection("e");
design.addDirection("s");
design.addDirection("n");
design.addPlayer("You", [1, 0, 3, 2]);
design.addPosition("a6", [0, 1, 6, 0]);
design.addPosition("b6", [-1, 1, 6, 0]);
design.addPosition("c6", [-1, 1, 6, 0]);
design.addPosition("d6", [-1, 1, 6, 0]);
design.addPosition("e6", [-1, 1, 6, 0]);
design.addPosition("f6", [-1, 0, 6, 0]);
design.addPosition("a5", [0, 1, 6, -6]);
design.addPosition("b5", [-1, 1, 6, -6]);
design.addPosition("c5", [-1, 1, 6, -6]);
design.addPosition("d5", [-1, 1, 6, -6]);
design.addPosition("e5", [-1, 1, 6, -6]);
design.addPosition("f5", [-1, 0, 6, -6]);
design.addPosition("a4", [0, 1, 6, -6]);
design.addPosition("b4", [-1, 1, 6, -6]);
design.addPosition("c4", [-1, 1, 6, -6]);
design.addPosition("d4", [-1, 1, 6, -6]);
design.addPosition("e4", [-1, 1, 6, -6]);
design.addPosition("f4", [-1, 0, 6, -6]);
design.addPosition("a3", [0, 1, 6, -6]);
design.addPosition("b3", [-1, 1, 6, -6]);
design.addPosition("c3", [-1, 1, 6, -6]);
design.addPosition("d3", [-1, 1, 6, -6]);
design.addPosition("e3", [-1, 1, 6, -6]);
design.addPosition("f3", [-1, 0, 6, -6]);
design.addPosition("a2", [0, 1, 6, -6]);
design.addPosition("b2", [-1, 1, 6, -6]);
design.addPosition("c2", [-1, 1, 6, -6]);
design.addPosition("d2", [-1, 1, 6, -6]);
design.addPosition("e2", [-1, 1, 6, -6]);
design.addPosition("f2", [-1, 0, 6, -6]);
design.addPosition("a1", [0, 1, 0, -6]);
design.addPosition("b1", [-1, 1, 0, -6]);
design.addPosition("c1", [-1, 1, 0, -6]);
design.addPosition("d1", [-1, 1, 0, -6]);
design.addPosition("e1", [-1, 1, 0, -6]);
design.addPosition("f1", [-1, 0, 0, -6]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addPiece("R0110F1", 0);
design.addAttribute(0, 0, 1);
design.addAttribute(0, 1, 'R0110F');
design.addMove(0, 0, [3], 0);
design.addMove(0, 0, [2], 0);
design.addMove(0, 0, [0], 0);
design.addMove(0, 0, [1], 0);
design.addPiece("R1010F1", 1);
design.addAttribute(1, 0, 1);
design.addAttribute(1, 1, 'R1010F');
design.addMove(1, 0, [3], 0);
design.addMove(1, 0, [2], 0);
design.addMove(1, 0, [0], 0);
design.addMove(1, 0, [1], 0);
design.addPiece("R0101F1", 2);
design.addAttribute(2, 0, 1);
design.addAttribute(2, 1, 'R0101F');
design.addMove(2, 0, [3], 0);
design.addMove(2, 0, [2], 0);
design.addMove(2, 0, [0], 0);
design.addMove(2, 0, [1], 0);
design.addPiece("R1001F1", 3);
design.addAttribute(3, 0, 1);
design.addAttribute(3, 1, 'R1001F');
design.addMove(3, 0, [3], 0);
design.addMove(3, 0, [2], 0);
design.addMove(3, 0, [0], 0);
design.addMove(3, 0, [1], 0);
design.addPiece("B01002", 4);
design.addAttribute(4, 0, 2);
design.addAttribute(4, 1, 'B0100');
design.addMove(4, 0, [3], 0);
design.addMove(4, 0, [2], 0);
design.addMove(4, 0, [0], 0);
design.addMove(4, 0, [1], 0);
design.addPiece("B10002", 5);
design.addAttribute(5, 0, 2);
design.addAttribute(5, 1, 'B1000');
design.addMove(5, 0, [3], 0);
design.addMove(5, 0, [2], 0);
design.addMove(5, 0, [0], 0);
design.addMove(5, 0, [1], 0);
design.addPiece("B00103", 6);
design.addAttribute(6, 0, 3);
design.addAttribute(6, 1, 'B0010');
design.addMove(6, 0, [3], 0);
design.addMove(6, 0, [2], 0);
design.addMove(6, 0, [0], 0);
design.addMove(6, 0, [1], 0);
design.addPiece("B00013", 7);
design.addAttribute(7, 0, 3);
design.addAttribute(7, 1, 'B0001');
design.addMove(7, 0, [3], 0);
design.addMove(7, 0, [2], 0);
design.addMove(7, 0, [0], 0);
design.addMove(7, 0, [1], 0);
design.addPiece("B00104", 8);
design.addAttribute(8, 0, 4);
design.addAttribute(8, 1, 'B0010');
design.addMove(8, 0, [3], 0);
design.addMove(8, 0, [2], 0);
design.addMove(8, 0, [0], 0);
design.addMove(8, 0, [1], 0);
design.addPiece("B00014", 9);
design.addAttribute(9, 0, 4);
design.addAttribute(9, 1, 'B0001');
design.addMove(9, 0, [3], 0);
design.addMove(9, 0, [2], 0);
design.addMove(9, 0, [0], 0);
design.addMove(9, 0, [1], 0);
design.addPiece("B01005", 10);
design.addAttribute(10, 0, 5);
design.addAttribute(10, 1, 'B0100');
design.addMove(10, 0, [3], 0);
design.addMove(10, 0, [2], 0);
design.addMove(10, 0, [0], 0);
design.addMove(10, 0, [1], 0);
design.addPiece("B10005", 11);
design.addAttribute(11, 0, 5);
design.addAttribute(11, 1, 'B1000');
design.addMove(11, 0, [3], 0);
design.addMove(11, 0, [2], 0);
design.addMove(11, 0, [0], 0);
design.addMove(11, 0, [1], 0);
design.addPiece("B00006", 12);
design.addAttribute(12, 0, 6);
design.addAttribute(12, 1, 'B0000');
design.addMove(12, 0, [3], 0);
design.addMove(12, 0, [2], 0);
design.addMove(12, 0, [0], 0);
design.addMove(12, 0, [1], 0);
design.addPiece("B00007", 13);
design.addAttribute(13, 0, 7);
design.addAttribute(13, 1, 'B0000');
design.addMove(13, 0, [3], 0);
design.addMove(13, 0, [2], 0);
design.addMove(13, 0, [0], 0);
design.addMove(13, 0, [1], 0);
design.addPiece("B0110F8", 14);
design.addAttribute(14, 0, 8);
design.addAttribute(14, 1, 'B0110F');
design.addMove(14, 0, [3], 0);
design.addMove(14, 0, [2], 0);
design.addMove(14, 0, [0], 0);
design.addMove(14, 0, [1], 0);
design.addPiece("B1010F8", 15);
design.addAttribute(15, 0, 8);
design.addAttribute(15, 1, 'B1010F');
design.addMove(15, 0, [3], 0);
design.addMove(15, 0, [2], 0);
design.addMove(15, 0, [0], 0);
design.addMove(15, 0, [1], 0);
design.addPiece("B0101F8", 16);
design.addAttribute(16, 0, 8);
design.addAttribute(16, 1, 'B0101F');
design.addMove(16, 0, [3], 0);
design.addMove(16, 0, [2], 0);
design.addMove(16, 0, [0], 0);
design.addMove(16, 0, [1], 0);
design.addPiece("B1001F8", 17);
design.addAttribute(17, 0, 8);
design.addAttribute(17, 1, 'B1001F');
design.addMove(17, 0, [3], 0);
design.addMove(17, 0, [2], 0);
design.addMove(17, 0, [0], 0);
design.addMove(17, 0, [1], 0);
design.addPiece("B01009", 18);
design.addAttribute(18, 0, 9);
design.addAttribute(18, 1, 'B0100');
design.addMove(18, 0, [3], 0);
design.addMove(18, 0, [2], 0);
design.addMove(18, 0, [0], 0);
design.addMove(18, 0, [1], 0);
design.addPiece("B10009", 19);
design.addAttribute(19, 0, 9);
design.addAttribute(19, 1, 'B1000');
design.addMove(19, 0, [3], 0);
design.addMove(19, 0, [2], 0);
design.addMove(19, 0, [0], 0);
design.addMove(19, 0, [1], 0);
design.addPiece("B010010", 20);
design.addAttribute(20, 0, 10);
design.addAttribute(20, 1, 'B0100');
design.addMove(20, 0, [3], 0);
design.addMove(20, 0, [2], 0);
design.addMove(20, 0, [0], 0);
design.addMove(20, 0, [1], 0);
design.addPiece("B100010", 21);
design.addAttribute(21, 0, 10);
design.addAttribute(21, 1, 'B1000');
design.addMove(21, 0, [3], 0);
design.addMove(21, 0, [2], 0);
design.addMove(21, 0, [0], 0);
design.addMove(21, 0, [1], 0);
design.addPiece("B010011", 22);
design.addAttribute(22, 0, 11);
design.addAttribute(22, 1, 'B0100');
design.addMove(22, 0, [3], 0);
design.addMove(22, 0, [2], 0);
design.addMove(22, 0, [0], 0);
design.addMove(22, 0, [1], 0);
design.addPiece("B100011", 23);
design.addAttribute(23, 0, 11);
design.addAttribute(23, 1, 'B1000');
design.addMove(23, 0, [3], 0);
design.addMove(23, 0, [2], 0);
design.addMove(23, 0, [0], 0);
design.addMove(23, 0, [1], 0);
design.addPiece("B001012", 24);
design.addAttribute(24, 0, 12);
design.addAttribute(24, 1, 'B0010');
design.addMove(24, 0, [3], 0);
design.addMove(24, 0, [2], 0);
design.addMove(24, 0, [0], 0);
design.addMove(24, 0, [1], 0);
design.addPiece("B000112", 25);
design.addAttribute(25, 0, 12);
design.addAttribute(25, 1, 'B0001');
design.addMove(25, 0, [3], 0);
design.addMove(25, 0, [2], 0);
design.addMove(25, 0, [0], 0);
design.addMove(25, 0, [1], 0);
design.addPiece("B001013", 26);
design.addAttribute(26, 0, 13);
design.addAttribute(26, 1, 'B0010');
design.addMove(26, 0, [3], 0);
design.addMove(26, 0, [2], 0);
design.addMove(26, 0, [0], 0);
design.addMove(26, 0, [1], 0);
design.addPiece("B000113", 27);
design.addAttribute(27, 0, 13);
design.addAttribute(27, 1, 'B0001');
design.addMove(27, 0, [3], 0);
design.addMove(27, 0, [2], 0);
design.addMove(27, 0, [0], 0);
design.addMove(27, 0, [1], 0);
design.addPiece("G0110F14", 28);
design.addAttribute(28, 0, 14);
design.addAttribute(28, 1, 'G0110F');
design.addMove(28, 0, [3], 0);
design.addMove(28, 0, [2], 0);
design.addMove(28, 0, [0], 0);
design.addMove(28, 0, [1], 0);
design.addPiece("G1010F14", 29);
design.addAttribute(29, 0, 14);
design.addAttribute(29, 1, 'G1010F');
design.addMove(29, 0, [3], 0);
design.addMove(29, 0, [2], 0);
design.addMove(29, 0, [0], 0);
design.addMove(29, 0, [1], 0);
design.addPiece("G0101F14", 30);
design.addAttribute(30, 0, 14);
design.addAttribute(30, 1, 'G0101F');
design.addMove(30, 0, [3], 0);
design.addMove(30, 0, [2], 0);
design.addMove(30, 0, [0], 0);
design.addMove(30, 0, [1], 0);
design.addPiece("G1001F14", 31);
design.addAttribute(31, 0, 14);
design.addAttribute(31, 1, 'G1001F');
design.addMove(31, 0, [3], 0);
design.addMove(31, 0, [2], 0);
design.addMove(31, 0, [0], 0);
design.addMove(31, 0, [1], 0);
design.addPiece("B010015", 32);
design.addAttribute(32, 0, 15);
design.addAttribute(32, 1, 'B0100');
design.addMove(32, 0, [3], 0);
design.addMove(32, 0, [2], 0);
design.addMove(32, 0, [0], 0);
design.addMove(32, 0, [1], 0);
design.addPiece("B100015", 33);
design.addAttribute(33, 0, 15);
design.addAttribute(33, 1, 'B1000');
design.addMove(33, 0, [3], 0);
design.addMove(33, 0, [2], 0);
design.addMove(33, 0, [0], 0);
design.addMove(33, 0, [1], 0);
design.setup("You", "R0110F1", 0);
design.setup("You", "R1010F1", 1);
design.setup("You", "R0101F1", 6);
design.setup("You", "R1001F1", 7);
design.setup("You", "B01002", 2);
design.setup("You", "B10002", 3);
design.setup("You", "B00103", 4);
design.setup("You", "B00013", 10);
design.setup("You", "B00104", 5);
design.setup("You", "B00014", 11);
design.setup("You", "B01005", 8);
design.setup("You", "B10005", 9);
design.setup("You", "B00006", 12);
design.setup("You", "B00007", 13);
design.setup("You", "B0110F8", 14);
design.setup("You", "B1010F8", 15);
design.setup("You", "B0101F8", 20);
design.setup("You", "B1001F8", 21);
design.setup("You", "B01009", 16);
design.setup("You", "B10009", 17);
design.setup("You", "B010010", 22);
design.setup("You", "B100010", 23);
design.setup("You", "B010011", 24);
design.setup("You", "B100011", 25);
design.setup("You", "B001012", 26);
design.setup("You", "B000112", 32);
design.setup("You", "B001013", 27);
design.setup("You", "B000113", 33);
design.setup("You", "G0110F14", 28);
design.setup("You", "G1010F14", 29);
design.setup("You", "G0101F14", 34);
design.setup("You", "G1001F14", 35);
design.setup("You", "B010015", 30);
design.setup("You", "B100015", 31);
design.goal(0, "You", "G0110F14", [0]);
design.goal(0, "You", "G1010F14", [1]);
design.goal(0, "You", "G0101F14", [6]);
design.goal(0, "You", "G1001F14", [7]);
design.goal(0, "You", "B0110F8", [14]);
design.goal(0, "You", "B1010F8", [15]);
design.goal(0, "You", "B0101F8", [20]);
design.goal(0, "You", "B1001F8", [21]);
design.goal(0, "You", "R0110F1", [28]);
design.goal(0, "You", "R1010F1", [29]);
design.goal(0, "You", "R0101F1", [34]);
design.goal(0, "You", "R1001F1", [35]);
}
Dagaz.View.configure = function(view) {
view.defPiece("YouR0110F1", "You R0110F1");
view.defPiece("YouR1010F1", "You R1010F1");
view.defPiece("YouR0101F1", "You R0101F1");
view.defPiece("YouR1001F1", "You R1001F1");
view.defPiece("YouB01002", "You B01002");
view.defPiece("YouB10002", "You B10002");
view.defPiece("YouB00103", "You B00103");
view.defPiece("YouB00013", "You B00013");
view.defPiece("YouB00104", "You B00104");
view.defPiece("YouB00014", "You B00014");
view.defPiece("YouB01005", "You B01005");
view.defPiece("YouB10005", "You B10005");
view.defPiece("YouB00006", "You B00006");
view.defPiece("YouB00007", "You B00007");
view.defPiece("YouB0110F8", "You B0110F8");
view.defPiece("YouB1010F8", "You B1010F8");
view.defPiece("YouB0101F8", "You B0101F8");
view.defPiece("YouB1001F8", "You B1001F8");
view.defPiece("YouB01009", "You B01009");
view.defPiece("YouB10009", "You B10009");
view.defPiece("YouB010010", "You B010010");
view.defPiece("YouB100010", "You B100010");
view.defPiece("YouB010011", "You B010011");
view.defPiece("YouB100011", "You B100011");
view.defPiece("YouB001012", "You B001012");
view.defPiece("YouB000112", "You B000112");
view.defPiece("YouB001013", "You B001013");
view.defPiece("YouB000113", "You B000113");
view.defPiece("YouG0110F14", "You G0110F14");
view.defPiece("YouG1010F14", "You G1010F14");
view.defPiece("YouG0101F14", "You G0101F14");
view.defPiece("YouG1001F14", "You G1001F14");
view.defPiece("YouB010015", "You B010015");
view.defPiece("YouB100015", "You B100015");
view.defPosition("a6", 0, 0, 100, 100);
view.defPosition("b6", 100, 0, 100, 100);
view.defPosition("c6", 200, 0, 100, 100);
view.defPosition("d6", 300, 0, 100, 100);
view.defPosition("e6", 400, 0, 100, 100);
view.defPosition("f6", 500, 0, 100, 100);
view.defPosition("a5", 0, 100, 100, 100);
view.defPosition("b5", 100, 100, 100, 100);
view.defPosition("c5", 200, 100, 100, 100);
view.defPosition("d5", 300, 100, 100, 100);
view.defPosition("e5", 400, 100, 100, 100);
view.defPosition("f5", 500, 100, 100, 100);
view.defPosition("a4", 0, 200, 100, 100);
view.defPosition("b4", 100, 200, 100, 100);
view.defPosition("c4", 200, 200, 100, 100);
view.defPosition("d4", 300, 200, 100, 100);
view.defPosition("e4", 400, 200, 100, 100);
view.defPosition("f4", 500, 200, 100, 100);
view.defPosition("a3", 0, 300, 100, 100);
view.defPosition("b3", 100, 300, 100, 100);
view.defPosition("c3", 200, 300, 100, 100);
view.defPosition("d3", 300, 300, 100, 100);
view.defPosition("e3", 400, 300, 100, 100);
view.defPosition("f3", 500, 300, 100, 100);
view.defPosition("a2", 0, 400, 100, 100);
view.defPosition("b2", 100, 400, 100, 100);
view.defPosition("c2", 200, 400, 100, 100);
view.defPosition("d2", 300, 400, 100, 100);
view.defPosition("e2", 400, 400, 100, 100);
view.defPosition("f2", 500, 400, 100, 100);
view.defPosition("a1", 0, 500, 100, 100);
view.defPosition("b1", 100, 500, 100, 100);
view.defPosition("c1", 200, 500, 100, 100);
view.defPosition("d1", 300, 500, 100, 100);
view.defPosition("e1", 400, 500, 100, 100);
view.defPosition("f1", 500, 500, 100, 100);
}
|
var API = require('../');
var expect = require('expect.js');
var config = require('./config');
describe('api_common', function () {
describe('isAccessTokenValid', function () {
it('should invalid', function () {
var token = new API.AccessToken('token', new Date().getTime() - 7200 * 1000);
expect(token.isValid()).not.to.be.ok();
});
it('should valid', function () {
var token = new API.AccessToken('token', new Date().getTime() + 7200 * 1000);
expect(token.isValid()).to.be.ok();
});
});
describe('mixin', function () {
it('should ok', function () {
API.mixin({sayHi: function () {}});
expect(API.prototype).to.have.property('sayHi');
});
it('should not ok when override method', function () {
var obj = {sayHi: function () {}};
expect(API.mixin).withArgs(obj).to.throwException(/Don't allow override existed prototype method\./);
});
});
describe('getAccessToken', function () {
it('should ok', function* () {
var api = new API(config.appid, config.appsecret);
var token = yield api.getAccessToken();
expect(token).to.only.have.keys('accessToken', 'expireTime');
});
it('should not ok', function* () {
var api = new API('appid', 'secret');
try {
yield api.getAccessToken();
} catch (err) {
expect(err).to.have.property('name', 'WeChatAPIError');
expect(err).to.have.property('message', 'invalid credential');
}
});
});
});
|
'use strict';
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Writer = require('broccoli-writer');
function CustomReplace (inputTree, configTree, options) {
if (!(this instanceof CustomReplace)) {
return new CustomReplace(inputTree, configTree, options);
}
Writer.call(this, inputTree, options); // this._super();
this.inputTree = inputTree;
this.configTree = configTree;
this.options = options;
}
CustomReplace.prototype = Object.create(Writer.prototype);
CustomReplace.prototype.constructor = CustomReplace;
CustomReplace.prototype.write = function (readTree, destDir) {
var self = this;
var inputDir, configDir;
return readTree(this.inputTree)
.then(function(path) {
inputDir = path;
return readTree(self.configTree);
})
.then(function(path) {
configDir = path;
return {
configDir: configDir,
inputDir: inputDir,
destDir: destDir
};
})
.then(this.process.bind(this));
};
CustomReplace.prototype.process = function(results) {
var files = this.options.files;
var config = this.getConfig(results.configDir);
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
var filePath = path.join(results.inputDir, file);
var destPath = path.join(results.destDir, file);
this.processFile(config, filePath, destPath);
}
};
CustomReplace.prototype.processFile = function(config, filePath, destPath) {
var contents = fs.readFileSync(filePath, { encoding: 'utf8' });
for (var i = 0, l = this.options.patterns.length; i < l; i++) {
var pattern = this.options.patterns[i];
var replacement = pattern.replacement;
if (typeof replacement === 'function') {
replacement = replacement(config);
}
contents = contents.replace(pattern.match, replacement);
}
if (!fs.existsSync(path.dirname(destPath))) {
mkdirp.sync(path.dirname(destPath));
}
fs.writeFileSync(destPath, contents, { encoding: 'utf8' });
};
CustomReplace.prototype.getConfig = function (srcDir) {
var configPath = path.join(srcDir, this.options.configPath);
return JSON.parse(fs.readFileSync(configPath, { encoding: 'utf8' }));
};
module.exports = CustomReplace;
|
'use strict';
var localUtils = require('./utils');
var abstractMapReduce = require('pouchdb-abstract-mapreduce');
var parseField = localUtils.parseField;
//
// One thing about these mappers:
//
// Per the advice of John-David Dalton (http://youtu.be/NthmeLEhDDM),
// what you want to do in this case is optimize for the smallest possible
// function, since that's the thing that gets run over and over again.
//
// This code would be a lot simpler if all the if/elses were inside
// the function, but it would also be a lot less performant.
//
function createDeepMultiMapper(fields, emit) {
return function (doc) {
var toEmit = [];
for (var i = 0, iLen = fields.length; i < iLen; i++) {
var parsedField = parseField(fields[i]);
var value = doc;
for (var j = 0, jLen = parsedField.length; j < jLen; j++) {
var key = parsedField[j];
value = value[key];
if (!value) {
break;
}
}
toEmit.push(value);
}
emit(toEmit);
};
}
function createDeepSingleMapper(field, emit) {
var parsedField = parseField(field);
return function (doc) {
var value = doc;
for (var i = 0, len = parsedField.length; i < len; i++) {
var key = parsedField[i];
value = value[key];
if (!value) {
return; // do nothing
}
}
emit(value);
};
}
function createShallowSingleMapper(field, emit) {
return function (doc) {
emit(doc[field]);
};
}
function createShallowMultiMapper(fields, emit) {
return function (doc) {
var toEmit = [];
for (var i = 0, len = fields.length; i < len; i++) {
toEmit.push(doc[fields[i]]);
}
emit(toEmit);
};
}
function checkShallow(fields) {
for (var i = 0, len = fields.length; i < len; i++) {
var field = fields[i];
if (field.indexOf('.') !== -1) {
return false;
}
}
return true;
}
function createMapper(fields, emit) {
var isShallow = checkShallow(fields);
var isSingle = fields.length === 1;
// notice we try to optimize for the most common case,
// i.e. single shallow indexes
if (isShallow) {
if (isSingle) {
return createShallowSingleMapper(fields[0], emit);
} else { // multi
return createShallowMultiMapper(fields, emit);
}
} else { // deep
if (isSingle) {
return createDeepSingleMapper(fields[0], emit);
} else { // multi
return createDeepMultiMapper(fields, emit);
}
}
}
var abstractMapper = abstractMapReduce({
name: 'indexes',
mapper: function (mapFunDef, emit) {
// mapFunDef is a list of fields
var fields = Object.keys(mapFunDef.fields);
return createMapper(fields, emit);
},
reducer: function (/*reduceFunDef*/) {
throw new Error('reduce not supported');
},
ddocValidator: function (ddoc, viewName) {
var view = ddoc.views[viewName];
if (!view.map || !view.map.fields) {
throw new Error('ddoc ' + ddoc._id +' with view ' + viewName +
' doesn\'t have map.fields defined. ' +
'maybe it wasn\'t created by this plugin?');
}
}
});
module.exports = abstractMapper;
|
// @flow
import React from 'react'
import Route from 'react-router-dom/Route'
import { Wheel1, Wheel2 } from 'components/Wheels'
import styles from './Wheels.css'
type Props = {}
const Wheel = (props: Props) => (
<div className={styles['wheels']}>
<Route path='/wheels/1' component={Wheel1} exact />
<Route path='/wheels/2' component={Wheel2} exact />
</div>
)
export default Wheel
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _utils = require('./utils');
function getLocalPromise() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
return null;
}
}
var P = local.Promise;
if (!(0, _utils.isPromise)(P)) {
return null;
}
return P;
}
var Config = (function () {
function Config() {
_classCallCheck(this, Config);
this._promise = getLocalPromise();
}
_createClass(Config, [{
key: 'Promise',
set: function set(promise) {
if (!(0, _utils.isPromise)(promise)) {
throw new Error('Promise must be a promise');
} else {
this._promise = promise;
}
},
get: function get() {
if (!(0, _utils.isPromise)(this._promise)) {
throw new Error('No promise exist');
}
return this._promise;
}
}]);
return Config;
})();
var config = new Config();
exports.config = config;
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('team', 'Unit | Model | team', {
// Specify the other units that are required for this test.
needs: []
});
test('it exists', function(assert) {
let model = this.subject();
// let store = this.store();
assert.ok(!!model);
});
|
var vec2 = require('../math/vec2');
var Ray = require('../collision/Ray');
module.exports = RaycastResult;
/**
* Storage for Ray casting hit data.
* @class RaycastResult
* @constructor
*/
function RaycastResult(){
/**
* The normal of the hit, oriented in world space.
* @property {array} normal
*/
this.normal = vec2.create();
/**
* The hit shape, or null.
* @property {Shape} shape
*/
this.shape = null;
/**
* The hit body, or null.
* @property {Body} body
*/
this.body = null;
/**
* The index of the hit triangle, if the hit shape was indexable.
* @property {number} faceIndex
* @default -1
*/
this.faceIndex = -1;
/**
* Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet.
* @property {number} fraction
* @default -1
*/
this.fraction = -1;
/**
* If the ray should stop traversing.
* @readonly
* @property {Boolean} isStopped
*/
this.isStopped = false;
}
/**
* Reset all result data. Must be done before re-using the result object.
* @method reset
*/
RaycastResult.prototype.reset = function () {
vec2.set(this.normal, 0, 0);
this.shape = null;
this.body = null;
this.faceIndex = -1;
this.fraction = -1;
this.isStopped = false;
};
/**
* Get the distance to the hit point.
* @method getHitDistance
* @param {Ray} ray
*/
RaycastResult.prototype.getHitDistance = function (ray) {
return vec2.distance(ray.from, ray.to) * this.fraction;
};
/**
* Returns true if the ray hit something since the last reset().
* @method hasHit
*/
RaycastResult.prototype.hasHit = function () {
return this.fraction !== -1;
};
/**
* Get world hit point.
* @method getHitPoint
* @param {array} out
* @param {Ray} ray
*/
RaycastResult.prototype.getHitPoint = function (out, ray) {
vec2.lerp(out, ray.from, ray.to, this.fraction);
};
/**
* Can be called while iterating over hits to stop searching for hit points.
* @method stop
*/
RaycastResult.prototype.stop = function(){
this.isStopped = true;
};
/**
* @method shouldStop
* @private
* @param {Ray} ray
* @return {boolean}
*/
RaycastResult.prototype.shouldStop = function(ray){
return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY);
};
/**
* @method set
* @private
* @param {array} normal
* @param {Shape} shape
* @param {Body} body
* @param {number} fraction
* @param {number} faceIndex
*/
RaycastResult.prototype.set = function(
normal,
shape,
body,
fraction,
faceIndex
){
vec2.copy(this.normal, normal);
this.shape = shape;
this.body = body;
this.fraction = fraction;
this.faceIndex = faceIndex;
};
|
//Finance.js
//For more information, visit http://financejs.org
//Copyright 2014 - 2015 Essam Al Joubori, MIT license
// Instantiate a Finance class
var Finance = function() {};
// Present Value (PV)
Finance.prototype.PV = function (rate, cf1) {
var rate = rate/100, pv;
pv = cf1 / (1 + rate);
return Math.round(pv * 100) / 100;
};
// Future Value (FV)
Finance.prototype.FV = function (rate, cf0, numOfPeriod) {
var rate = rate/100, fv;
fv = cf0 * Math.pow((1 + rate), numOfPeriod);
return Math.round(fv * 100) / 100;
};
// Net Present Value (NPV)
Finance.prototype.NPV = function (rate) {
var rate = rate/100, npv = arguments[1];
for (var i = 2; i < arguments.length; i++) {
npv +=(arguments[i] / Math.pow((1 + rate), i - 1));
}
return Math.round(npv * 100) / 100;
};
// seekZero seeks the zero point of the function fn(x), accurate to within x \pm 0.01. fn(x) must be decreasing with x.
function seekZero(fn) {
var x = 1;
while (fn(x) > 0) {
x += 1;
}
while (fn(x) < 0) {
x -= 0.01
}
return x + 0.01;
}
// Internal Rate of Return (IRR)
Finance.prototype.IRR = function(cfs) {
var args = arguments;
var numberOfTries = 1;
// Cash flow values must contain at least one positive value and one negative value
var positive, negative;
Array.prototype.slice.call(args).forEach(function (value) {
if (value > 0) positive = true;
if (value < 0) negative = true;
})
if (!positive || !negative) throw new Error('IRR requires at least one positive value and one negative value');
function npv(rate) {
numberOfTries++;
if (numberOfTries > 1000) {
throw new Error('IRR can\'t find a result');
}
var rrate = (1 + rate/100);
var npv = args[0];
for (var i = 1; i < args.length; i++) {
npv += (args[i] / Math.pow(rrate, i));
}
return npv;
}
return Math.round(seekZero(npv) * 100) / 100;
};
// Payback Period (PP)
Finance.prototype.PP = function(numOfPeriods, cfs) {
// for even cash flows
if (numOfPeriods === 0) {
return Math.abs(arguments[1]) / arguments[2];
}
// for uneven cash flows
var cumulativeCashFlow = arguments[1];
var yearsCounter = 1;
for (i = 2; i < arguments.length; i++) {
cumulativeCashFlow += arguments[i];
if (cumulativeCashFlow > 0) {
yearsCounter += (cumulativeCashFlow - arguments[i]) / arguments[i];
return yearsCounter;
} else {
yearsCounter++;
}
}
};
// Return on Investment (ROI)
Finance.prototype.ROI = function(cf0, earnings) {
var roi = (earnings - Math.abs(cf0)) / Math.abs(cf0) * 100;
return Math.round(roi * 100) / 100;
};
// Amortization
Finance.prototype.AM = function (principal, rate, period, yearOrMonth, payAtBeginning) {
var numerator, denominator, am;
var ratePerPeriod = rate / 12 / 100;
// for inputs in years
if (!yearOrMonth) {
numerator = buildNumerator(period * 12);
denominator = Math.pow((1 + ratePerPeriod), period * 12) - 1;
// for inputs in months
} else if (yearOrMonth === 1) {
numerator = buildNumerator(period)
denominator = Math.pow((1 + ratePerPeriod), period) - 1;
} else {
console.log('not defined');
}
am = principal * (numerator / denominator);
return Math.round(am * 100) / 100;
function buildNumerator(numInterestAccruals){
if( payAtBeginning ){
//if payments are made in the beginning of the period, then interest shouldn't be calculated for first period
numInterestAccruals -= 1;
}
return ratePerPeriod * Math.pow((1 + ratePerPeriod), numInterestAccruals);
}
};
// Profitability Index (PI)
Finance.prototype.PI = function(rate, cfs){
var totalOfPVs = 0, PI;
for (var i = 2; i < arguments.length; i++) {
var discountFactor;
// calculate discount factor
discountFactor = 1 / Math.pow((1 + rate/100), (i - 1));
totalOfPVs += arguments[i] * discountFactor;
}
PI = totalOfPVs/Math.abs(arguments[1]);
return Math.round(PI * 100) / 100;
};
// Discount Factor (DF)
Finance.prototype.DF = function(rate, numOfPeriods) {
var dfs = [], discountFactor;
for (var i = 1; i < numOfPeriods; i++) {
discountFactor = 1 / Math.pow((1 + rate/100), (i - 1));
roundedDiscountFactor = Math.ceil(discountFactor * 1000)/1000;
dfs.push(roundedDiscountFactor);
}
return dfs;
};
// Compound Interest (CI)
Finance.prototype.CI = function(rate, numOfCompoundings, principal, numOfPeriods) {
var CI = principal * Math.pow((1 + ((rate/100)/ numOfCompoundings)), numOfCompoundings * numOfPeriods);
return Math.round(CI * 100) / 100;
};
// Compound Annual Growth Rate (CAGR)
Finance.prototype.CAGR = function(beginningValue, endingValue, numOfPeriods) {
var CAGR = Math.pow((endingValue / beginningValue), 1 / numOfPeriods) - 1;
return Math.round(CAGR * 10000) / 100;
};
// Leverage Ratio (LR)
Finance.prototype.LR = function(totalLiabilities, totalDebts, totalIncome) {
return (totalLiabilities + totalDebts) / totalIncome;
};
// Rule of 72
Finance.prototype.R72 = function(rate) {
return 72 / rate;
};
// Weighted Average Cost of Capital (WACC)
Finance.prototype.WACC = function(marketValueOfEquity, marketValueOfDebt, costOfEquity, costOfDebt, taxRate) {
E = marketValueOfEquity;
D = marketValueOfDebt;
V = marketValueOfEquity + marketValueOfDebt;
Re = costOfEquity;
Rd = costOfDebt;
T = taxRate;
var WACC = ((E / V) * Re/100) + (((D / V) * Rd/100) * (1 - T/100));
return Math.round(WACC * 1000) / 10;
};
// PMT calculates the payment for a loan based on constant payments and a constant interest rate
Finance.prototype.PMT = function(fractionalRate, numOfPayments, principal) {
return -principal * fractionalRate/(1-Math.pow(1+fractionalRate,-numOfPayments))
};
// IAR calculates the Inflation-adjusted return
Finance.prototype.IAR = function(investmentReturn, inflationRate){
return 100 * (((1 + investmentReturn) / (1 + inflationRate)) - 1);
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = Finance;
}
}
|
define([
"./AA",
"./AB"
], function(AA, AB) {
return {
name: "A",
dependencies: arguments
}
});
|
import React, {Component} from 'react'
import {render} from 'react-dom'
import TodoContainer from './components/TodoContainer'
import {AppStore} from './AppStore'
class App extends Component {
static childContextTypes = {
store: React.PropTypes.any
}
getChildContext() {
return {
store: AppStore
}
}
render() {
return (
<TodoContainer />
)
}
}
render(<App />, document.getElementById('wrapper'))
|
jQuery(document).ready(function () {
$('[data-filter-select]').change(function () {
var options = $(this).data('filter-select');
options = $.extend({ url: '/filters' }, options);
var data = options.data ? options.data : {};
data[options.filterParam] = $(this).val();
data['filter'] = options.filter;
var element = $(options.target);
$.ajax({
url: options.url,
data: data,
success: function (json) {
populateSelect(element, json, { id: "", name: "selecione" } );
}
});
});
});
function populateSelect(element, options, first) {
element.html('');
if (first) {
appendOptionToSelect(element, first.id, first.name);
}
for (var i = 0; i < options.length; ++i) {
appendOptionToSelect(element, options[i].id, options[i].name);
}
}
function appendOptionToSelect(element, value, label) {
var option = ['<option value="', value, '">', label, '</option>' ].join('');
element.append(option);
}
|
{
"AD" : "Մ․Թ․",
"BC" : "Մ․Թ․Ա․",
"DateTimeCombination" : "{1} {0}",
"DateTimeTimezoneCombination" : "{1} {0} {2}",
"DateTimezoneCombination" : "{1} {2}",
"HMS_long" : "{0} {1} {2}",
"HMS_short" : "{0}:{1}:{2}",
"HM_abbreviated" : "h:mm a",
"HM_short" : "h:mm a",
"H_abbreviated" : "h a",
"MD_abbreviated" : "MMM d",
"MD_long" : "MMMM d",
"MD_short" : "M-d",
"M_abbreviated" : "MMM",
"M_long" : "MMMM",
"RelativeTime/oneUnit" : "{0} ago",
"RelativeTime/twoUnits" : "{0} {1} ago",
"TimeTimezoneCombination" : "{0} {2}",
"WMD_abbreviated" : "E MMM d",
"WMD_long" : "EEEE, MMMM d",
"WMD_short" : "E, M-d",
"WYMD_abbreviated" : "EEE, y MMM d",
"WYMD_long" : "EEEE, MMMM d, y",
"WYMD_short" : "EEE, M/d/yy",
"W_abbreviated" : "EEE",
"W_long" : "EEEE",
"YMD_abbreviated" : "MMM d, y",
"YMD_full" : "MM/dd/yy",
"YMD_long" : "MMMM dd, y",
"YMD_short" : "MM/dd/yy",
"YM_long" : "y MMMM",
"day" : "d",
"day_abbr" : "d",
"dayperiod" : "Dayperiod",
"days" : "d",
"days_abbr" : "d",
"hour" : "h",
"hour_abbr" : "h",
"hours" : "h",
"hours_abbr" : "h",
"minute" : "min",
"minute_abbr" : "min",
"minutes" : "min",
"minutes_abbr" : "min",
"month" : "m",
"monthAprLong" : "Ապրիլ",
"monthAprMedium" : "Ապր",
"monthAugLong" : "Օգոստոս",
"monthAugMedium" : "Օգս",
"monthDecLong" : "Դեկտեմբեր",
"monthDecMedium" : "Դեկ",
"monthFebLong" : "Փետրվար",
"monthFebMedium" : "Փտվ",
"monthJanLong" : "Հունվար",
"monthJanMedium" : "Հնվ",
"monthJulLong" : "Հուլիս",
"monthJulMedium" : "Հլս",
"monthJunLong" : "Հունիս",
"monthJunMedium" : "Հնս",
"monthMarLong" : "Մարտ",
"monthMarMedium" : "Մրտ",
"monthMayLong" : "Մայիս",
"monthMayMedium" : "Մյս",
"monthNovLong" : "Նոյեմբեր",
"monthNovMedium" : "Նոյ",
"monthOctLong" : "Հոկտեմբեր",
"monthOctMedium" : "Հոկ",
"monthSepLong" : "Սեպտեմբեր",
"monthSepMedium" : "Սեպ",
"month_abbr" : "m",
"months" : "m",
"months_abbr" : "m",
"periodAm" : "Dayperiod",
"periodPm" : "Dayperiod",
"second" : "s",
"second_abbr" : "s",
"seconds" : "s",
"seconds_abbr" : "s",
"today" : "Today",
"tomorrow" : "Tomorrow",
"weekdayFriLong" : "Ուրբաթ",
"weekdayFriMedium" : "Ուր",
"weekdayMonLong" : "Երկուշաբթի",
"weekdayMonMedium" : "Երկ",
"weekdaySatLong" : "Շաբաթ",
"weekdaySatMedium" : "Շաբ",
"weekdaySunLong" : "Կիրակի",
"weekdaySunMedium" : "Կիր",
"weekdayThuLong" : "Հինգշաբթի",
"weekdayThuMedium" : "Հնգ",
"weekdayTueLong" : "Երեքշաբթի",
"weekdayTueMedium" : "Երք",
"weekdayWedLong" : "Չորեքշաբթի",
"weekdayWedMedium" : "Չոր",
"year" : "y",
"year_abbr" : "y",
"years" : "y",
"years_abbr" : "y",
"yesterday" : "Yesterday"
}
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
|
/**
@module ember
@submodule ember-runtime
*/
// BEGIN IMPORTS
import Ember from 'ember-metal';
import isEqual from 'ember-runtime/is-equal';
import compare from 'ember-runtime/compare';
import copy from 'ember-runtime/copy';
import inject from 'ember-runtime/inject';
import Namespace from 'ember-runtime/system/namespace';
import EmberObject from 'ember-runtime/system/object';
import { Container, Registry, getOwner, setOwner } from 'ember-runtime/system/container';
import ArrayProxy from 'ember-runtime/system/array_proxy';
import ObjectProxy from 'ember-runtime/system/object_proxy';
import CoreObject from 'ember-runtime/system/core_object';
import NativeArray from 'ember-runtime/system/native_array';
import EmberStringUtils from 'ember-runtime/system/string';
import {
onLoad,
runLoadHooks
} from 'ember-runtime/system/lazy_load';
import EmberArray from 'ember-runtime/mixins/array';
import Comparable from 'ember-runtime/mixins/comparable';
import Copyable from 'ember-runtime/mixins/copyable';
import Enumerable from 'ember-runtime/mixins/enumerable';
import {
Freezable,
FROZEN_ERROR
} from 'ember-runtime/mixins/freezable';
import _ProxyMixin from 'ember-runtime/mixins/-proxy';
import Observable from 'ember-runtime/mixins/observable';
import ActionHandler from 'ember-runtime/mixins/action_handler';
import MutableEnumerable from 'ember-runtime/mixins/mutable_enumerable';
import MutableArray from 'ember-runtime/mixins/mutable_array';
import TargetActionSupport from 'ember-runtime/mixins/target_action_support';
import Evented from 'ember-runtime/mixins/evented';
import PromiseProxyMixin from 'ember-runtime/mixins/promise_proxy';
import {
sum,
min,
max,
map,
sort,
setDiff,
mapBy,
filter,
filterBy,
uniq,
union,
intersect
} from 'ember-runtime/computed/reduce_computed_macros';
import Controller from 'ember-runtime/controllers/controller';
import ControllerMixin from 'ember-runtime/mixins/controller';
import Service from 'ember-runtime/system/service';
import RSVP from 'ember-runtime/ext/rsvp'; // just for side effect of extending Ember.RSVP
import 'ember-runtime/ext/string'; // just for side effect of extending String.prototype
import 'ember-runtime/ext/function'; // just for side effect of extending Function.prototype
import { isArray, typeOf } from 'ember-runtime/utils';
import isEnabled from 'ember-metal/features';
import RegistryProxyMixin from 'ember-runtime/mixins/registry_proxy';
import ContainerProxyMixin from 'ember-runtime/mixins/container_proxy';
// END IMPORTS
// BEGIN EXPORTS
Ember.compare = compare;
Ember.copy = copy;
Ember.isEqual = isEqual;
Ember.inject = inject;
Ember.Array = EmberArray;
Ember.Comparable = Comparable;
Ember.Copyable = Copyable;
Ember.Freezable = Freezable;
Ember.FROZEN_ERROR = FROZEN_ERROR;
Ember.MutableEnumerable = MutableEnumerable;
Ember.MutableArray = MutableArray;
Ember.TargetActionSupport = TargetActionSupport;
Ember.Evented = Evented;
Ember.PromiseProxyMixin = PromiseProxyMixin;
Ember.Observable = Observable;
Ember.typeOf = typeOf;
Ember.isArray = isArray;
// ES6TODO: this seems a less than ideal way/place to add properties to Ember.computed
var EmComputed = Ember.computed;
EmComputed.sum = sum;
EmComputed.min = min;
EmComputed.max = max;
EmComputed.map = map;
EmComputed.sort = sort;
EmComputed.setDiff = setDiff;
EmComputed.mapBy = mapBy;
EmComputed.filter = filter;
EmComputed.filterBy = filterBy;
EmComputed.uniq = uniq;
EmComputed.union = union;
EmComputed.intersect = intersect;
Ember.String = EmberStringUtils;
Ember.Object = EmberObject;
Ember.Container = Container;
Ember.Registry = Registry;
if (isEnabled('ember-container-inject-owner')) {
Ember.getOwner = getOwner;
Ember.setOwner = setOwner;
Ember._RegistryProxyMixin = RegistryProxyMixin;
Ember._ContainerProxyMixin = ContainerProxyMixin;
}
Ember.Namespace = Namespace;
Ember.Enumerable = Enumerable;
Ember.ArrayProxy = ArrayProxy;
Ember.ObjectProxy = ObjectProxy;
Ember.ActionHandler = ActionHandler;
Ember.CoreObject = CoreObject;
Ember.NativeArray = NativeArray;
// ES6TODO: Currently we must rely on the global from ember-metal/core to avoid circular deps
// Ember.A = A;
Ember.onLoad = onLoad;
Ember.runLoadHooks = runLoadHooks;
Ember.Controller = Controller;
Ember.ControllerMixin = ControllerMixin;
Ember.Service = Service;
Ember._ProxyMixin = _ProxyMixin;
Ember.RSVP = RSVP;
// END EXPORTS
export default Ember;
|
module.exports = function( gulp ) {
gulp.task( 'watch', function () {
gulp.watch( 'front-end/resources/css/stylus/app.styl', ['stylus'] )
})
}
|
const nodeType = 3;
export default function (textContent) {
return { nodeType, textContent };
}
|
{
"name": "mark.js",
"url": "https://github.com/julmot/mark.js.git"
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getFunctionName = getFunctionName;
exports.default = getDisplayName;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _reactIs = require("react-is");
// Simplified polyfill for IE 11 support
// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3
var fnNameMatchRegex = /^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;
function getFunctionName(fn) {
var match = "".concat(fn).match(fnNameMatchRegex);
var name = match && match[1];
return name || '';
}
/**
* @param {function} Component
* @param {string} fallback
* @returns {string | undefined}
*/
function getFunctionComponentName(Component) {
var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return Component.displayName || Component.name || getFunctionName(Component) || fallback;
}
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = getFunctionComponentName(innerType);
return outerType.displayName || (functionName !== '' ? "".concat(wrapperName, "(").concat(functionName, ")") : wrapperName);
}
/**
* cherry-pick from
* https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js
* originally forked from recompose/getDisplayName with added IE 11 support
*
* @param {React.ReactType} Component
* @returns {string | undefined}
*/
function getDisplayName(Component) {
if (Component == null) {
return undefined;
}
if (typeof Component === 'string') {
return Component;
}
if (typeof Component === 'function') {
return getFunctionComponentName(Component, 'Component');
}
if ((0, _typeof2.default)(Component) === 'object') {
switch (Component.$$typeof) {
case _reactIs.ForwardRef:
return getWrappedName(Component, Component.render, 'ForwardRef');
case _reactIs.Memo:
return getWrappedName(Component, Component.type, 'memo');
default:
return undefined;
}
}
return undefined;
}
|
'use strict';
const alt = require('../alt');
class EditTemplateActions {
cancelChanges(){
this.dispatch();
}
setDeltaTemplate(newTemplate){
this.dispatch(newTemplate);
}
setDeltaUrl(newUrl){
this.dispatch(newUrl);
}
}
module.exports = alt.createActions(EditTemplateActions);
|
import styles from './css/_bits.scss';
import Html from './template.html';
import ClickEvent from "./js/click_event.js";
import ScrollEvent from './js/scroll_event.js';
import ScrollReveal from "./js/scroll_reveal.js";
import scrollSpeed from "./js/scroll-parallax.js";
import particles from "./js/perfect_particles.js";
window.addEventListener("load",function(){
$('.loading_gear').css({
"top": "-50px",
"opacity": "0",
});
$('.loading_cover').css({
"opacity": "0",
});
})
|
var assert = require("assert");
var Lib = require("./../ramda");
describe('tap', function() {
var tap = Lib.tap;
it("returns a function that returns tap's argument", function() {
var f = tap(100);
assert.equal(typeof f, "function");
assert.equal(f(null), 100);
});
it("may take a function for a second argument that executes with tap's argument", function() {
var sideEffect = 0;
assert.equal(sideEffect, 0);
var rv = tap(200, function(x) { sideEffect = "string " + x; });
assert.equal(rv, 200);
assert.equal(sideEffect, "string 200");
});
it("ignores the scond argument if it's not a function", function() {
assert(tap(300, 400), 300);
assert(tap(300, [400]), 300);
assert(tap(300, {x: 400}), 300);
assert(tap(300, '400'), 300);
assert(tap(300, false), 300);
assert(tap(300, null), 300);
});
});
describe('eq', function() {
var eq = Lib.eq;
var a = [];
var b = a;
it("tests for strict equality of its operands", function() {
assert.equal(eq(100, 100), true);
assert.equal(eq(100, '100'), false);
assert.equal(eq([], []), false);
assert.equal(eq(a, b), true);
});
});
|
var roundedRect = Chart.helpers.canvas.roundedRect;
module.exports = {
config: {
type: 'line',
plugins: [{
afterDraw: function(chart) {
var ctx = chart.ctx;
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.fillStyle = '#00ff00';
ctx.beginPath();
roundedRect(ctx, 10, 10, 50, 50, 25);
roundedRect(ctx, 70, 10, 100, 50, 25);
roundedRect(ctx, 10, 70, 50, 100, 25);
roundedRect(ctx, 70, 70, 100, 100, 25);
roundedRect(ctx, 180, 10, 50, 50, 100);
roundedRect(ctx, 240, 10, 100, 50, 100);
roundedRect(ctx, 180, 70, 50, 100, 100);
roundedRect(ctx, 240, 70, 100, 100, 100);
roundedRect(ctx, 350, 10, 50, 50, 0);
ctx.fill();
ctx.stroke();
}
}],
options: {
scales: {
xAxes: [{display: false}],
yAxes: [{display: false}]
}
}
},
options: {
canvas: {
height: 256,
width: 512
}
}
};
|
const _ = require("lodash")
, b_helper = require("./helpers/browserify_builder")
, config = require("./config")
, es = require("event-stream")
, folder = require("./helpers/folder_helpers")
, fs = require("fs");
let args = process.argv.slice(2, process.argv.length)
_.forEach(config.javascript_files, (js)=>{
b_helper(js, _.includes(args, "--watch"), _.includes(args, "--minify"));
})
|
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'he',
{
devTools :
{
title : 'מידע על האלמנט',
dialogName : 'שם הדיאלוג',
tabName : 'שם הטאב',
elementId : 'ID של האלמנט',
elementType : 'סוג האלמנט'
}
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const makeSerializable = require("../util/makeSerializable");
const ModuleDependency = require("./ModuleDependency");
/** @typedef {import("../ModuleGraph")} ModuleGraph */
class WebAssemblyExportImportedDependency extends ModuleDependency {
constructor(exportName, request, name, valueType) {
super(request);
/** @type {string} */
this.exportName = exportName;
/** @type {string} */
this.name = name;
/** @type {string} */
this.valueType = valueType;
}
/**
* Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph
* @returns {string[][]} referenced exports
*/
getReferencedExports(moduleGraph) {
return [[this.name]];
}
get type() {
return "wasm export import";
}
serialize(context) {
const { write } = context;
write(this.exportName);
write(this.name);
write(this.valueType);
super.serialize(context);
}
deserialize(context) {
const { read } = context;
this.exportName = read();
this.name = read();
this.valueType = read();
super.deserialize(context);
}
}
makeSerializable(
WebAssemblyExportImportedDependency,
"webpack/lib/dependencies/WebAssemblyExportImportedDependency"
);
module.exports = WebAssemblyExportImportedDependency;
|
/*! jQuery UI - v1.10.3 - 2013-12-28
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.nl={closeText:"Sluiten",prevText:"←",nextText:"→",currentText:"Vandaag",monthNames:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],monthNamesShort:["jan","feb","mrt","apr","mei","jun","jul","aug","sep","okt","nov","dec"],dayNames:["zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"],dayNamesShort:["zon","maa","din","woe","don","vri","zat"],dayNamesMin:["zo","ma","di","wo","do","vr","za"],weekHeader:"Wk",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.nl)});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7 12c0 .55.45 1 1 1h8c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1zm5-10C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"
}), 'RemoveCircleOutlineRounded');
exports.default = _default;
|
module.exports = require('./lib/prerenderRedisCache');
|
module.exports = {
"StackLayout": {
},
"*": {}
};
|
(function() { /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var componentHandler={upgradeDom:function(optJsClass,optCssClass){},upgradeElement:function(element,optJsClass){},upgradeElements:function(elements){},upgradeAllRegistered:function(){},registerUpgradedCallback:function(jsClass,callback){},register:function(config){},downgradeElements:function(nodes){}};
componentHandler=function(){var registeredComponents_=[];var createdComponents_=[];var componentConfigProperty_="mdlComponentConfigInternal_";function findRegisteredClass_(name,optReplace){for(var i=0;i<registeredComponents_.length;i++)if(registeredComponents_[i].className===name){if(typeof optReplace!=="undefined")registeredComponents_[i]=optReplace;return registeredComponents_[i]}return false}function getUpgradedListOfElement_(element){var dataUpgraded=element.getAttribute("data-upgraded");return dataUpgraded===
null?[""]:dataUpgraded.split(",")}function isElementUpgraded_(element,jsClass){var upgradedList=getUpgradedListOfElement_(element);return upgradedList.indexOf(jsClass)!==-1}function upgradeDomInternal(optJsClass,optCssClass){if(typeof optJsClass==="undefined"&&typeof optCssClass==="undefined")for(var i=0;i<registeredComponents_.length;i++)upgradeDomInternal(registeredComponents_[i].className,registeredComponents_[i].cssClass);else{var jsClass=(optJsClass);if(typeof optCssClass==="undefined"){var registeredClass=
findRegisteredClass_(jsClass);if(registeredClass)optCssClass=registeredClass.cssClass}var elements=document.querySelectorAll("."+optCssClass);for(var n=0;n<elements.length;n++)upgradeElementInternal(elements[n],jsClass)}}function upgradeElementInternal(element,optJsClass){if(!(typeof element==="object"&&element instanceof Element))throw new Error("Invalid argument provided to upgrade MDL element.");var upgradedList=getUpgradedListOfElement_(element);var classesToUpgrade=[];if(!optJsClass){var classList=
element.classList;registeredComponents_.forEach(function(component){if(classList.contains(component.cssClass)&&classesToUpgrade.indexOf(component)===-1&&!isElementUpgraded_(element,component.className))classesToUpgrade.push(component)})}else if(!isElementUpgraded_(element,optJsClass))classesToUpgrade.push(findRegisteredClass_(optJsClass));for(var i=0,n=classesToUpgrade.length,registeredClass;i<n;i++){registeredClass=classesToUpgrade[i];if(registeredClass){upgradedList.push(registeredClass.className);
element.setAttribute("data-upgraded",upgradedList.join(","));var instance=new registeredClass.classConstructor(element);instance[componentConfigProperty_]=registeredClass;createdComponents_.push(instance);for(var j=0,m=registeredClass.callbacks.length;j<m;j++)registeredClass.callbacks[j](element);if(registeredClass.widget)element[registeredClass.className]=instance}else throw new Error("Unable to find a registered component for the given class.");var ev;if("CustomEvent"in window&&typeof window.CustomEvent===
"function")ev=new CustomEvent("mdl-componentupgraded",{bubbles:true,cancelable:false});else{ev=document.createEvent("Events");ev.initEvent("mdl-componentupgraded",true,true)}element.dispatchEvent(ev)}}function upgradeElementsInternal(elements){if(!Array.isArray(elements))if(elements instanceof Element)elements=[elements];else elements=Array.prototype.slice.call(elements);for(var i=0,n=elements.length,element;i<n;i++){element=elements[i];if(element instanceof HTMLElement){upgradeElementInternal(element);
if(element.children.length>0)upgradeElementsInternal(element.children)}}}function registerInternal(config){var widgetMissing=typeof config.widget==="undefined"&&typeof config["widget"]==="undefined";var widget=true;if(!widgetMissing)widget=config.widget||config["widget"];var newConfig=({classConstructor:config.constructor||config["constructor"],className:config.classAsString||config["classAsString"],cssClass:config.cssClass||config["cssClass"],widget:widget,callbacks:[]});registeredComponents_.forEach(function(item){if(item.cssClass===
newConfig.cssClass)throw new Error("The provided cssClass has already been registered: "+item.cssClass);if(item.className===newConfig.className)throw new Error("The provided className has already been registered");});if(config.constructor.prototype.hasOwnProperty(componentConfigProperty_))throw new Error("MDL component classes must not have "+componentConfigProperty_+" defined as a property.");var found=findRegisteredClass_(config.classAsString,newConfig);if(!found)registeredComponents_.push(newConfig)}
function registerUpgradedCallbackInternal(jsClass,callback){var regClass=findRegisteredClass_(jsClass);if(regClass)regClass.callbacks.push(callback)}function upgradeAllRegisteredInternal(){for(var n=0;n<registeredComponents_.length;n++)upgradeDomInternal(registeredComponents_[n].className)}function deconstructComponentInternal(component){if(component){var componentIndex=createdComponents_.indexOf(component);createdComponents_.splice(componentIndex,1);var upgrades=component.element_.getAttribute("data-upgraded").split(",");
var componentPlace=upgrades.indexOf(component[componentConfigProperty_].classAsString);upgrades.splice(componentPlace,1);component.element_.setAttribute("data-upgraded",upgrades.join(","));var ev;if("CustomEvent"in window&&typeof window.CustomEvent==="function")ev=new CustomEvent("mdl-componentdowngraded",{bubbles:true,cancelable:false});else{ev=document.createEvent("Events");ev.initEvent("mdl-componentdowngraded",true,true)}component.element_.dispatchEvent(ev)}}function downgradeNodesInternal(nodes){var downgradeNode=
function(node){createdComponents_.filter(function(item){return item.element_===node}).forEach(deconstructComponentInternal)};if(nodes instanceof Array||nodes instanceof NodeList)for(var n=0;n<nodes.length;n++)downgradeNode(nodes[n]);else if(nodes instanceof Node)downgradeNode(nodes);else throw new Error("Invalid argument provided to downgrade MDL nodes.");}return{upgradeDom:upgradeDomInternal,upgradeElement:upgradeElementInternal,upgradeElements:upgradeElementsInternal,upgradeAllRegistered:upgradeAllRegisteredInternal,
registerUpgradedCallback:registerUpgradedCallbackInternal,register:registerInternal,downgradeElements:downgradeNodesInternal}}();componentHandler.ComponentConfigPublic;componentHandler.ComponentConfig;componentHandler.Component;componentHandler["upgradeDom"]=componentHandler.upgradeDom;componentHandler["upgradeElement"]=componentHandler.upgradeElement;componentHandler["upgradeElements"]=componentHandler.upgradeElements;componentHandler["upgradeAllRegistered"]=componentHandler.upgradeAllRegistered;
componentHandler["registerUpgradedCallback"]=componentHandler.registerUpgradedCallback;componentHandler["register"]=componentHandler.register;componentHandler["downgradeElements"]=componentHandler.downgradeElements;window.componentHandler=componentHandler;window["componentHandler"]=componentHandler;
window.addEventListener("load",function(){if("classList"in document.createElement("div")&&"querySelector"in document&&"addEventListener"in window&&Array.prototype.forEach){document.documentElement.classList.add("mdl-js");componentHandler.upgradeAllRegistered()}else{componentHandler.upgradeElement=function(){};componentHandler.register=function(){}}});(function(){var MaterialButton=function MaterialButton(element){this.element_=element;this.init()};window["MaterialButton"]=MaterialButton;MaterialButton.prototype.Constant_={};MaterialButton.prototype.CssClasses_={RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_CONTAINER:"mdl-button__ripple-container",RIPPLE:"mdl-ripple"};MaterialButton.prototype.blurHandler_=function(event){if(event)this.element_.blur()};MaterialButton.prototype.disable=function(){this.element_.disabled=true};MaterialButton.prototype["disable"]=
MaterialButton.prototype.disable;MaterialButton.prototype.enable=function(){this.element_.disabled=false};MaterialButton.prototype["enable"]=MaterialButton.prototype.enable;MaterialButton.prototype.init=function(){if(this.element_){if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){var rippleContainer=document.createElement("span");rippleContainer.classList.add(this.CssClasses_.RIPPLE_CONTAINER);this.rippleElement_=document.createElement("span");this.rippleElement_.classList.add(this.CssClasses_.RIPPLE);
rippleContainer.appendChild(this.rippleElement_);this.boundRippleBlurHandler=this.blurHandler_.bind(this);this.rippleElement_.addEventListener("mouseup",this.boundRippleBlurHandler);this.element_.appendChild(rippleContainer)}this.boundButtonBlurHandler=this.blurHandler_.bind(this);this.element_.addEventListener("mouseup",this.boundButtonBlurHandler);this.element_.addEventListener("mouseleave",this.boundButtonBlurHandler)}};componentHandler.register({constructor:MaterialButton,classAsString:"MaterialButton",
cssClass:"mdl-js-button",widget:true})})();(function(){var MaterialProgress=function MaterialProgress(element){this.element_=element;this.init()};window["MaterialProgress"]=MaterialProgress;MaterialProgress.prototype.Constant_={};MaterialProgress.prototype.CssClasses_={INDETERMINATE_CLASS:"mdl-progress__indeterminate"};MaterialProgress.prototype.setProgress=function(p){if(this.element_.classList.contains(this.CssClasses_.INDETERMINATE_CLASS))return;this.progressbar_.style.width=p+"%"};MaterialProgress.prototype["setProgress"]=MaterialProgress.prototype.setProgress;
MaterialProgress.prototype.setBuffer=function(p){this.bufferbar_.style.width=p+"%";this.auxbar_.style.width=100-p+"%"};MaterialProgress.prototype["setBuffer"]=MaterialProgress.prototype.setBuffer;MaterialProgress.prototype.init=function(){if(this.element_){var el=document.createElement("div");el.className="progressbar bar bar1";this.element_.appendChild(el);this.progressbar_=el;el=document.createElement("div");el.className="bufferbar bar bar2";this.element_.appendChild(el);this.bufferbar_=el;el=document.createElement("div");
el.className="auxbar bar bar3";this.element_.appendChild(el);this.auxbar_=el;this.progressbar_.style.width="0%";this.bufferbar_.style.width="100%";this.auxbar_.style.width="0%";this.element_.classList.add("is-upgraded")}};componentHandler.register({constructor:MaterialProgress,classAsString:"MaterialProgress",cssClass:"mdl-js-progress",widget:true})})();(function(){var MaterialTextfield=function MaterialTextfield(element){this.element_=element;this.maxRows=this.Constant_.NO_MAX_ROWS;this.init()};window["MaterialTextfield"]=MaterialTextfield;MaterialTextfield.prototype.Constant_={NO_MAX_ROWS:-1,MAX_ROWS_ATTRIBUTE:"maxrows"};MaterialTextfield.prototype.CssClasses_={LABEL:"mdl-textfield__label",INPUT:"mdl-textfield__input",IS_DIRTY:"is-dirty",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_INVALID:"is-invalid",IS_UPGRADED:"is-upgraded",HAS_PLACEHOLDER:"has-placeholder"};
MaterialTextfield.prototype.onKeyDown_=function(event){var currentRowCount=event.target.value.split("\n").length;if(event.keyCode===13)if(currentRowCount>=this.maxRows)event.preventDefault()};MaterialTextfield.prototype.onFocus_=function(event){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)};MaterialTextfield.prototype.onBlur_=function(event){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)};MaterialTextfield.prototype.onReset_=function(event){this.updateClasses_()};MaterialTextfield.prototype.updateClasses_=
function(){this.checkDisabled();this.checkValidity();this.checkDirty();this.checkFocus()};MaterialTextfield.prototype.checkDisabled=function(){if(this.input_.disabled)this.element_.classList.add(this.CssClasses_.IS_DISABLED);else this.element_.classList.remove(this.CssClasses_.IS_DISABLED)};MaterialTextfield.prototype["checkDisabled"]=MaterialTextfield.prototype.checkDisabled;MaterialTextfield.prototype.checkFocus=function(){if(Boolean(this.element_.querySelector(":focus")))this.element_.classList.add(this.CssClasses_.IS_FOCUSED);
else this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)};MaterialTextfield.prototype["checkFocus"]=MaterialTextfield.prototype.checkFocus;MaterialTextfield.prototype.checkValidity=function(){if(this.input_.validity)if(this.input_.validity.valid)this.element_.classList.remove(this.CssClasses_.IS_INVALID);else this.element_.classList.add(this.CssClasses_.IS_INVALID)};MaterialTextfield.prototype["checkValidity"]=MaterialTextfield.prototype.checkValidity;MaterialTextfield.prototype.checkDirty=
function(){if(this.input_.value&&this.input_.value.length>0)this.element_.classList.add(this.CssClasses_.IS_DIRTY);else this.element_.classList.remove(this.CssClasses_.IS_DIRTY)};MaterialTextfield.prototype["checkDirty"]=MaterialTextfield.prototype.checkDirty;MaterialTextfield.prototype.disable=function(){this.input_.disabled=true;this.updateClasses_()};MaterialTextfield.prototype["disable"]=MaterialTextfield.prototype.disable;MaterialTextfield.prototype.enable=function(){this.input_.disabled=false;
this.updateClasses_()};MaterialTextfield.prototype["enable"]=MaterialTextfield.prototype.enable;MaterialTextfield.prototype.change=function(value){this.input_.value=value||"";this.updateClasses_()};MaterialTextfield.prototype["change"]=MaterialTextfield.prototype.change;MaterialTextfield.prototype.init=function(){if(this.element_){this.label_=this.element_.querySelector("."+this.CssClasses_.LABEL);this.input_=this.element_.querySelector("."+this.CssClasses_.INPUT);if(this.input_){if(this.input_.hasAttribute((this.Constant_.MAX_ROWS_ATTRIBUTE))){this.maxRows=
parseInt(this.input_.getAttribute((this.Constant_.MAX_ROWS_ATTRIBUTE)),10);if(isNaN(this.maxRows))this.maxRows=this.Constant_.NO_MAX_ROWS}if(this.input_.hasAttribute("placeholder"))this.element_.classList.add(this.CssClasses_.HAS_PLACEHOLDER);this.boundUpdateClassesHandler=this.updateClasses_.bind(this);this.boundFocusHandler=this.onFocus_.bind(this);this.boundBlurHandler=this.onBlur_.bind(this);this.boundResetHandler=this.onReset_.bind(this);this.input_.addEventListener("input",this.boundUpdateClassesHandler);
this.input_.addEventListener("focus",this.boundFocusHandler);this.input_.addEventListener("blur",this.boundBlurHandler);this.input_.addEventListener("reset",this.boundResetHandler);if(this.maxRows!==this.Constant_.NO_MAX_ROWS){this.boundKeyDownHandler=this.onKeyDown_.bind(this);this.input_.addEventListener("keydown",this.boundKeyDownHandler)}var invalid=this.element_.classList.contains(this.CssClasses_.IS_INVALID);this.updateClasses_();this.element_.classList.add(this.CssClasses_.IS_UPGRADED);if(invalid)this.element_.classList.add(this.CssClasses_.IS_INVALID);
if(this.input_.hasAttribute("autofocus")){this.element_.focus();this.checkFocus()}}}};componentHandler.register({constructor:MaterialTextfield,classAsString:"MaterialTextfield",cssClass:"mdl-js-textfield",widget:true})})();(function(){var h,l=this;function m(a){return void 0!==a}function aa(){}function ba(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=
typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b}function ca(a){return null!=a}function da(a){return"array"==ba(a)}function ea(a){var b=ba(a);return"array"==b||"object"==b&&"number"==typeof a.length}function n(a){return"string"==typeof a}function p(a){return"function"==ba(a)}function fa(a){var b=typeof a;return"object"==b&&null!=a||"function"==b}var ga="closure_uid_"+(1E9*Math.random()>>>
0),ha=0;function ia(a,b,c){return a.call.apply(a.bind,arguments)}function ja(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}}function q(a,b,c){q=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ia:ja;return q.apply(null,arguments)}function ka(a,b){var c=
Array.prototype.slice.call(arguments,1);return function(){var b=c.slice();b.push.apply(b,arguments);return a.apply(this,b)}}function r(a,b){for(var c in b)a[c]=b[c]}var la=Date.now||function(){return+new Date};function na(a,b){var c=a.split("."),d=l;c[0]in d||!d.execScript||d.execScript("var "+c[0]);for(var e;c.length&&(e=c.shift());)!c.length&&m(b)?d[e]=b:d=d[e]?d[e]:d[e]={}}function t(a,b){function c(){}c.prototype=b.prototype;a.c=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.Jd=function(a,
c,f){for(var g=Array(arguments.length-2),k=2;k<arguments.length;k++)g[k-2]=arguments[k];return b.prototype[c].apply(a,g)}}function u(a){if(Error.captureStackTrace)Error.captureStackTrace(this,u);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))}t(u,Error);u.prototype.name="CustomError";var oa;function pa(a,b){for(var c=a.split("%s"),d="",e=Array.prototype.slice.call(arguments,1);e.length&&1<c.length;)d+=c.shift()+e.shift();return d+c.join("%s")}var qa=String.prototype.trim?function(a){return a.trim()}:
function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};function ra(a){if(!sa.test(a))return a;-1!=a.indexOf("&")&&(a=a.replace(ta,"&"));-1!=a.indexOf("<")&&(a=a.replace(ua,"<"));-1!=a.indexOf(">")&&(a=a.replace(va,">"));-1!=a.indexOf('"')&&(a=a.replace(wa,"""));-1!=a.indexOf("'")&&(a=a.replace(xa,"'"));-1!=a.indexOf("\x00")&&(a=a.replace(ya,"�"));return a}var ta=/&/g,ua=/</g,va=/>/g,wa=/"/g,xa=/'/g,ya=/\x00/g,sa=/[\x00&<>"']/;function za(a,b){return a<b?-1:a>b?1:0}function Aa(a,
b){b.unshift(a);u.call(this,pa.apply(null,b));b.shift()}t(Aa,u);Aa.prototype.name="AssertionError";function Ba(a,b){throw new Aa("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));}var Ca=Array.prototype.indexOf?function(a,b,c){return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(n(a))return n(b)&&1==b.length?a.indexOf(b,c):-1;for(;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1},Da=Array.prototype.forEach?function(a,b,c){Array.prototype.forEach.call(a,
b,c)}:function(a,b,c){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)f in e&&b.call(c,e[f],f,a)};function Ea(a,b){for(var c=n(a)?a.split(""):a,d=a.length-1;0<=d;--d)d in c&&b.call(void 0,c[d],d,a)}var Fa=Array.prototype.filter?function(a,b,c){return Array.prototype.filter.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=[],f=0,g=n(a)?a.split(""):a,k=0;k<d;k++)if(k in g){var z=g[k];b.call(c,z,k,a)&&(e[f++]=z)}return e},Ga=Array.prototype.map?function(a,b,c){return Array.prototype.map.call(a,
b,c)}:function(a,b,c){for(var d=a.length,e=Array(d),f=n(a)?a.split(""):a,g=0;g<d;g++)g in f&&(e[g]=b.call(c,f[g],g,a));return e},Ha=Array.prototype.some?function(a,b,c){return Array.prototype.some.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return!0;return!1};function Ia(a,b,c){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return f;return-1}function Ja(a,b){return 0<=Ca(a,b)}function Ka(a,b){var c=
Ca(a,b),d;(d=0<=c)&&La(a,c);return d}function La(a,b){return 1==Array.prototype.splice.call(a,b,1).length}function Ma(a,b){var c=Ia(a,b,void 0);0<=c&&La(a,c)}function Na(a,b){var c=0;Ea(a,function(d,e){b.call(void 0,d,e,a)&&La(a,e)&&c++})}function Oa(a){return Array.prototype.concat.apply(Array.prototype,arguments)}function Pa(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]}var Qa;a:{var Ra=l.navigator;if(Ra){var Sa=Ra.userAgent;if(Sa){Qa=Sa;break a}}Qa=""}function v(a){return-1!=
Qa.indexOf(a)}function Ta(a,b,c){for(var d in a)b.call(c,a[d],d,a)}function Ua(a,b){for(var c in a)if(b.call(void 0,a[c],c,a))return!0;return!1}function Va(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b}function Wa(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b}var Xa="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Ya(a,b){for(var c,d,e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<Xa.length;f++)c=
Xa[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c])}}var Za=v("Opera"),w=v("Trident")||v("MSIE"),$a=v("Edge"),ab=$a||w,bb=v("Gecko")&&!(-1!=Qa.toLowerCase().indexOf("webkit")&&!v("Edge"))&&!(v("Trident")||v("MSIE"))&&!v("Edge"),x=-1!=Qa.toLowerCase().indexOf("webkit")&&!v("Edge"),cb=x&&v("Mobile"),db=v("Macintosh");function eb(){var a=l.document;return a?a.documentMode:void 0}var fb;a:{var gb="",hb=function(){var a=Qa;if(bb)return/rv\:([^\);]+)(\)|;)/.exec(a);if($a)return/Edge\/([\d\.]+)/.exec(a);
if(w)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(x)return/WebKit\/(\S+)/.exec(a);if(Za)return/(?:Version)[ \/]?(\S+)/.exec(a)}();hb&&(gb=hb?hb[1]:"");if(w){var ib=eb();if(null!=ib&&ib>parseFloat(gb)){fb=String(ib);break a}}fb=gb}var jb={};function y(a){var b;if(!(b=jb[a])){b=0;for(var c=qa(String(fb)).split("."),d=qa(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f<e;f++){var g=c[f]||"",k=d[f]||"",z=RegExp("(\\d*)(\\D*)","g"),J=RegExp("(\\d*)(\\D*)","g");do{var ma=z.exec(g)||
["","",""],W=J.exec(k)||["","",""];if(0==ma[0].length&&0==W[0].length)break;b=za(0==ma[1].length?0:parseInt(ma[1],10),0==W[1].length?0:parseInt(W[1],10))||za(0==ma[2].length,0==W[2].length)||za(ma[2],W[2])}while(0==b)}b=jb[a]=0<=b}return b}var kb=l.document,lb=kb&&w?eb()||("CSS1Compat"==kb.compatMode?parseInt(fb,10):5):void 0;var mb=!w||9<=Number(lb),nb=!bb&&!w||w&&9<=Number(lb)||bb&&y("1.9.1");w&&y("9");function ob(){this.oa="";this.Jc=pb}ob.prototype.mc=!0;ob.prototype.kc=function(){return 1};ob.prototype.toString=
function(){return"SafeUrl{"+this.oa+"}"};function qb(a){if(a instanceof ob&&a.constructor===ob&&a.Jc===pb)return a.oa;Ba("expected object of type SafeUrl, got '"+a+"' of type "+ba(a));return"type_error:SafeUrl"}var rb=/^(?:(?:https?|mailto|ftp):|[^&:/?#]*(?:[/?#]|$))/i;function sb(a){if(a instanceof ob)return a;a=a.mc?a.oa:String(a);rb.test(a)||(a="about:invalid#zClosurez");return tb(a)}var pb={};function tb(a){var b=new ob;b.oa=a;return b}tb("about:blank");function ub(){this.oa="";this.Ic=vb;this.fc=
null}ub.prototype.kc=function(){return this.fc};ub.prototype.mc=!0;ub.prototype.toString=function(){return"SafeHtml{"+this.oa+"}"};function wb(a){if(a instanceof ub&&a.constructor===ub&&a.Ic===vb)return a.oa;Ba("expected object of type SafeHtml, got '"+a+"' of type "+ba(a));return"type_error:SafeHtml"}var vb={};ub.prototype.dd=function(a){this.oa=a;this.fc=null;return this};function xb(a){return a?new yb(zb(a)):oa||(oa=new yb)}function Ab(a,b){var c=b||document;return c.querySelectorAll&&c.querySelector?
c.querySelectorAll("."+a):Bb(a,b)}function Bb(a,b){var c,d,e,f;c=document;c=b||c;if(c.querySelectorAll&&c.querySelector&&a)return c.querySelectorAll(""+(a?"."+a:""));if(a&&c.getElementsByClassName){var g=c.getElementsByClassName(a);return g}g=c.getElementsByTagName("*");if(a){f={};for(d=e=0;c=g[d];d++){var k=c.className;"function"==typeof k.split&&Ja(k.split(/\s+/),a)&&(f[e++]=c)}f.length=e;return f}return g}function Cb(a,b){Ta(b,function(b,d){"style"==d?a.style.cssText=b:"class"==d?a.className=b:
"for"==d?a.htmlFor=b:Db.hasOwnProperty(d)?a.setAttribute(Db[d],b):0==d.lastIndexOf("aria-",0)||0==d.lastIndexOf("data-",0)?a.setAttribute(d,b):a[d]=b})}var Db={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"};function Eb(a,b,c,d){function e(c){c&&b.appendChild(n(c)?a.createTextNode(c):c)}for(;d<c.length;d++){var f=
c[d];!ea(f)||fa(f)&&0<f.nodeType?e(f):Da(Fb(f)?Pa(f):f,e)}}function Gb(a){return a&&a.parentNode?a.parentNode.removeChild(a):null}function zb(a){return 9==a.nodeType?a:a.ownerDocument||a.document}function Fb(a){if(a&&"number"==typeof a.length){if(fa(a))return"function"==typeof a.item||"string"==typeof a.item;if(p(a))return"function"==typeof a.item}return!1}function Hb(a){return Ib(a,function(a){return n(a.className)&&Ja(a.className.split(/\s+/),"firebaseui-textfield")})}function Ib(a,b){for(var c=
0;a;){if(b(a))return a;a=a.parentNode;c++}return null}function yb(a){this.ta=a||l.document||document}h=yb.prototype;h.ib=xb;h.L=function(a){return n(a)?this.ta.getElementById(a):a};h.Mb=function(a,b){return Ab(a,b||this.ta)};h.C=function(a,b){var c=b||this.ta,d=c||document;return(d.getElementsByClassName?d.getElementsByClassName(a)[0]:d.querySelectorAll&&d.querySelector?d.querySelector("."+a):Bb(a,c)[0])||null};h.Ib=function(a,b,c){var d=this.ta,e=arguments,f=String(e[0]),g=e[1];if(!mb&&g&&(g.name||
g.type)){f=["<",f];g.name&&f.push(' name="',ra(g.name),'"');if(g.type){f.push(' type="',ra(g.type),'"');var k={};Ya(k,g);delete k.type;g=k}f.push(">");f=f.join("")}f=d.createElement(f);g&&(n(g)?f.className=g:da(g)?f.className=g.join(" "):Cb(f,g));2<e.length&&Eb(d,f,e,2);return f};h.createElement=function(a){return this.ta.createElement(String(a))};h.createTextNode=function(a){return this.ta.createTextNode(String(a))};h.appendChild=function(a,b){a.appendChild(b)};h.append=function(a,b){Eb(zb(a),a,
arguments,1)};h.canHaveChildren=function(a){if(1!=a.nodeType)return!1;switch(a.tagName){case "APPLET":case "AREA":case "BASE":case "BR":case "COL":case "COMMAND":case "EMBED":case "FRAME":case "HR":case "IMG":case "INPUT":case "IFRAME":case "ISINDEX":case "KEYGEN":case "LINK":case "NOFRAMES":case "NOSCRIPT":case "META":case "OBJECT":case "PARAM":case "SCRIPT":case "SOURCE":case "STYLE":case "TRACK":case "WBR":return!1}return!0};h.removeNode=Gb;h.jc=function(a){return nb&&void 0!=a.children?a.children:
Fa(a.childNodes,function(a){return 1==a.nodeType})};h.contains=function(a,b){if(!a||!b)return!1;if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a==b||!!(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a};w&&y(8);var Jb={Xd:!0},Kb={Zd:!0},Lb={Yd:!0};function A(){throw Error("Do not instantiate directly");}A.prototype.ga=null;A.prototype.toString=function(){return this.content};function Mb(a,b,c,d){a:if(a=a(b||Nb,
void 0,c),d=(d||xb()).createElement("DIV"),a=Ob(a),a.match(Pb),d.innerHTML=a,1==d.childNodes.length&&(a=d.firstChild,1==a.nodeType)){d=a;break a}return d}function Ob(a){if(!fa(a))return String(a);if(a instanceof A){if(a.S===Jb)return a.content;if(a.S===Lb)return ra(a.content)}Ba("Soy template output is unsafe for use as HTML: "+a);return"zSoyz"}var Pb=/^<(body|caption|col|colgroup|head|html|tr|td|th|tbody|thead|tfoot)>/i,Nb={};function Qb(a){if(null!=a)switch(a.ga){case 1:return 1;case -1:return-1;
case 0:return 0}return null}function Rb(){A.call(this)}t(Rb,A);Rb.prototype.S=Jb;function B(a){return null!=a&&a.S===Jb?a:a instanceof ub?C(wb(a),a.kc()):C(ra(String(String(a))),Qb(a))}function Sb(){A.call(this)}t(Sb,A);Sb.prototype.S={Wd:!0};Sb.prototype.ga=1;function Tb(){A.call(this)}t(Tb,A);Tb.prototype.S=Kb;Tb.prototype.ga=1;function Ub(){A.call(this)}t(Ub,A);Ub.prototype.S={Vd:!0};Ub.prototype.ga=1;function Vb(){A.call(this)}t(Vb,A);Vb.prototype.S={Ud:!0};Vb.prototype.ga=1;function Wb(a,b){this.content=
String(a);this.ga=null!=b?b:null}t(Wb,A);Wb.prototype.S=Lb;function Xb(a){function b(a){this.content=a}b.prototype=a.prototype;return function(a){return new b(String(a))}}function D(a){return new Wb(a,void 0)}var C=function(a){function b(a){this.content=a}b.prototype=a.prototype;return function(a,d){var e=new b(String(a));void 0!==d&&(e.ga=d);return e}}(Rb);Xb(Sb);var Yb=Xb(Tb);Xb(Ub);Xb(Vb);function Zb(a){var b={label:$b("New password")};function c(){}c.prototype=a;a=new c;for(var d in b)a[d]=b[d];
return a}function $b(a){return(a=String(a))?new Wb(a,void 0):""}(function(a){function b(a){this.content=a}b.prototype=a.prototype;return function(a,d){var e=String(a);if(!e)return"";e=new b(e);void 0!==d&&(e.ga=d);return e}})(Rb);function ac(a){return null!=a&&a.S===Jb?String(String(a.content).replace(bc,"").replace(cc,"<")).replace(dc,ec):ra(String(a))}function fc(a){null!=a&&a.S===Kb?a=String(a).replace(gc,hc):a instanceof ob?a=String(qb(a)).replace(gc,hc):(a=String(a),ic.test(a)?a=a.replace(gc,
hc):(Ba("Bad value `%s` for |filterNormalizeUri",[a]),a="#zSoyz"));return a}var jc={"\x00":"�","\t":"	","\n":" ","\x0B":"","\f":"","\r":" "," ":" ",'"':""","&":"&","'":"'","-":"-","/":"/","<":"<","=":"=",">":">","`":"`","\u0085":"…","\u00a0":" ","\u2028":"
","\u2029":"
"};function ec(a){return jc[a]}var kc={"\x00":"%00","\u0001":"%01","\u0002":"%02","\u0003":"%03","\u0004":"%04","\u0005":"%05","\u0006":"%06","\u0007":"%07",
"\b":"%08","\t":"%09","\n":"%0A","\x0B":"%0B","\f":"%0C","\r":"%0D","\u000e":"%0E","\u000f":"%0F","\u0010":"%10","\u0011":"%11","\u0012":"%12","\u0013":"%13","\u0014":"%14","\u0015":"%15","\u0016":"%16","\u0017":"%17","\u0018":"%18","\u0019":"%19","\u001a":"%1A","\u001b":"%1B","\u001c":"%1C","\u001d":"%1D","\u001e":"%1E","\u001f":"%1F"," ":"%20",'"':"%22","'":"%27","(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C","{":"%7B","}":"%7D","\u007f":"%7F","\u0085":"%C2%85","\u00a0":"%C2%A0","\u2028":"%E2%80%A8",
"\u2029":"%E2%80%A9","\uff01":"%EF%BC%81","\uff03":"%EF%BC%83","\uff04":"%EF%BC%84","\uff06":"%EF%BC%86","\uff07":"%EF%BC%87","\uff08":"%EF%BC%88","\uff09":"%EF%BC%89","\uff0a":"%EF%BC%8A","\uff0b":"%EF%BC%8B","\uff0c":"%EF%BC%8C","\uff0f":"%EF%BC%8F","\uff1a":"%EF%BC%9A","\uff1b":"%EF%BC%9B","\uff1d":"%EF%BC%9D","\uff1f":"%EF%BC%9F","\uff20":"%EF%BC%A0","\uff3b":"%EF%BC%BB","\uff3d":"%EF%BC%BD"};function hc(a){return kc[a]}var dc=/[\x00\x22\x27\x3c\x3e]/g,gc=/[\x00- \x22\x27-\x29\x3c\x3e\\\x7b\x7d\x7f\x85\xa0\u2028\u2029\uff01\uff03\uff04\uff06-\uff0c\uff0f\uff1a\uff1b\uff1d\uff1f\uff20\uff3b\uff3d]/g,
ic=/^(?![^#?]*\/(?:\.|%2E){2}(?:[\/?#]|$))(?:(?:https?|mailto):|[^&:\/?#]*(?:[\/?#]|$))/i,bc=/<(?:!|\/?([a-zA-Z][a-zA-Z0-9:\-]*))(?:[^>'"]|"[^"]*"|'[^']*')*>/g,cc=/</g;function lc(a){a.prototype.then=a.prototype.then;a.prototype.$goog_Thenable=!0}function mc(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}}function nc(a,b,c){this.fd=c;this.Pc=a;this.pd=b;this.sb=0;this.nb=null}nc.prototype.get=function(){var a;0<this.sb?(this.sb--,a=this.nb,this.nb=a.next,a.next=null):a=this.Pc();
return a};nc.prototype.put=function(a){this.pd(a);this.sb<this.fd&&(this.sb++,a.next=this.nb,this.nb=a)};function oc(){this.Bb=this.La=null}var qc=new nc(function(){return new pc},function(a){a.reset()},100);oc.prototype.add=function(a,b){var c=qc.get();c.set(a,b);this.Bb?this.Bb.next=c:this.La=c;this.Bb=c};oc.prototype.remove=function(){var a=null;this.La&&(a=this.La,this.La=this.La.next,this.La||(this.Bb=null),a.next=null);return a};function pc(){this.next=this.scope=this.Lb=null}pc.prototype.set=
function(a,b){this.Lb=a;this.scope=b;this.next=null};pc.prototype.reset=function(){this.next=this.scope=this.Lb=null};function rc(a){l.setTimeout(function(){throw a;},0)}var sc;function tc(){var a=l.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&!v("Presto")&&(a=function(){var a=document.createElement("IFRAME");a.style.display="none";a.src="";document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");
a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=q(function(a){if(("*"==d||a.origin==d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&!v("Trident")&&!v("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(m(c.next)){c=c.next;var a=c.cc;c.cc=null;a()}};return function(a){d.next={cc:a};d=d.next;
b.port2.postMessage(0)}}return"undefined"!==typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(a){var b=document.createElement("SCRIPT");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};document.documentElement.appendChild(b)}:function(a){l.setTimeout(a,0)}}function uc(a,b){vc||wc();xc||(vc(),xc=!0);yc.add(a,b)}var vc;function wc(){if(l.Promise&&l.Promise.resolve){var a=l.Promise.resolve(void 0);vc=function(){a.then(zc)}}else vc=
function(){var a=zc;!p(l.setImmediate)||l.Window&&l.Window.prototype&&!v("Edge")&&l.Window.prototype.setImmediate==l.setImmediate?(sc||(sc=tc()),sc(a)):l.setImmediate(a)}}var xc=!1,yc=new oc;function zc(){for(var a;a=yc.remove();){try{a.Lb.call(a.scope)}catch(b){rc(b)}qc.put(a)}xc=!1}function E(a,b){this.R=Ac;this.ca=void 0;this.Ca=this.da=this.i=null;this.kb=this.Kb=!1;if(a!=aa)try{var c=this;a.call(b,function(a){Bc(c,Cc,a)},function(a){if(!(a instanceof Dc))try{if(a instanceof Error)throw a;throw Error("Promise rejected.");
}catch(b$0){}Bc(c,Ec,a)})}catch(d){Bc(this,Ec,d)}}var Ac=0,Cc=2,Ec=3;function Fc(){this.next=this.context=this.Ga=this.Ya=this.ra=null;this.cb=!1}Fc.prototype.reset=function(){this.context=this.Ga=this.Ya=this.ra=null;this.cb=!1};var Gc=new nc(function(){return new Fc},function(a){a.reset()},100);function Hc(a,b,c){var d=Gc.get();d.Ya=a;d.Ga=b;d.context=c;return d}function Ic(a){if(a instanceof E)return a;var b=new E(aa);Bc(b,Cc,a);return b}function Jc(a){return new E(function(b,c){c(a)})}E.prototype.then=
function(a,b,c){return Kc(this,p(a)?a:null,p(b)?b:null,c)};lc(E);function Lc(a){var b=Ic(Mc());return Kc(b,null,a,void 0)}E.prototype.cancel=function(a){this.R==Ac&&uc(function(){var b=new Dc(a);Nc(this,b)},this)};function Nc(a,b){if(a.R==Ac)if(a.i){var c=a.i;if(c.da){for(var d=0,e=null,f=null,g=c.da;g&&(g.cb||(d++,g.ra==a&&(e=g),!(e&&1<d)));g=g.next)e||(f=g);e&&(c.R==Ac&&1==d?Nc(c,b):(f?(d=f,d.next==c.Ca&&(c.Ca=d),d.next=d.next.next):Oc(c),Pc(c,e,Ec,b)))}a.i=null}else Bc(a,Ec,b)}function Qc(a,b){a.da||
a.R!=Cc&&a.R!=Ec||Rc(a);a.Ca?a.Ca.next=b:a.da=b;a.Ca=b}function Kc(a,b,c,d){var e=Hc(null,null,null);e.ra=new E(function(a,g){e.Ya=b?function(c){try{var e=b.call(d,c);a(e)}catch(J){g(J)}}:a;e.Ga=c?function(b){try{var e=c.call(d,b);!m(e)&&b instanceof Dc?g(b):a(e)}catch(J){g(J)}}:g});e.ra.i=a;Qc(a,e);return e.ra}E.prototype.xd=function(a){this.R=Ac;Bc(this,Cc,a)};E.prototype.yd=function(a){this.R=Ac;Bc(this,Ec,a)};function Bc(a,b,c){if(a.R==Ac){a===c&&(b=Ec,c=new TypeError("Promise cannot resolve to itself"));
a.R=1;var d;a:{var e=c,f=a.xd,g=a.yd;if(e instanceof E)Qc(e,Hc(f||aa,g||null,a)),d=!0;else if(mc(e))e.then(f,g,a),d=!0;else{if(fa(e))try{var k=e.then;if(p(k)){Sc(e,k,f,g,a);d=!0;break a}}catch(z){g.call(a,z);d=!0;break a}d=!1}}d||(a.ca=c,a.R=b,a.i=null,Rc(a),b!=Ec||c instanceof Dc||Tc(a,c))}}function Sc(a,b,c,d,e){function f(a){k||(k=!0,d.call(e,a))}function g(a){k||(k=!0,c.call(e,a))}var k=!1;try{b.call(a,g,f)}catch(z){f(z)}}function Rc(a){a.Kb||(a.Kb=!0,uc(a.Tc,a))}function Oc(a){var b=null;a.da&&
(b=a.da,a.da=b.next,b.next=null);a.da||(a.Ca=null);return b}E.prototype.Tc=function(){for(var a;a=Oc(this);)Pc(this,a,this.R,this.ca);this.Kb=!1};function Pc(a,b,c,d){if(c==Ec&&b.Ga&&!b.cb)for(;a&&a.kb;a=a.i)a.kb=!1;if(b.ra)b.ra.i=null,Uc(b,c,d);else try{b.cb?b.Ya.call(b.context):Uc(b,c,d)}catch(e){Vc.call(null,e)}Gc.put(b)}function Uc(a,b,c){b==Cc?a.Ya.call(a.context,c):a.Ga&&a.Ga.call(a.context,c)}function Tc(a,b){a.kb=!0;uc(function(){a.kb&&Vc.call(null,b)})}var Vc=rc;function Dc(a){u.call(this,
a)}t(Dc,u);Dc.prototype.name="cancel";function Wc(){0!=Xc&&(Yc[this[ga]||(this[ga]=++ha)]=this);this.Da=this.Da;this.za=this.za}var Xc=0,Yc={};Wc.prototype.Da=!1;Wc.prototype.j=function(){if(!this.Da&&(this.Da=!0,this.b(),0!=Xc)){var a=this[ga]||(this[ga]=++ha);delete Yc[a]}};function Zc(a,b){a.Da?m(void 0)?b.call(void 0):b():(a.za||(a.za=[]),a.za.push(m(void 0)?q(b,void 0):b))}Wc.prototype.b=function(){if(this.za)for(;this.za.length;)this.za.shift()()};function $c(a){a&&"function"==typeof a.j&&a.j()}
var ad=!w||9<=Number(lb),bd=w&&!y("9");!x||y("528");bb&&y("1.9b")||w&&y("8")||Za&&y("9.5")||x&&y("528");bb&&!y("8")||w&&y("9");function cd(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.Aa=!1;this.yc=!0}cd.prototype.stopPropagation=function(){this.Aa=!0};cd.prototype.preventDefault=function(){this.defaultPrevented=!0;this.yc=!1};function dd(a){dd[" "](a);return a}dd[" "]=aa;function F(a,b){cd.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;
this.charCode=this.keyCode=this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.U=this.state=null;a&&this.init(a,b)}t(F,cd);F.prototype.init=function(a,b){var c=this.type=a.type,d=a.changedTouches?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.currentTarget=b;var e=a.relatedTarget;if(e){if(bb){var f;a:{try{dd(e.nodeName);f=!0;break a}catch(g){}f=!1}f||(e=null)}}else"mouseover"==c?e=
a.fromElement:"mouseout"==c&&(e=a.toElement);this.relatedTarget=e;null===d?(this.offsetX=x||void 0!==a.offsetX?a.offsetX:a.layerX,this.offsetY=x||void 0!==a.offsetY?a.offsetY:a.layerY,this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0):(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0);this.button=
a.button;this.keyCode=a.keyCode||0;this.charCode=a.charCode||("keypress"==c?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.state=a.state;this.U=a;a.defaultPrevented&&this.preventDefault()};F.prototype.stopPropagation=function(){F.c.stopPropagation.call(this);this.U.stopPropagation?this.U.stopPropagation():this.U.cancelBubble=!0};F.prototype.preventDefault=function(){F.c.preventDefault.call(this);var a=this.U;if(a.preventDefault)a.preventDefault();
else if(a.returnValue=!1,bd)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};var ed="closure_listenable_"+(1E6*Math.random()|0);function fd(a){return!(!a||!a[ed])}var gd=0;function hd(a,b,c,d,e){this.listener=a;this.vb=null;this.src=b;this.type=c;this.Ma=!!d;this.mb=e;this.key=++gd;this.Ja=this.eb=!1}function id(a){a.Ja=!0;a.listener=null;a.vb=null;a.src=null;a.mb=null}function jd(a){this.src=a;this.F={};this.bb=0}h=jd.prototype;h.add=function(a,b,c,d,e){var f=a.toString();
a=this.F[f];a||(a=this.F[f]=[],this.bb++);var g=kd(a,b,d,e);-1<g?(b=a[g],c||(b.eb=!1)):(b=new hd(b,this.src,f,!!d,e),b.eb=c,a.push(b));return b};h.remove=function(a,b,c,d){a=a.toString();if(!(a in this.F))return!1;var e=this.F[a];b=kd(e,b,c,d);return-1<b?(id(e[b]),La(e,b),0==e.length&&(delete this.F[a],this.bb--),!0):!1};function ld(a,b){var c=b.type;c in a.F&&Ka(a.F[c],b)&&(id(b),0==a.F[c].length&&(delete a.F[c],a.bb--))}h.wb=function(a){a=a&&a.toString();var b=0,c;for(c in this.F)if(!a||c==a){for(var d=
this.F[c],e=0;e<d.length;e++)++b,id(d[e]);delete this.F[c];this.bb--}return b};h.Ta=function(a,b,c,d){a=this.F[a.toString()];var e=-1;a&&(e=kd(a,b,c,d));return-1<e?a[e]:null};h.hasListener=function(a,b){var c=m(a),d=c?a.toString():"",e=m(b);return Ua(this.F,function(a){for(var g=0;g<a.length;++g)if(!(c&&a[g].type!=d||e&&a[g].Ma!=b))return!0;return!1})};function kd(a,b,c,d){for(var e=0;e<a.length;++e){var f=a[e];if(!f.Ja&&f.listener==b&&f.Ma==!!c&&f.mb==d)return e}return-1}var md="closure_lm_"+(1E6*
Math.random()|0),nd={},od=0;function pd(a,b,c,d,e){if(da(b)){for(var f=0;f<b.length;f++)pd(a,b[f],c,d,e);return null}c=qd(c);return fd(a)?a.ka(b,c,d,e):rd(a,b,c,!1,d,e)}function rd(a,b,c,d,e,f){if(!b)throw Error("Invalid event type");var g=!!e,k=sd(a);k||(a[md]=k=new jd(a));c=k.add(b,c,d,e,f);if(c.vb)return c;d=td();c.vb=d;d.src=a;d.listener=c;if(a.addEventListener)a.addEventListener(b.toString(),d,g);else if(a.attachEvent)a.attachEvent(ud(b.toString()),d);else throw Error("addEventListener and attachEvent are unavailable.");
od++;return c}function td(){var a=vd,b=ad?function(c){return a.call(b.src,b.listener,c)}:function(c){c=a.call(b.src,b.listener,c);if(!c)return c};return b}function wd(a,b,c,d,e){if(da(b)){for(var f=0;f<b.length;f++)wd(a,b[f],c,d,e);return null}c=qd(c);return fd(a)?a.oc(b,c,d,e):rd(a,b,c,!0,d,e)}function xd(a,b,c,d,e){if(da(b))for(var f=0;f<b.length;f++)xd(a,b[f],c,d,e);else c=qd(c),fd(a)?a.Zb(b,c,d,e):a&&(a=sd(a))&&(b=a.Ta(b,c,!!d,e))&&yd(b)}function yd(a){if("number"==typeof a||!a||a.Ja)return;var b=
a.src;if(fd(b)){ld(b.T,a);return}var c=a.type,d=a.vb;b.removeEventListener?b.removeEventListener(c,d,a.Ma):b.detachEvent&&b.detachEvent(ud(c),d);od--;(c=sd(b))?(ld(c,a),0==c.bb&&(c.src=null,b[md]=null)):id(a)}function ud(a){return a in nd?nd[a]:nd[a]="on"+a}function zd(a,b,c,d){var e=!0;if(a=sd(a))if(b=a.F[b.toString()])for(b=b.concat(),a=0;a<b.length;a++){var f=b[a];f&&f.Ma==c&&!f.Ja&&(f=Ad(f,d),e=e&&!1!==f)}return e}function Ad(a,b){var c=a.listener,d=a.mb||a.src;a.eb&&yd(a);return c.call(d,b)}
function vd(a,b){if(a.Ja)return!0;if(!ad){var c;if(!(c=b))a:{c=["window","event"];for(var d=l,e;e=c.shift();)if(null!=d[e])d=d[e];else{c=null;break a}c=d}e=c;c=new F(e,this);d=!0;if(!(0>e.keyCode||void 0!=e.returnValue)){a:{var f=!1;if(0==e.keyCode)try{e.keyCode=-1;break a}catch(z){f=!0}if(f||void 0==e.returnValue)e.returnValue=!0}e=[];for(f=c.currentTarget;f;f=f.parentNode)e.push(f);for(var f=a.type,g=e.length-1;!c.Aa&&0<=g;g--){c.currentTarget=e[g];var k=zd(e[g],f,!0,c),d=d&&k}for(g=0;!c.Aa&&g<
e.length;g++)c.currentTarget=e[g],k=zd(e[g],f,!1,c),d=d&&k}return d}return Ad(a,new F(b,this))}function sd(a){a=a[md];return a instanceof jd?a:null}var Bd="__closure_events_fn_"+(1E9*Math.random()>>>0);function qd(a){if(p(a))return a;a[Bd]||(a[Bd]=function(b){return a.handleEvent(b)});return a[Bd]}function G(){Wc.call(this);this.T=new jd(this);this.Kc=this;this.ub=null}t(G,Wc);G.prototype[ed]=!0;h=G.prototype;h.Xb=function(a){this.ub=a};h.addEventListener=function(a,b,c,d){pd(this,a,b,c,d)};h.removeEventListener=
function(a,b,c,d){xd(this,a,b,c,d)};h.dispatchEvent=function(a){var b,c=this.ub;if(c)for(b=[];c;c=c.ub)b.push(c);var c=this.Kc,d=a.type||a;if(n(a))a=new cd(a,c);else if(a instanceof cd)a.target=a.target||c;else{var e=a;a=new cd(d,c);Ya(a,e)}var e=!0,f;if(b)for(var g=b.length-1;!a.Aa&&0<=g;g--)f=a.currentTarget=b[g],e=Cd(f,d,!0,a)&&e;a.Aa||(f=a.currentTarget=c,e=Cd(f,d,!0,a)&&e,a.Aa||(e=Cd(f,d,!1,a)&&e));if(b)for(g=0;!a.Aa&&g<b.length;g++)f=a.currentTarget=b[g],e=Cd(f,d,!1,a)&&e;return e};h.b=function(){G.c.b.call(this);
this.T&&this.T.wb(void 0);this.ub=null};h.ka=function(a,b,c,d){return this.T.add(String(a),b,!1,c,d)};h.oc=function(a,b,c,d){return this.T.add(String(a),b,!0,c,d)};h.Zb=function(a,b,c,d){return this.T.remove(String(a),b,c,d)};function Cd(a,b,c,d){b=a.T.F[String(b)];if(!b)return!0;b=b.concat();for(var e=!0,f=0;f<b.length;++f){var g=b[f];if(g&&!g.Ja&&g.Ma==c){var k=g.listener,z=g.mb||g.src;g.eb&&ld(a.T,g);e=!1!==k.call(z,d)&&e}}return e&&0!=d.yc}h.Ta=function(a,b,c,d){return this.T.Ta(String(a),b,c,
d)};h.hasListener=function(a,b){return this.T.hasListener(m(a)?String(a):void 0,b)};function Dd(a,b){if(p(a))b&&(a=q(a,b));else if(a&&"function"==typeof a.handleEvent)a=q(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647<Number(0)?-1:l.setTimeout(a,0)}function Ed(a){if(a.O&&"function"==typeof a.O)return a.O();if(n(a))return a.split("");if(ea(a)){for(var b=[],c=a.length,d=0;d<c;d++)b.push(a[d]);return b}return Va(a)}function Fd(a,b,c){if(a.forEach&&"function"==typeof a.forEach)a.forEach(b,
c);else if(ea(a)||n(a))Da(a,b,c);else{var d;if(a.ha&&"function"==typeof a.ha)d=a.ha();else if(a.O&&"function"==typeof a.O)d=void 0;else if(ea(a)||n(a)){d=[];for(var e=a.length,f=0;f<e;f++)d.push(f)}else d=Wa(a);for(var e=Ed(a),f=e.length,g=0;g<f;g++)b.call(c,e[g],d&&d[g],a)}}var Gd="StopIteration"in l?l.StopIteration:{message:"StopIteration",stack:""};function Hd(){}Hd.prototype.next=function(){throw Gd;};Hd.prototype.qa=function(){return this};function Id(a){if(a instanceof Hd)return a;if("function"==
typeof a.qa)return a.qa(!1);if(ea(a)){var b=0,c=new Hd;c.next=function(){for(;;){if(b>=a.length)throw Gd;if(b in a)return a[b++];b++}};return c}throw Error("Not implemented");}function Jd(a,b){if(ea(a))try{Da(a,b,void 0)}catch(c){if(c!==Gd)throw c;}else{a=Id(a);try{for(;;)b.call(void 0,a.next(),void 0,a)}catch(c$1){if(c$1!==Gd)throw c$1;}}}function Kd(a){if(ea(a))return Pa(a);a=Id(a);var b=[];Jd(a,function(a){b.push(a)});return b}function Ld(a,b){this.P={};this.m=[];this.Ka=this.w=0;var c=arguments.length;
if(1<c){if(c%2)throw Error("Uneven number of arguments");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else a&&this.addAll(a)}h=Ld.prototype;h.O=function(){Md(this);for(var a=[],b=0;b<this.m.length;b++)a.push(this.P[this.m[b]]);return a};h.ha=function(){Md(this);return this.m.concat()};h.Oa=function(a){return Nd(this.P,a)};h.clear=function(){this.P={};this.Ka=this.w=this.m.length=0};h.remove=function(a){return Nd(this.P,a)?(delete this.P[a],this.w--,this.Ka++,this.m.length>2*this.w&&
Md(this),!0):!1};function Md(a){if(a.w!=a.m.length){for(var b=0,c=0;b<a.m.length;){var d=a.m[b];Nd(a.P,d)&&(a.m[c++]=d);b++}a.m.length=c}if(a.w!=a.m.length){for(var e={},c=b=0;b<a.m.length;)d=a.m[b],Nd(e,d)||(a.m[c++]=d,e[d]=1),b++;a.m.length=c}}h.get=function(a,b){return Nd(this.P,a)?this.P[a]:b};h.set=function(a,b){Nd(this.P,a)||(this.w++,this.m.push(a),this.Ka++);this.P[a]=b};h.addAll=function(a){var b;a instanceof Ld?(b=a.ha(),a=a.O()):(b=Wa(a),a=Va(a));for(var c=0;c<b.length;c++)this.set(b[c],
a[c])};h.forEach=function(a,b){for(var c=this.ha(),d=0;d<c.length;d++){var e=c[d],f=this.get(e);a.call(b,f,e,this)}};h.clone=function(){return new Ld(this)};h.qa=function(a){Md(this);var b=0,c=this.Ka,d=this,e=new Hd;e.next=function(){if(c!=d.Ka)throw Error("The map has changed since the iterator was created");if(b>=d.m.length)throw Gd;var e=d.m[b++];return a?e:d.P[e]};return e};function Nd(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function Od(a,b,c,d,e){this.reset(a,b,c,d,e)}Od.prototype.Jb=
null;var Pd=0;Od.prototype.reset=function(a,b,c,d,e){"number"==typeof e||Pd++;this.Fc=d||la();this.ya=a;this.rc=b;this.qc=c;delete this.Jb};Od.prototype.Ac=function(a){this.ya=a};function Qd(a){this.sc=a;this.Wa=this.fa=this.ya=this.i=null}function Rd(a,b){this.name=a;this.value=b}Rd.prototype.toString=function(){return this.name};var Sd=new Rd("SHOUT",1200),Td=new Rd("SEVERE",1E3),Ud=new Rd("WARNING",900),Vd=new Rd("INFO",800),Wd=new Rd("CONFIG",700);h=Qd.prototype;h.getName=function(){return this.sc};
h.getParent=function(){return this.i};h.jc=function(){this.fa||(this.fa={});return this.fa};h.Ac=function(a){this.ya=a};function Xd(a){if(a.ya)return a.ya;if(a.i)return Xd(a.i);Ba("Root logger has no level set.");return null}h.log=function(a,b,c){if(a.value>=Xd(this).value)for(p(b)&&(b=b()),a=new Od(a,String(b),this.sc),c&&(a.Jb=c),c="log:"+a.rc,l.console&&(l.console.timeStamp?l.console.timeStamp(c):l.console.markTimeline&&l.console.markTimeline(c)),l.msWriteProfilerMark&&l.msWriteProfilerMark(c),
c=this;c;){b=c;var d=a;if(b.Wa)for(var e=0,f;f=b.Wa[e];e++)f(d);c=c.getParent()}};h.info=function(a,b){this.log(Vd,a,b)};var Yd={},Zd=null;function $d(){Zd||(Zd=new Qd(""),Yd[""]=Zd,Zd.Ac(Wd))}function ae(a){$d();var b;if(!(b=Yd[a])){b=new Qd(a);var c=a.lastIndexOf("."),d=a.substr(c+1),c=ae(a.substr(0,c));c.jc()[d]=b;b.i=c;Yd[a]=b}return b}function be(){this.xc=la()}var ce=new be;be.prototype.set=function(a){this.xc=a};be.prototype.reset=function(){this.set(la())};be.prototype.get=function(){return this.xc};
function de(a){this.na=a||"";this.ud=ce}h=de.prototype;h.bc=!0;h.Bc=!0;h.rd=!0;h.qd=!0;h.Cc=!1;h.sd=!1;function ee(a){return 10>a?"0"+a:String(a)}function fe(a,b){var c=(a.Fc-b)/1E3,d=c.toFixed(3),e=0;if(1>c)e=2;else for(;100>c;)e++,c*=10;for(;0<e--;)d=" "+d;return d}function ge(a){de.call(this,a)}t(ge,de);function he(){this.od=q(this.Lc,this);this.hb=new ge;this.hb.Bc=!1;this.hb.Cc=!1;this.nc=this.hb.bc=!1;this.pc="";this.Vc={}}he.prototype.Lc=function(a){if(!this.Vc[a.qc]){var b;b=this.hb;var c=
[];c.push(b.na," ");if(b.Bc){var d=new Date(a.Fc);c.push("[",ee(d.getFullYear()-2E3)+ee(d.getMonth()+1)+ee(d.getDate())+" "+ee(d.getHours())+":"+ee(d.getMinutes())+":"+ee(d.getSeconds())+"."+ee(Math.floor(d.getMilliseconds()/10)),"] ")}b.rd&&c.push("[",fe(a,b.ud.get()),"s] ");b.qd&&c.push("[",a.qc,"] ");b.sd&&c.push("[",a.ya.name,"] ");c.push(a.rc);b.Cc&&(d=a.Jb)&&c.push("\n",d instanceof Error?d.message:d.toString());b.bc&&c.push("\n");b=c.join("");if(c=ie)switch(a.ya){case Sd:je(c,"info",b);break;
case Td:je(c,"error",b);break;case Ud:je(c,"warn",b);break;default:je(c,"debug",b)}else this.pc+=b}};var ie=l.console;function je(a,b,c){if(a[b])a[b](c);else a.log(c)}function ke(a){if(a.altKey&&!a.ctrlKey||a.metaKey||112<=a.keyCode&&123>=a.keyCode)return!1;switch(a.keyCode){case 18:case 20:case 93:case 17:case 40:case 35:case 27:case 36:case 45:case 37:case 224:case 91:case 144:case 12:case 34:case 33:case 19:case 255:case 44:case 39:case 145:case 16:case 38:case 252:case 224:case 92:return!1;case 0:return!bb;
default:return 166>a.keyCode||183<a.keyCode}}function le(a,b,c,d,e){if(!(w||$a||x&&y("525")))return!0;if(db&&e)return me(a);if(e&&!d)return!1;"number"==typeof b&&(b=ne(b));if(!c&&(17==b||18==b||db&&91==b))return!1;if((x||$a)&&d&&c)switch(a){case 220:case 219:case 221:case 192:case 186:case 189:case 187:case 188:case 190:case 191:case 192:case 222:return!1}if(w&&d&&b==a)return!1;switch(a){case 13:return!0;case 27:return!(x||$a)}return me(a)}function me(a){if(48<=a&&57>=a||96<=a&&106>=a||65<=a&&90>=
a||(x||$a)&&0==a)return!0;switch(a){case 32:case 43:case 63:case 64:case 107:case 109:case 110:case 111:case 186:case 59:case 189:case 187:case 61:case 188:case 190:case 191:case 192:case 222:case 219:case 220:case 221:return!0;default:return!1}}function ne(a){if(bb)a=oe(a);else if(db&&x)a:switch(a){case 93:a=91;break a}return a}function oe(a){switch(a){case 61:return 187;case 59:return 186;case 173:return 189;case 224:return 91;case 0:return 224;default:return a}}function pe(a,b){this.yb=[];this.tc=
a;this.ec=b||null;this.Va=this.Ea=!1;this.ca=void 0;this.Yb=this.Nc=this.Eb=!1;this.Ab=0;this.i=null;this.Fb=0}pe.prototype.cancel=function(a){if(this.Ea)this.ca instanceof pe&&this.ca.cancel();else{if(this.i){var b=this.i;delete this.i;a?b.cancel(a):(b.Fb--,0>=b.Fb&&b.cancel())}this.tc?this.tc.call(this.ec,this):this.Yb=!0;this.Ea||(a=new qe,re(this),se(this,!1,a))}};pe.prototype.dc=function(a,b){this.Eb=!1;se(this,a,b)};function se(a,b,c){a.Ea=!0;a.ca=c;a.Va=!b;te(a)}function re(a){if(a.Ea){if(!a.Yb)throw new ue;
a.Yb=!1}}function ve(a,b,c){a.yb.push([b,c,void 0]);a.Ea&&te(a)}pe.prototype.then=function(a,b,c){var d,e,f=new E(function(a,b){d=a;e=b});ve(this,d,function(a){a instanceof qe?f.cancel():e(a)});return f.then(a,b,c)};lc(pe);function we(a){return Ha(a.yb,function(a){return p(a[1])})}function te(a){if(a.Ab&&a.Ea&&we(a)){var b=a.Ab,c=xe[b];c&&(l.clearTimeout(c.va),delete xe[b]);a.Ab=0}a.i&&(a.i.Fb--,delete a.i);for(var b=a.ca,d=c=!1;a.yb.length&&!a.Eb;){var e=a.yb.shift(),f=e[0],g=e[1],e=e[2];if(f=a.Va?
g:f)try{var k=f.call(e||a.ec,b);m(k)&&(a.Va=a.Va&&(k==b||k instanceof Error),a.ca=b=k);if(mc(b)||"function"===typeof l.Promise&&b instanceof l.Promise)d=!0,a.Eb=!0}catch(z){b=z,a.Va=!0,we(a)||(c=!0)}}a.ca=b;d&&(k=q(a.dc,a,!0),d=q(a.dc,a,!1),b instanceof pe?(ve(b,k,d),b.Nc=!0):b.then(k,d));c&&(b=new ye(b),xe[b.va]=b,a.Ab=b.va)}function ue(){u.call(this)}t(ue,u);ue.prototype.message="Deferred has already fired";ue.prototype.name="AlreadyCalledError";function qe(){u.call(this)}t(qe,u);qe.prototype.message=
"Deferred was canceled";qe.prototype.name="CanceledError";function ye(a){this.va=l.setTimeout(q(this.vd,this),0);this.Sc=a}ye.prototype.vd=function(){delete xe[this.va];throw this.Sc;};var xe={};var ze=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/;function Ae(a,b){if(a)for(var c=a.split("&"),d=0;d<c.length;d++){var e=c[d].indexOf("="),f,g=null;0<=e?(f=c[d].substring(0,e),g=c[d].substring(e+1)):f=c[d];b(f,g?decodeURIComponent(g.replace(/\+/g,
" ")):"")}}function Be(a,b,c,d){for(var e=c.length;0<=(b=a.indexOf(c,b))&&b<d;){var f=a.charCodeAt(b-1);if(38==f||63==f)if(f=a.charCodeAt(b+e),!f||61==f||38==f||35==f)return b;b+=e+1}return-1}var Ce=/#|$/;function De(a,b){var c=a.search(Ce),d=Be(a,0,b,c);if(0>d)return null;var e=a.indexOf("&",d);if(0>e||e>c)e=c;d+=b.length+1;return decodeURIComponent(a.substr(d,e-d).replace(/\+/g," "))}var Ee=/[?&]($|#)/;function Fe(a,b){this.Z=this.Ba=this.pa="";this.Ia=null;this.Sa=this.X="";this.M=this.ed=!1;var c;
if(a instanceof Fe)this.M=m(b)?b:a.M,Ge(this,a.pa),c=a.Ba,H(this),this.Ba=c,c=a.Z,H(this),this.Z=c,He(this,a.Ia),c=a.X,H(this),this.X=c,Ie(this,a.ba.clone()),Je(this,a.Sa);else if(a&&(c=String(a).match(ze))){this.M=!!b;Ge(this,c[1]||"",!0);var d=c[2]||"";H(this);this.Ba=Ke(d);d=c[3]||"";H(this);this.Z=Ke(d,!0);He(this,c[4]);d=c[5]||"";H(this);this.X=Ke(d,!0);Ie(this,c[6]||"",!0);Je(this,c[7]||"",!0)}else this.M=!!b,this.ba=new Le(null,0,this.M)}Fe.prototype.toString=function(){var a=[],b=this.pa;
b&&a.push(Me(b,Ne,!0),":");var c=this.Z;if(c||"file"==b)a.push("//"),(b=this.Ba)&&a.push(Me(b,Ne,!0),"@"),a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c=this.Ia,null!=c&&a.push(":",String(c));if(c=this.X)this.Z&&"/"!=c.charAt(0)&&a.push("/"),a.push(Me(c,"/"==c.charAt(0)?Oe:Pe,!0));(c=this.ba.toString())&&a.push("?",c);(c=this.Sa)&&a.push("#",Me(c,Qe));return a.join("")};Fe.prototype.resolve=function(a){var b=this.clone(),c=!!a.pa;c?Ge(b,a.pa):c=!!a.Ba;if(c){var d=a.Ba;
H(b);b.Ba=d}else c=!!a.Z;c?(d=a.Z,H(b),b.Z=d):c=null!=a.Ia;d=a.X;if(c)He(b,a.Ia);else if(c=!!a.X){if("/"!=d.charAt(0))if(this.Z&&!this.X)d="/"+d;else{var e=b.X.lastIndexOf("/");-1!=e&&(d=b.X.substr(0,e+1)+d)}e=d;if(".."==e||"."==e)d="";else if(-1!=e.indexOf("./")||-1!=e.indexOf("/.")){for(var d=0==e.lastIndexOf("/",0),e=e.split("/"),f=[],g=0;g<e.length;){var k=e[g++];"."==k?d&&g==e.length&&f.push(""):".."==k?((1<f.length||1==f.length&&""!=f[0])&&f.pop(),d&&g==e.length&&f.push("")):(f.push(k),d=!0)}d=
f.join("/")}else d=e}c?(H(b),b.X=d):c=""!==a.ba.toString();c?Ie(b,Ke(a.ba.toString())):c=!!a.Sa;c&&Je(b,a.Sa);return b};Fe.prototype.clone=function(){return new Fe(this)};function Ge(a,b,c){H(a);a.pa=c?Ke(b,!0):b;a.pa&&(a.pa=a.pa.replace(/:$/,""))}function He(a,b){H(a);if(b){b=Number(b);if(isNaN(b)||0>b)throw Error("Bad port number "+b);a.Ia=b}else a.Ia=null}function Ie(a,b,c){H(a);b instanceof Le?(a.ba=b,a.ba.Wb(a.M)):(c||(b=Me(b,Re)),a.ba=new Le(b,0,a.M));return a}function Je(a,b,c){H(a);a.Sa=c?
Ke(b):b;return a}function H(a){if(a.ed)throw Error("Tried to modify a read-only Uri");}Fe.prototype.Wb=function(a){this.M=a;this.ba&&this.ba.Wb(a);return this};function Se(a){return a instanceof Fe?a.clone():new Fe(a,void 0)}function Te(a){var b=window.location.href;b instanceof Fe||(b=Se(b));a instanceof Fe||(a=Se(a));return b.resolve(a)}function Ke(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Me(a,b,c){return n(a)?(a=encodeURI(a).replace(b,Ue),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,
"%$1")),a):null}function Ue(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)}var Ne=/[#\/\?@]/g,Pe=/[\#\?:]/g,Oe=/[\#\?]/g,Re=/[\#\?@]/g,Qe=/#/g;function Le(a,b,c){this.w=this.v=null;this.I=a||null;this.M=!!c}function Ve(a){a.v||(a.v=new Ld,a.w=0,a.I&&Ae(a.I,function(b,c){a.add(decodeURIComponent(b.replace(/\+/g," ")),c)}))}h=Le.prototype;h.add=function(a,b){Ve(this);this.I=null;a=We(this,a);var c=this.v.get(a);c||this.v.set(a,c=[]);c.push(b);this.w+=1;return this};h.remove=
function(a){Ve(this);a=We(this,a);return this.v.Oa(a)?(this.I=null,this.w-=this.v.get(a).length,this.v.remove(a)):!1};h.clear=function(){this.v=this.I=null;this.w=0};h.Oa=function(a){Ve(this);a=We(this,a);return this.v.Oa(a)};h.ha=function(){Ve(this);for(var a=this.v.O(),b=this.v.ha(),c=[],d=0;d<b.length;d++)for(var e=a[d],f=0;f<e.length;f++)c.push(b[d]);return c};h.O=function(a){Ve(this);var b=[];if(n(a))this.Oa(a)&&(b=Oa(b,this.v.get(We(this,a))));else{a=this.v.O();for(var c=0;c<a.length;c++)b=
Oa(b,a[c])}return b};h.set=function(a,b){Ve(this);this.I=null;a=We(this,a);this.Oa(a)&&(this.w-=this.v.get(a).length);this.v.set(a,[b]);this.w+=1;return this};h.get=function(a,b){var c=a?this.O(a):[];return 0<c.length?String(c[0]):b};h.toString=function(){if(this.I)return this.I;if(!this.v)return"";for(var a=[],b=this.v.ha(),c=0;c<b.length;c++)for(var d=b[c],e=encodeURIComponent(String(d)),d=this.O(d),f=0;f<d.length;f++){var g=e;""!==d[f]&&(g+="="+encodeURIComponent(String(d[f])));a.push(g)}return this.I=
a.join("&")};h.clone=function(){var a=new Le;a.I=this.I;this.v&&(a.v=this.v.clone(),a.w=this.w);return a};function We(a,b){var c=String(b);a.M&&(c=c.toLowerCase());return c}h.Wb=function(a){a&&!this.M&&(Ve(this),this.I=null,this.v.forEach(function(a,c){var d=c.toLowerCase();c!=d&&(this.remove(c),this.remove(d),0<a.length&&(this.I=null,this.v.set(We(this,d),Pa(a)),this.w+=a.length))},this));this.M=a};h.extend=function(a){for(var b=0;b<arguments.length;b++)Fd(arguments[b],function(a,b){this.add(b,a)},
this)};function Xe(a){a=String(a);if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function Ye(a){var b=[];Ze(new $e,a,b);return b.join("")}function $e(){this.xb=void 0}function Ze(a,b,c){if(null==
b)c.push("null");else{if("object"==typeof b){if(da(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f<b;f++)c.push(e),e=d[f],Ze(a,a.xb?a.xb.call(d,String(f),e):e,c),e=",";c.push("]");return}if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();else{c.push("{");f="";for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(e=b[d],"function"!=typeof e&&(c.push(f),af(d,c),c.push(":"),Ze(a,a.xb?a.xb.call(b,d,e):e,c),f=","));c.push("}");return}}switch(typeof b){case "string":af(b,
c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?String(b):"null");break;case "boolean":c.push(String(b));break;case "function":c.push("null");break;default:throw Error("Unknown type: "+typeof b);}}}var bf={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},cf=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g;function af(a,b){b.push('"',a.replace(cf,function(a){var b=bf[a];b||(b="\\u"+(a.charCodeAt(0)|65536).toString(16).substr(1),
bf[a]=b);return b}),'"')}function df(a){Wc.call(this);this.Pb=a;this.m={}}t(df,Wc);var ef=[];h=df.prototype;h.ka=function(a,b,c,d){da(b)||(b&&(ef[0]=b.toString()),b=ef);for(var e=0;e<b.length;e++){var f=pd(a,b[e],c||this.handleEvent,d||!1,this.Pb||this);if(!f)break;this.m[f.key]=f}return this};h.oc=function(a,b,c,d){return ff(this,a,b,c,d)};function ff(a,b,c,d,e,f){if(da(c))for(var g=0;g<c.length;g++)ff(a,b,c[g],d,e,f);else{b=wd(b,c,d||a.handleEvent,e,f||a.Pb||a);if(!b)return a;a.m[b.key]=b}return a}
h.Zb=function(a,b,c,d,e){if(da(b))for(var f=0;f<b.length;f++)this.Zb(a,b[f],c,d,e);else c=c||this.handleEvent,e=e||this.Pb||this,c=qd(c),d=!!d,b=fd(a)?a.Ta(b,c,d,e):a?(a=sd(a))?a.Ta(b,c,d,e):null:null,b&&(yd(b),delete this.m[b.key]);return this};h.wb=function(){Ta(this.m,function(a,b){this.m.hasOwnProperty(b)&&yd(a)},this);this.m={}};h.b=function(){df.c.b.call(this);this.wb()};h.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented");};function gf(){}gf.Wc=function(){return gf.$?
gf.$:gf.$=new gf};gf.prototype.jd=0;function hf(a){G.call(this);this.Pa=a||xb();this.va=null;this.wa=!1;this.f=null;this.ia=void 0;this.fb=this.fa=this.i=null;this.Ad=!1}t(hf,G);h=hf.prototype;h.ad=gf.Wc();h.L=function(){return this.f};h.Mb=function(a){return this.f?this.Pa.Mb(a,this.f):[]};h.C=function(a){return this.f?this.Pa.C(a,this.f):null};function jf(a){a.ia||(a.ia=new df(a));return a.ia}h.getParent=function(){return this.i};h.Xb=function(a){if(this.i&&this.i!=a)throw Error("Method not supported");
hf.c.Xb.call(this,a)};h.ib=function(){return this.Pa};h.Ib=function(){this.f=this.Pa.createElement("DIV")};function I(a,b){if(a.wa)throw Error("Component already rendered");a.f||a.Ib();b?b.insertBefore(a.f,null):a.Pa.ta.body.appendChild(a.f);a.i&&!a.i.wa||a.l()}h.l=function(){this.wa=!0;kf(this,function(a){!a.wa&&a.L()&&a.l()})};h.Ra=function(){kf(this,function(a){a.wa&&a.Ra()});this.ia&&this.ia.wb();this.wa=!1};h.b=function(){this.wa&&this.Ra();this.ia&&(this.ia.j(),delete this.ia);kf(this,function(a){a.j()});
!this.Ad&&this.f&&Gb(this.f);this.i=this.f=this.fb=this.fa=null;hf.c.b.call(this)};function kf(a,b){a.fa&&Da(a.fa,b,void 0)}h.removeChild=function(a,b){if(a){var c=n(a)?a:a.va||(a.va=":"+(a.ad.jd++).toString(36)),d;this.fb&&c?(d=this.fb,d=(null!==d&&c in d?d[c]:void 0)||null):d=null;a=d;if(c&&a){d=this.fb;c in d&&delete d[c];Ka(this.fa,a);b&&(a.Ra(),a.f&&Gb(a.f));c=a;if(null==c)throw Error("Unable to set parent component");c.i=null;hf.c.Xb.call(c,null)}}if(!a)throw Error("Child is not in parent component");
return a};function lf(a){if(a.classList)return a.classList;a=a.className;return n(a)&&a.match(/\S+/g)||[]}function mf(a,b){return a.classList?a.classList.contains(b):Ja(lf(a),b)}function nf(a,b){a.classList?a.classList.add(b):mf(a,b)||(a.className+=0<a.className.length?" "+b:b)}function of(a,b){a.classList?a.classList.remove(b):mf(a,b)&&(a.className=Fa(lf(a),function(a){return a!=b}).join(" "))}function pf(a,b){G.call(this);a&&(this.qb&&this.detach(),this.f=a,this.pb=pd(this.f,"keypress",this,b),
this.Tb=pd(this.f,"keydown",this.lb,b,this),this.qb=pd(this.f,"keyup",this.$c,b,this))}t(pf,G);h=pf.prototype;h.f=null;h.pb=null;h.Tb=null;h.qb=null;h.K=-1;h.ja=-1;h.Db=!1;var qf={3:13,12:144,63232:38,63233:40,63234:37,63235:39,63236:112,63237:113,63238:114,63239:115,63240:116,63241:117,63242:118,63243:119,63244:120,63245:121,63246:122,63247:123,63248:44,63272:46,63273:36,63275:35,63276:33,63277:34,63289:144,63302:45},rf={Up:38,Down:40,Left:37,Right:39,Enter:13,F1:112,F2:113,F3:114,F4:115,F5:116,
F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,"U+007F":46,Home:36,End:35,PageUp:33,PageDown:34,Insert:45},sf=w||$a||x&&y("525"),tf=db&&bb;h=pf.prototype;h.lb=function(a){if(x||$a)if(17==this.K&&!a.ctrlKey||18==this.K&&!a.altKey||db&&91==this.K&&!a.metaKey)this.ja=this.K=-1;-1==this.K&&(a.ctrlKey&&17!=a.keyCode?this.K=17:a.altKey&&18!=a.keyCode?this.K=18:a.metaKey&&91!=a.keyCode&&(this.K=91));sf&&!le(a.keyCode,this.K,a.shiftKey,a.ctrlKey,a.altKey)?this.handleEvent(a):(this.ja=ne(a.keyCode),tf&&
(this.Db=a.altKey))};h.$c=function(a){this.ja=this.K=-1;this.Db=a.altKey};h.handleEvent=function(a){var b=a.U,c,d,e=b.altKey;w&&"keypress"==a.type?(c=this.ja,d=13!=c&&27!=c?b.keyCode:0):(x||$a)&&"keypress"==a.type?(c=this.ja,d=0<=b.charCode&&63232>b.charCode&&me(c)?b.charCode:0):Za&&!x?(c=this.ja,d=me(c)?b.keyCode:0):(c=b.keyCode||this.ja,d=b.charCode||0,tf&&(e=this.Db),db&&63==d&&224==c&&(c=191));var f=c=ne(c),g=b.keyIdentifier;c?63232<=c&&c in qf?f=qf[c]:25==c&&a.shiftKey&&(f=9):g&&g in rf&&(f=
rf[g]);a=f==this.K;this.K=f;b=new uf(f,d,a,b);b.altKey=e;this.dispatchEvent(b)};h.L=function(){return this.f};h.detach=function(){this.pb&&(yd(this.pb),yd(this.Tb),yd(this.qb),this.qb=this.Tb=this.pb=null);this.f=null;this.ja=this.K=-1};h.b=function(){pf.c.b.call(this);this.detach()};function uf(a,b,c,d){F.call(this,d);this.type="key";this.keyCode=a;this.charCode=b;this.repeat=c}t(uf,F);var vf=!w;function K(a){var b=a.type;if(!m(b))return null;switch(b.toLowerCase()){case "checkbox":case "radio":return a.checked?
a.value:null;case "select-one":return b=a.selectedIndex,0<=b?a.options[b].value:null;case "select-multiple":for(var b=[],c,d=0;c=a.options[d];d++)c.selected&&b.push(c.value);return b.length?b:null;default:return m(a.value)?a.value:null}}function wf(a){G.call(this);this.f=a;pd(a,xf,this.lb,!1,this);pd(a,"click",this.lc,!1,this)}t(wf,G);var xf=bb?"keypress":"keydown";wf.prototype.lb=function(a){(13==a.keyCode||x&&3==a.keyCode)&&yf(this,a)};wf.prototype.lc=function(a){yf(this,a)};function yf(a,b){var c=
new zf(b);if(a.dispatchEvent(c)){c=new Af(b);try{a.dispatchEvent(c)}finally{b.stopPropagation()}}}wf.prototype.b=function(){wf.c.b.call(this);xd(this.f,xf,this.lb,!1,this);xd(this.f,"click",this.lc,!1,this);delete this.f};function Af(a){F.call(this,a.U);this.type="action"}t(Af,F);function zf(a){F.call(this,a.U);this.type="beforeaction"}t(zf,F);function Bf(a){G.call(this);this.f=a;a=w?"focusout":"blur";this.gd=pd(this.f,w?"focusin":"focus",this,!w);this.hd=pd(this.f,a,this,!w)}t(Bf,G);Bf.prototype.handleEvent=
function(a){var b=new F(a.U);b.type="focusin"==a.type||"focus"==a.type?"focusin":"focusout";this.dispatchEvent(b)};Bf.prototype.b=function(){Bf.c.b.call(this);yd(this.gd);yd(this.hd);delete this.f};function Cf(a){G.call(this);this.$a=null;this.f=a;a=w||$a||x&&!y("531")&&"TEXTAREA"==a.tagName;this.ic=new df(this);this.ic.ka(this.f,a?["keydown","paste","cut","drop","input"]:"input",this)}t(Cf,G);Cf.prototype.handleEvent=function(a){if("input"==a.type)w&&y(10)&&0==a.keyCode&&0==a.charCode||(Df(this),
this.dispatchEvent(Ef(a)));else if("keydown"!=a.type||ke(a)){var b="keydown"==a.type?this.f.value:null;w&&229==a.keyCode&&(b=null);var c=Ef(a);Df(this);this.$a=Dd(function(){this.$a=null;this.f.value!=b&&this.dispatchEvent(c)},this)}};function Df(a){null!=a.$a&&(l.clearTimeout(a.$a),a.$a=null)}function Ef(a){a=new F(a.U);a.type="input";return a}Cf.prototype.b=function(){Cf.c.b.call(this);this.ic.j();Df(this);delete this.f};var Ff=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;
function Mc(){var a={},b=a.document||document,c=document.createElement("SCRIPT"),d={zc:c,Gc:void 0},e=new pe(Gf,d),f=null,g=null!=a.timeout?a.timeout:5E3;0<g&&(f=window.setTimeout(function(){Hf(c,!0);var a=new If(Jf,"Timeout reached for loading script //www.gstatic.com/accountchooser/client.js");re(e);se(e,!1,a)},g),d.Gc=f);c.onload=c.onreadystatechange=function(){c.readyState&&"loaded"!=c.readyState&&"complete"!=c.readyState||(Hf(c,a.Md||!1,f),re(e),se(e,!0,null))};c.onerror=function(){Hf(c,!0,f);
var a=new If(Kf,"Error while loading script //www.gstatic.com/accountchooser/client.js");re(e);se(e,!1,a)};d=a.attributes||{};Ya(d,{type:"text/javascript",charset:"UTF-8",src:"//www.gstatic.com/accountchooser/client.js"});Cb(c,d);Lf(b).appendChild(c);return e}function Lf(a){var b=a.getElementsByTagName("HEAD");return b&&0!=b.length?b[0]:a.documentElement}function Gf(){if(this&&this.zc){var a=this.zc;a&&"SCRIPT"==a.tagName&&Hf(a,!0,this.Gc)}}function Hf(a,b,c){null!=c&&l.clearTimeout(c);a.onload=aa;
a.onerror=aa;a.onreadystatechange=aa;b&&window.setTimeout(function(){Gb(a)},0)}var Kf=0,Jf=1;function If(a,b){var c="Jsloader error (code #"+a+")";b&&(c+=": "+b);u.call(this,c);this.code=a}t(If,u);function Mf(a){this.rb=a}Mf.prototype.set=function(a,b){m(b)?this.rb.set(a,Ye(b)):this.rb.remove(a)};Mf.prototype.get=function(a){var b;try{b=this.rb.get(a)}catch(c){return}if(null!==b)try{return Xe(b)}catch(c$2){throw"Storage: Invalid value was encountered";}};Mf.prototype.remove=function(a){this.rb.remove(a)};
function Nf(){}function Of(){}t(Of,Nf);Of.prototype.clear=function(){var a=Kd(this.qa(!0)),b=this;Da(a,function(a){b.remove(a)})};function Pf(a){this.N=a}t(Pf,Of);function Qf(a){if(!a.N)return!1;try{return a.N.setItem("__sak","1"),a.N.removeItem("__sak"),!0}catch(b){return!1}}h=Pf.prototype;h.set=function(a,b){try{this.N.setItem(a,b)}catch(c){if(0==this.N.length)throw"Storage mechanism: Storage disabled";throw"Storage mechanism: Quota exceeded";}};h.get=function(a){a=this.N.getItem(a);if(!n(a)&&null!==
a)throw"Storage mechanism: Invalid value was encountered";return a};h.remove=function(a){this.N.removeItem(a)};h.qa=function(a){var b=0,c=this.N,d=new Hd;d.next=function(){if(b>=c.length)throw Gd;var d=c.key(b++);if(a)return d;d=c.getItem(d);if(!n(d))throw"Storage mechanism: Invalid value was encountered";return d};return d};h.clear=function(){this.N.clear()};h.key=function(a){return this.N.key(a)};function Rf(){var a=null;try{a=window.localStorage||null}catch(b){}this.N=a}t(Rf,Pf);function Sf(){var a=
null;try{a=window.sessionStorage||null}catch(b){}this.N=a}t(Sf,Pf);function Tf(a,b){this.Xa=a;this.na=b+"::"}t(Tf,Of);Tf.prototype.set=function(a,b){this.Xa.set(this.na+a,b)};Tf.prototype.get=function(a){return this.Xa.get(this.na+a)};Tf.prototype.remove=function(a){this.Xa.remove(this.na+a)};Tf.prototype.qa=function(a){var b=this.Xa.qa(!0),c=this,d=new Hd;d.next=function(){for(var d=b.next();d.substr(0,c.na.length)!=c.na;)d=b.next();return a?d.substr(c.na.length):c.Xa.get(d)};return d};function Uf(a){a=
a||{};var b=a.email,c=a.disabled;return C('<div class="firebaseui-textfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label"><label class="mdl-textfield__label firebaseui-label" for="email">'+(a.Kd?"Enter new email address":"Email")+'</label><input type="email" name="email" autocomplete="username" class="mdl-textfield__input firebaseui-input firebaseui-id-email" value="'+ac(null!=b?b:"")+'"'+(c?"disabled":"")+'></div><div class="firebaseui-error-wrapper"><p class="firebaseui-error firebaseui-hidden firebaseui-id-email-error"></p></div>')}
function L(a){a=a||{};a=a.label;return C('<button type="submit" class="firebaseui-id-submit firebaseui-button mdl-button mdl-js-button mdl-button--raised mdl-button--colored">'+(a?B(a):"Next")+"</button>")}function Vf(a){a=a||{};a=a.label;return C('<div class="firebaseui-new-password-component"><div class="firebaseui-textfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label"><label class="mdl-textfield__label firebaseui-label" for="newPassword">'+(a?B(a):"Choose password")+'</label><input type="password" name="newPassword" autocomplete="new-password" class="mdl-textfield__input firebaseui-input firebaseui-id-new-password"></div><a href="javascript:void(0)" class="firebaseui-input-floating-button firebaseui-id-password-toggle firebaseui-input-toggle-on firebaseui-input-toggle-blur"></a><div class="firebaseui-error-wrapper"><p class="firebaseui-error firebaseui-hidden firebaseui-id-new-password-error"></p></div></div>')}
function Wf(){var a;a={};return C('<div class="firebaseui-textfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label"><label class="mdl-textfield__label firebaseui-label" for="password">'+(a.current?"Current password":"Password")+'</label><input type="password" name="password" autocomplete="current-password" class="mdl-textfield__input firebaseui-input firebaseui-id-password"></div><div class="firebaseui-error-wrapper"><p class="firebaseui-error firebaseui-hidden firebaseui-id-password-error"></p></div>')}
function Xf(){return C('<a class="firebaseui-link firebaseui-id-secondary-link" href="javascript:void(0)">Trouble signing in?</a>')}function Yf(){return C('<button class="firebaseui-id-secondary-link firebaseui-button mdl-button mdl-js-button mdl-button--raised mdl-button--colored">Cancel</button>')}function Zf(a){return C('<div class="firebaseui-info-bar firebaseui-id-info-bar"><p class="firebaseui-info-bar-message">'+B(a.message)+' <a href="javascript:void(0)" class="firebaseui-link firebaseui-id-dismiss-info-bar">Dismiss</a></p></div>')}
Zf.B="firebaseui.auth.soy2.element.infoBar";function $f(){return C('<div class="mdl-progress mdl-js-progress mdl-progress__indeterminate firebaseui-busy-indicator firebaseui-id-busy-indicator"></div>')}$f.B="firebaseui.auth.soy2.element.busyIndicator";function ag(a){a=a||{};var b="";switch(a.providerId){case "google.com":b+="Google";break;case "github.com":b+="Github";break;case "facebook.com":b+="Facebook";break;case "twitter.com":b+="Twitter";break;default:b+="Password"}return D(b)}function bg(a){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-sign-in"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Sign in with email</h1></div><div class="firebaseui-card-content"><div class="firebaseui-relative-wrapper">'+
Uf(a)+'</div></div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+L(null)+"</div></div></form></div>")}bg.B="firebaseui.auth.soy2.page.signIn";function cg(a){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-sign-in"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Sign in</h1></div><div class="firebaseui-card-content">'+Uf(a)+Wf()+'</div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+
C(L({label:$b("Sign In")}))+"</div>"+Xf()+"</div></form></div>")}cg.B="firebaseui.auth.soy2.page.passwordSignIn";function dg(a){a=a||{};var b=a.Hc,c=a.Cb,d=C,e='<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-sign-up"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Create account</h1></div><div class="firebaseui-card-content">'+Uf(a),f;f=a||{};f=f.name;f=C('<div class="firebaseui-textfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label"><label class="mdl-textfield__label firebaseui-label" for="name">First & last name</label><input type="text" name="name" autocomplete="name" class="mdl-textfield__input firebaseui-input firebaseui-id-name" value="'+
ac(null!=f?f:"")+'"></div><div class="firebaseui-error-wrapper"><p class="firebaseui-error firebaseui-hidden firebaseui-id-name-error"></p></div>');e=e+f+Vf({Ld:!0});b?(a=a||{},a=C('<p class="firebaseui-tos">By tapping SAVE, you are indicating that you agree to the <a href="'+ac(fc(a.Hc))+'" class="firebaseui-link" target="_blank">Terms of Service</a></p>')):a="";return d(e+a+'</div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+(c?Yf():"")+C(L({label:$b("Save")}))+"</div></div></form></div>")}
dg.B="firebaseui.auth.soy2.page.passwordSignUp";function eg(a){a=a||{};var b=a.Cb;return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-recovery"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Recover password</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">Get instructions sent to this email that explain how to reset your password</p>'+Uf(a)+'</div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+
(b?Yf():"")+L({label:$b("Send")})+"</div></div></form></div>")}eg.B="firebaseui.auth.soy2.page.passwordRecovery";function fg(a){var b=a.H;return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-recovery-email-sent"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Check your email</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">Follow the instructions sent to <strong>'+B(a.email)+'</strong> to recover your password</p></div><div class="firebaseui-card-footer">'+
(b?'<div class="firebaseui-form-actions">'+L({label:$b("Done")})+"</div>":"")+"</div></div>")}fg.B="firebaseui.auth.soy2.page.passwordRecoveryEmailSent";function gg(){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-callback"><div class="firebaseui-callback-indicator-container">'+$f()+"</div></div>")}gg.B="firebaseui.auth.soy2.page.callback";function hg(a){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-linking"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Sign in</h1></div><div class="firebaseui-card-content"><h2 class="firebaseui-subtitle">You already have an account</h2><p class="firebaseui-text">You\u2019ve already used <strong>'+
B(a.email)+"</strong> to sign in. Enter your password for that account.</p>"+Wf()+'</div><div class="firebaseui-card-footer">'+Xf()+'<div class="firebaseui-form-actions">'+C(L({label:$b("Sign In")}))+"</div></div></form></div>")}hg.B="firebaseui.auth.soy2.page.passwordLinking";function ig(a){var b=a.email;a=""+ag(a);a=$b(a);b=""+('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-federated-linking"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Sign in</h1></div><div class="firebaseui-card-content"><h2 class="firebaseui-subtitle">You already have an account</h2><p class="firebaseui-text">You\u2019ve already used <strong>'+
B(b)+"</strong>. Sign in with "+B(a)+' to continue.</p></div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+L({label:$b("Sign in with "+a)})+"</div></div></form></div>");return C(b)}ig.B="firebaseui.auth.soy2.page.federatedLinking";function jg(a){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-reset"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Reset your password</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">for <strong>'+
B(a.email)+"</strong></p>"+Vf(Zb(a))+'</div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+C(L({label:$b("Save")}))+"</div></div></form></div>")}jg.B="firebaseui.auth.soy2.page.passwordReset";function kg(a){a=a||{};return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-reset-success"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Password changed</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">You can now sign in with your new password</p></div><div class="firebaseui-card-footer">'+
(a.H?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></div>")}kg.B="firebaseui.auth.soy2.page.passwordResetSuccess";function lg(a){a=a||{};return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-password-reset-failure"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Try resetting your password again</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">Your request to reset your password has expired or the link has already been used</p></div><div class="firebaseui-card-footer">'+
(a.H?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></div>")}lg.B="firebaseui.auth.soy2.page.passwordResetFailure";function mg(a){var b=a.H;return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-email-change-revoke-success"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Updated email address</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">Your sign-in email address has been changed back to <strong>'+
B(a.email)+'</strong>.</p><p class="firebaseui-text">If you didn\u2019t ask to change your sign-in email, it\u2019s possible someone is trying to access your account and you should <a class="firebaseui-link firebaseui-id-reset-password-link" href="javascript:void(0)">change your password right away</a>.</p></div><div class="firebaseui-card-footer">'+(b?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></form></div>")}mg.B="firebaseui.auth.soy2.page.emailChangeRevokeSuccess";function ng(a){a=
a||{};return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-email-change-revoke-failure"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Unable to update your email address</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">There was a problem changing your sign-in email back.</p><p class="firebaseui-text">If you try again and still can\u2019t reset your email, try asking your administrator for help.</p></div><div class="firebaseui-card-footer">'+
(a.H?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></div>")}ng.B="firebaseui.auth.soy2.page.emailChangeRevokeFailure";function og(a){a=a||{};return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-email-verification-success"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Your email has been verified</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">You can now sign in with your new account</p></div><div class="firebaseui-card-footer">'+
(a.H?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></div>")}og.B="firebaseui.auth.soy2.page.emailVerificationSuccess";function pg(a){a=a||{};return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-email-verification-failure"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Try verifying your email again</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">Your request to verify your email has expired or the link has already been used</p></div><div class="firebaseui-card-footer">'+
(a.H?'<div class="firebaseui-form-actions">'+L(null)+"</div>":"")+"</div></div>")}pg.B="firebaseui.auth.soy2.page.emailVerificationFailure";function qg(a){return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-unrecoverable-error"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Error encountered</h1></div><div class="firebaseui-card-content"><p class="firebaseui-text">'+B(a.Rc)+"</p></div></div>")}qg.B="firebaseui.auth.soy2.page.unrecoverableError";
function rg(a){var b=a.ld;return C('<div class="mdl-card mdl-shadow--2dp firebaseui-container firebaseui-id-page-email-mismatch"><form onsubmit="return false;"><div class="firebaseui-card-header"><h1 class="firebaseui-title">Sign in</h1></div><div class="firebaseui-card-content"><h2 class="firebaseui-subtitle">Continue with '+B(a.zd)+'?</h2><p class="firebaseui-text">You originally wanted to sign in with '+B(b)+'</p></div><div class="firebaseui-card-footer"><div class="firebaseui-form-actions">'+
Yf()+L({label:$b("Continue")})+"</div></div></form></div>")}rg.B="firebaseui.auth.soy2.page.emailMismatch";function sg(a,b,c){var d='<div class="firebaseui-container firebaseui-page-provider-sign-in firebaseui-id-page-provider-sign-in"><div class="firebaseui-card-content"><form onsubmit="return false;"><ul class="firebaseui-idp-list">';a=a.nd;b=a.length;for(var e=0;e<b;e++){var f;f={providerId:a[e]};var g=c,k=f.providerId,z=f,z=z||{},J="";switch(z.providerId){case "google.com":J+="firebaseui-idp-google";
break;case "github.com":J+="firebaseui-idp-github";break;case "facebook.com":J+="firebaseui-idp-facebook";break;case "twitter.com":J+="firebaseui-idp-twitter";break;default:J+="firebaseui-idp-password"}var z=C,J='<button class="firebaseui-idp-button mdl-button mdl-js-button mdl-button--raised '+ac(D(J))+' firebaseui-id-idp-button " data-provider-id="'+ac(k)+'"><img class="firebaseui-idp-icon" src="',ma=f,ma=ma||{},W="";switch(ma.providerId){case "google.com":W+=fc(g.Zc);break;case "github.com":W+=
fc(g.Yc);break;case "facebook.com":W+=fc(g.Uc);break;case "twitter.com":W+=fc(g.wd);break;default:W+=fc(g.kd)}g=Yb(W);f=z(J+ac(fc(g))+'">'+("password"==k?'<span class="firebaseui-idp-text firebaseui-idp-text-long">Sign in with email</span><span class="firebaseui-idp-text firebaseui-idp-text-short">Email</span>':'<span class="firebaseui-idp-text firebaseui-idp-text-long">Sign in with '+B(ag(f))+'</span><span class="firebaseui-idp-text firebaseui-idp-text-short">'+B(ag(f))+"</span>")+"</button>");d+=
'<li class="firebaseui-list-item">'+f+"</li>"}return C(d+"</ul></form></div></div>")}sg.B="firebaseui.auth.soy2.page.providerSignIn";function tg(){return D("This email already exists without any means of sign-in. Please reset the password to recover.")}function ug(){return D("Please login again to perform this operation")}function vg(a,b,c,d){this.Qa=a;this.hc=b||null;this.md=c||null;this.Vb=d||null}vg.prototype.D=function(){return this.Qa};vg.prototype.ab=function(){return{email:this.Qa,displayName:this.hc,
photoUrl:this.md,providerId:this.Vb}};function wg(a){return a.email?new vg(a.email,a.displayName,a.photoUrl,a.providerId):null}var xg=null;function yg(a){return!(!a||-32E3!=a.code||"Service unavailable"!=a.message)}function zg(a,b,c,d){xg||(a={callbacks:{empty:a,select:function(a,d){a&&a.account&&b?b(wg(a.account)):c&&c(!yg(d))},store:a,update:a},language:"en",providers:void 0,ui:d},"undefined"!=typeof accountchooser&&accountchooser.Api&&accountchooser.Api.init?xg=accountchooser.Api.init(a):(xg=new Ag(a),
Bg()))}function Cg(a,b,c){function d(){var a=Te(c).toString();xg.select(Ga(b||[],function(a){return a.ab()}),{clientCallbackUrl:a})}b&&b.length?d():xg.checkEmpty(function(b,c){b||c?a(!yg(c)):d()})}function Ag(a){this.a=a;this.a.callbacks=this.a.callbacks||{}}function Bg(){var a=xg;p(a.a.callbacks.empty)&&a.a.callbacks.empty()}var Dg={code:-32E3,message:"Service unavailable",data:"Service is unavailable."};h=Ag.prototype;h.store=function(){p(this.a.callbacks.store)&&this.a.callbacks.store(void 0,Dg)};
h.select=function(){p(this.a.callbacks.select)&&this.a.callbacks.select(void 0,Dg)};h.update=function(){p(this.a.callbacks.update)&&this.a.callbacks.update(void 0,Dg)};h.checkDisabled=function(a){a(!0)};h.checkEmpty=function(a){a(void 0,Dg)};h.checkAccountExist=function(a,b){b(void 0,Dg)};h.checkShouldUpdate=function(a,b){b(void 0,Dg)};function Eg(a){a=fa(a)&&1==a.nodeType?a:document.querySelector(String(a));if(null==a)throw Error("Could not find the FirebaseUI widget element on the page.");return a}
function Fg(){this.$={}}function M(a,b,c){if(b.toLowerCase()in a.$)throw Error("Configuration "+b+" has already been defined.");a.$[b.toLowerCase()]=c}Fg.prototype.update=function(a,b){if(!(a.toLowerCase()in this.$))throw Error("Configuration "+a+" is not defined.");this.$[a.toLowerCase()]=b};Fg.prototype.get=function(a){if(!(a.toLowerCase()in this.$))throw Error("Configuration "+a+" is not defined.");return this.$[a.toLowerCase()]};function Gg(a,b){var c=a.get(b);if(!c)throw Error("Configuration "+
b+" is required.");return c}var N={},Hg=0;function Ig(a,b){if(!a)throw Error("Event target element must be provided!");var c=Jg(a);if(N[c]&&N[c].length)for(var d=0;d<N[c].length;d++)N[c][d].dispatchEvent(b)}function Kg(a){var b=Jg(a.L());N[b]&&N[b].length&&(Ma(N[b],function(b){return b==a}),N[b].length||delete N[b])}function Jg(a){"undefined"===typeof a.gc&&(a.gc=Hg,Hg++);return a.gc}function Lg(a){if(!a)throw Error("Event target element must be provided!");this.Qc=a;G.call(this)}t(Lg,G);Lg.prototype.L=
function(){return this.Qc};Lg.prototype.register=function(){var a=Jg(this.L());N[a]?Ja(N[a],this)||N[a].push(this):N[a]=[this]};Lg.prototype.unregister=function(){Kg(this)};var Mg={"facebook.com":"FacebookAuthProvider","github.com":"GithubAuthProvider","google.com":"GoogleAuthProvider",password:"EmailAuthProvider","twitter.com":"TwitterAuthProvider"};var Ng;Ng=ae("firebaseui");var Og=new he;if(1!=Og.nc){$d();var Pg=Zd,Qg=Og.od;Pg.Wa||(Pg.Wa=[]);Pg.Wa.push(Qg);Og.nc=!0}function Rg(a){Ng&&Ng.log(Td,
a,void 0)}function Sg(a,b){this.Qa=a;this.sa=b||null}Sg.prototype.D=function(){return this.Qa};Sg.prototype.ab=function(){var a;if(a=this.sa){a=this.sa;var b={},c;for(c in a)b[c]=a[c];a=b}return{email:this.Qa,credential:a}};function Tg(a){if(a&&a.email){var b;if(b=a.credential){var c=(b=a.credential)&&b.provider;Mg[c]&&firebase.auth[Mg[c]]?(b.secret&&b.accessToken&&(b.oauthToken=b.accessToken,b.oauthTokenSecret=b.secret),b=firebase.auth[Mg[c]].credential(b)):b=null}return new Sg(a.email,b)}return null}
var Ug=/MSIE ([\d.]+).*Windows NT ([\d.]+)/,Vg=/Firefox\/([\d.]+)/,Wg=/Opera[ \/]([\d.]+)(.*Version\/([\d.]+))?/,Xg=/Chrome\/([\d.]+)/,Yg=/((Windows NT ([\d.]+))|(Mac OS X ([\d_]+))).*Version\/([\d.]+).*Safari/,Zg=/Mac OS X;.*(?!(Version)).*Safari/,$g=/Android ([\d.]+).*Safari/,ah=/OS ([\d_]+) like Mac OS X.*Mobile.*Safari/,bh=/Konqueror\/([\d.]+)/,ch=/MSIE ([\d.]+).*Windows Phone OS ([\d.]+)/;function O(a,b){this.Ka=a;var c=a.split(b||".");this.Na=[];for(var d=0;d<c.length;d++)this.Na.push(parseInt(c[d],
10))}O.prototype.compare=function(a){a instanceof O||(a=new O(String(a)));for(var b=Math.max(this.Na.length,a.Na.length),c=0;c<b;c++){var d=this.Na[c],e=a.Na[c];if(void 0!==d&&void 0!==e&&d!==e)return d-e;if(void 0===d)return-1;if(void 0===e)return 1}return 0};function P(a,b){return 0<=a.compare(b)}function dh(){var a=window.navigator&&window.navigator.userAgent;if(a){var b;if(b=a.match(Wg)){var c=new O(b[3]||b[1]);return 0<=a.indexOf("Opera Mini")?!1:0<=a.indexOf("Opera Mobi")?0<=a.indexOf("Android")&&
P(c,"10.1"):P(c,"8.0")}if(b=a.match(Vg))return P(new O(b[1]),"2.0");if(b=a.match(Xg))return P(new O(b[1]),"6.0");if(b=a.match(Yg))return c=new O(b[6]),a=b[3]&&new O(b[3]),b=b[5]&&new O(b[5],"_"),(!(!a||!P(a,"6.0"))||!(!b||!P(b,"10.5.6")))&&P(c,"3.0");if(b=a.match($g))return P(new O(b[1]),"3.0");if(b=a.match(ah))return P(new O(b[1],"_"),"4.0");if(b=a.match(bh))return P(new O(b[1]),"4.7");if(b=a.match(ch))return c=new O(b[1]),a=new O(b[2]),P(c,"7.0")&&P(a,"7.0");if(b=a.match(Ug))return c=new O(b[1]),
a=new O(b[2]),P(c,"7.0")&&P(a,"6.0");if(a.match(Zg))return!1}return!0}var eh,fh=new Rf;eh=Qf(fh)?new Tf(fh,"firebaseui"):null;var gh=new Mf(eh),hh,ih=new Sf;hh=Qf(ih)?new Tf(ih,"firebaseui"):null;var jh=new Mf(hh),kh={name:"pendingEmailCredential",Ha:!1},lh={name:"redirectUrl",Ha:!1},mh={name:"rememberAccount",Ha:!1},nh={name:"rememberedAccounts",Ha:!0};function oh(a,b){return(a.Ha?gh:jh).get(b?a.name+":"+b:a.name)}function ph(a,b){(a.Ha?gh:jh).remove(b?a.name+":"+b:a.name)}function qh(a,b,c){(a.Ha?
gh:jh).set(c?a.name+":"+c:a.name,b)}function rh(a){a=oh(nh,a)||[];a=Ga(a,function(a){return wg(a)});return Fa(a,ca)}function sh(a,b){var c=rh(b),d=Ia(c,function(b){return b.D()==a.D()&&(b.Vb||null)==(a.Vb||null)});-1<d&&La(c,d);c.unshift(a);qh(nh,Ga(c,function(a){return a.ab()}),b)}function th(a){a=oh(kh,a)||null;return Tg(a)}function uh(){this.a=new Fg;M(this.a,"acUiConfig");M(this.a,"callbacks");M(this.a,"credentialHelper",vh);M(this.a,"popupMode",!1);M(this.a,"queryParameterForSignInSuccessUrl",
"signInSuccessUrl");M(this.a,"queryParameterForWidgetMode","mode");M(this.a,"signInFlow");M(this.a,"signInOptions");M(this.a,"signInSuccessUrl");M(this.a,"siteName");M(this.a,"tosUrl");M(this.a,"widgetUrl")}var vh="accountchooser.com",wh={Bd:vh,NONE:"none"},xh={Dd:"popup",Fd:"redirect"};function yh(a){return a.a.get("acUiConfig")||null}var zh={Cd:"callback",Ed:"recoverEmail",Gd:"resetPassword",Hd:"select",Id:"verifyEmail"};function Ah(a){var b=a.a.get("widgetUrl");b||(b=Je(Se(window.location.href),
""),b=Ie(b,"",void 0).toString());return Bh(a,b)}function Bh(a,b){for(var c=Ch(a),d=b.search(Ce),e=0,f,g=[];0<=(f=Be(b,e,c,d));)g.push(b.substring(e,f)),e=Math.min(b.indexOf("&",f)+1||d,d);g.push(b.substr(e));c=[g.join("").replace(Ee,"$1"),"&",c];c.push("=",encodeURIComponent("select"));c[1]&&(d=c[0],e=d.indexOf("#"),0<=e&&(c.push(d.substr(e)),c[0]=d=d.substr(0,e)),e=d.indexOf("?"),0>e?c[1]="?":e==d.length-1&&(c[1]=void 0));return c.join("")}function Dh(a){a=a.a.get("signInOptions")||[];for(var b=
[],c=0;c<a.length;c++){var d=a[c],d=fa(d)?d:{provider:d};Mg[d.provider]&&b.push(d)}return b}function Eh(a){return Ga(Dh(a),function(a){return a.provider})}function Fh(a,b){for(var c=Dh(a),d=0;d<c.length;d++)if(c[d].provider===b)return c=c[d].scopes,da(c)?c:[];return[]}function Ch(a){return Gg(a.a,"queryParameterForWidgetMode")}function Gh(a){a=a.a.get("signInFlow");for(var b in xh)if(xh[b]==a)return xh[b];return"redirect"}function Hh(a){return a.a.get("callbacks")||{}}function Ih(a){a=a.a.get("credentialHelper");
for(var b in wh)if(wh[b]==a)return wh[b];return vh}uh.prototype.zb=function(a){for(var b in a)try{this.a.update(b,a[b])}catch(c){Rg('Invalid config: "'+b+'"')}cb&&this.a.update("popupMode",!1)};uh.prototype.update=function(a,b){this.a.update(a,b)};var Q={};function R(a,b,c,d){Q[a].apply(null,Array.prototype.slice.call(arguments,1))}function S(a,b){var c;c=Hb(a);b?(of(a,"firebaseui-input-invalid"),nf(a,"firebaseui-input"),c&&of(c,"firebaseui-textfield-invalid")):(of(a,"firebaseui-input"),nf(a,"firebaseui-input-invalid"),
c&&nf(c,"firebaseui-textfield-invalid"))}function Jh(a,b,c){b=new Cf(b);Zc(a,ka($c,b));jf(a).ka(b,"input",c)}function Kh(a,b,c){b=new pf(b);Zc(a,ka($c,b));jf(a).ka(b,"key",function(a){13==a.keyCode&&(a.stopPropagation(),a.preventDefault(),c(a))})}function Lh(a,b,c){b=new Bf(b);Zc(a,ka($c,b));jf(a).ka(b,"focusin",c)}function Mh(a,b,c){b=new Bf(b);Zc(a,ka($c,b));jf(a).ka(b,"focusout",c)}function Nh(a,b,c){b=new wf(b);Zc(a,ka($c,b));jf(a).ka(b,"action",function(a){a.stopPropagation();a.preventDefault();
c(a)})}function Oh(a){nf(a,"firebaseui-hidden")}function T(a,b){if(b)if("textContent"in a)a.textContent=b;else if(3==a.nodeType)a.data=b;else if(a.firstChild&&3==a.firstChild.nodeType){for(;a.lastChild!=a.firstChild;)a.removeChild(a.lastChild);a.firstChild.data=b}else{for(var c;c=a.firstChild;)a.removeChild(c);a.appendChild(zb(a).createTextNode(String(b)))}of(a,"firebaseui-hidden")}function Ph(a){return!mf(a,"firebaseui-hidden")&&"none"!=a.style.display}function Qh(){Gb(Rh.call(this))}function Rh(){return this.C("firebaseui-id-info-bar")}
function Sh(){return this.C("firebaseui-id-dismiss-info-bar")}var Th={Nd:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/profile-picture-small.png",Zc:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/google.svg",Yc:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/github.svg",Uc:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/facebook.svg",wd:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/twitter.svg",kd:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/mail.svg",
Sd:"https://www.gstatic.com/firebasejs/ui/0.5.0/images/auth/"};function Uh(a,b,c){cd.call(this,a,b);for(var d in c)this[d]=c[d]}t(Uh,cd);function U(a,b,c,d){hf.call(this,c);this.Ec=a;this.Dc=b;this.ob=!1;this.wc=d||null;this.Y=this.Za=null}t(U,hf);U.prototype.Ib=function(){var a=Mb(this.Ec,this.Dc,Th,this.ib());Vh(a,"upgradeElement");this.f=a};var Wh=["mdl-js-textfield","mdl-js-progress","mdl-js-button"];function Vh(a,b){a&&window.componentHandler&&window.componentHandler[b]&&Da(Wh,function(c){if(mf(a,
c))window.componentHandler[b](a);c=Ab(c,a);Da(c,function(a){window.componentHandler[b](a)})})}U.prototype.l=function(){U.c.l.call(this);Ig(V(this),new Uh("pageEnter",V(this),{pageId:this.wc}))};U.prototype.Ra=function(){Ig(V(this),new Uh("pageExit",V(this),{pageId:this.wc}));U.c.Ra.call(this)};U.prototype.b=function(){window.clearTimeout(this.Za);this.Dc=this.Ec=this.Za=null;this.ob=!1;this.Y=null;Vh(this.L(),"downgradeElements");U.c.b.call(this)};function Xh(a){a.ob=!0;a.Za=window.setTimeout(function(){a.L()&&
null===a.Y&&(a.Y=Mb($f,null,null,a.ib()),a.L().appendChild(a.Y),Vh(a.Y,"upgradeElement"))},500)}function Yh(a,b,c,d,e){function f(){if(a.Da)return null;a.ob=!1;window.clearTimeout(a.Za);a.Za=null;a.Y&&(Vh(a.Y,"downgradeElements"),Gb(a.Y),a.Y=null)}if(a.ob)return null;Xh(a);return b.apply(null,c).then(d,e).then(f,f)}function V(a){return a.L().parentElement||a.L().parentNode}function Zh(a,b,c){Kh(a,b,function(){c.focus()})}function $h(a,b,c){Kh(a,b,function(){c()})}r(U.prototype,{G:function(a){Qh.call(this);
var b=Mb(Zf,{message:a},null,this.ib());this.L().appendChild(b);Nh(this,Sh.call(this),function(){Gb(b)})},Od:Qh,Qd:Rh,Pd:Sh});function ai(){return this.C("firebaseui-id-submit")}function bi(){return this.C("firebaseui-id-secondary-link")}function ci(a,b){var c=ai.call(this);Nh(this,c,function(){a()});(c=bi.call(this))&&b&&Nh(this,c,function(){b()})}function di(){return this.C("firebaseui-id-password")}function ei(){return this.C("firebaseui-id-password-error")}function fi(){var a=di.call(this),b=
ei.call(this);Jh(this,a,function(){Ph(b)&&(S(a,!0),Oh(b))})}function gi(){var a=di.call(this),b;b=ei.call(this);K(a)?(S(a,!0),Oh(b),b=!0):(S(a,!1),T(b,D("Enter your password").toString()),b=!1);return b?K(a):null}function hi(a,b,c,d){U.call(this,hg,{email:a},d,"passwordLinking");this.o=b;this.tb=c}t(hi,U);hi.prototype.l=function(){this.Rb();this.A(this.o,this.tb);$h(this,this.W(),this.o);this.W().focus();hi.c.l.call(this)};hi.prototype.b=function(){this.o=null;hi.c.b.call(this)};hi.prototype.ea=function(){return K(this.C("firebaseui-id-email"))};
r(hi.prototype,{W:di,Ob:ei,Rb:fi,Hb:gi,J:ai,ua:bi,A:ci});function ii(){return this.C("firebaseui-id-email")}function ji(){return this.C("firebaseui-id-email-error")}function ki(a){var b=ii.call(this),c=ji.call(this);Jh(this,b,function(){Ph(c)&&(S(b,!0),Oh(c))});a&&Kh(this,b,function(){a()})}function li(){return qa(K(ii.call(this))||"")}function mi(){var a=ii.call(this),b;b=ji.call(this);var c=K(a)||"";c?Ff.test(c)?(S(a,!0),Oh(b),b=!0):(S(a,!1),T(b,D("That email address isn't correct").toString()),
b=!1):(S(a,!1),T(b,D("Enter your email address to continue").toString()),b=!1);return b?qa(K(a)):null}function ni(a,b,c,d){U.call(this,cg,{email:c},d,"passwordSignIn");this.o=a;this.tb=b}t(ni,U);ni.prototype.l=function(){this.xa();this.Rb();this.A(this.o,this.tb);Zh(this,this.u(),this.W());$h(this,this.W(),this.o);K(this.u())?this.W().focus():this.u().focus();ni.c.l.call(this)};ni.prototype.b=function(){this.tb=this.o=null;ni.c.b.call(this)};r(ni.prototype,{u:ii,Fa:ji,xa:ki,D:li,ea:mi,W:di,Ob:ei,
Rb:fi,Hb:gi,J:ai,ua:bi,A:ci});function X(a,b,c,d,e){U.call(this,a,b,d,e||"notice");this.aa=c||null}t(X,U);X.prototype.l=function(){this.aa&&(this.A(this.aa),this.J().focus());X.c.l.call(this)};X.prototype.b=function(){this.aa=null;X.c.b.call(this)};r(X.prototype,{J:ai,ua:bi,A:ci});function oi(a,b,c){X.call(this,fg,{email:a,H:!!b},b,c,"passwordRecoveryEmailSent")}t(oi,X);function pi(a,b){X.call(this,og,{H:!!a},a,b,"emailVerificationSuccess")}t(pi,X);function qi(a,b){X.call(this,pg,{H:!!a},a,b,"emailVerificationFailure")}
t(qi,X);function ri(a,b){X.call(this,kg,{H:!!a},a,b,"passwordResetSuccess")}t(ri,X);function si(a,b){X.call(this,lg,{H:!!a},a,b,"passwordResetFailure")}t(si,X);function ti(a,b){X.call(this,ng,{H:!!a},a,b,"emailChangeRevokeFailure")}t(ti,X);function ui(a,b){X.call(this,qg,{Rc:a},void 0,b,"unrecoverableError")}t(ui,X);var vi=!1,wi=null;function xi(a,b){vi=!!b;wi||(wi="undefined"==typeof accountchooser&&dh()?Lc(function(){}):Ic());wi.then(a,a)}function yi(a,b){var c=Hh(a.a).accountChooserInvoked||null;
c?c(b):b()}function zi(a,b,c){(a=Hh(a.a).accountChooserResult||null)?a(b,c):c()}function Ai(a,b,c,d,e){d?(R("callback",a,b),vi&&c()):yi(a,function(){Cg(function(d){zi(a,d?"empty":"unavailable",function(){R("signIn",a,b);(d||vi)&&c()})},rh(a.h),e)})}function Bi(a,b,c,d){function e(a){a=Y(a);Ci(b,c,void 0,a);d()}zi(b,"accountSelected",function(){qh(mh,!1,b.h);Z(b,b.g.fetchProvidersForEmail(a.D()).then(function(e){Di(b,c,e,a.D(),a.hc||null||void 0);d()},e))})}function Ei(a,b,c,d){zi(b,a?"addAccount":
"unavailable",function(){R("signIn",b,c);(a||vi)&&d()})}function Fi(a,b,c,d){function e(){var b=a();b&&(b=Hh(b.a).uiShown||null)&&b()}zg(function(){var f=a();f&&Ai(f,b,e,c,d)},function(c){var d=a();d&&Bi(c,d,b,e)},function(c){var d=a();d&&Ei(c,d,b,e)},a()&&yh(a().a))}function Gi(a,b,c,d){function e(c){if(!c.name||"cancel"!=c.name){var d;a:{var e=c.message;try{var f=((JSON.parse(e).error||{}).message||"").toLowerCase().match(/invalid.+(access|id)_token/);if(f&&f.length){d=!0;break a}}catch(g$3){}d=
!1}d?(c=V(b),b.j(),Ci(a,c,void 0,D("Your sign-in session has expired. Please try again.").toString())):(d=c&&c.message||"",c.code&&(d=Y(c)),b.G(d))}}var f=c;c.provider&&"password"==c.provider&&(f=null);var g=a.g.currentUser||d;if(!g)throw Error("User not logged in.");Z(a,a.g.signOut().then(function(){var b=new vg(g.email,g.displayName,g.photoURL,f&&f.provider);null!=oh(mh,a.h)&&!oh(mh,a.h)||sh(b,a.h);ph(mh,a.h);Z(a,a.Mc.signInWithCredential(c).then(function(b){var c=Hh(a.a).signInSuccess||null,d=
oh(lh,a.h)||null||void 0;ph(lh,a.h);var e=!1;if(window.opener&&window.opener.location&&window.opener.location.assign){if(!c||c(b,f,d))e=!0,window.opener.location.assign(Hi(a,d));c||window.close()}else if(!c||c(b,f,d))e=!0,window.location.assign(Hi(a,d));e||a.reset()},e).then(function(){},e))},e))}function Hi(a,b){var c=b||a.a.a.get("signInSuccessUrl");if(!c)throw Error("No redirect URL has been found. You must either specify a signInSuccessUrl in the configuration, pass in a redirect URL to the widget URL, or return false from the callback.");
return c}function Y(a){var b="";switch(a.code){case "auth/email-already-in-use":b+="The email address is already used by another account";break;case "auth/requires-recent-login":b+=ug();break;case "auth/too-many-requests":b+="You have entered an incorrect password too many times. Please try again in a few minutes.";break;case "auth/user-cancelled":b+="Please authorize the required permissions to sign in to the application";break;case "auth/user-not-found":b+="That email address doesn't match an existing account";
break;case "auth/user-token-expired":b+=ug();break;case "auth/weak-password":b+="Strong passwords have at least 6 characters and a mix of letters and numbers";break;case "auth/wrong-password":b+="The email and password you entered don't match";break;case "auth/network-request-failed":b+="A network error has occurred."}if(b=D(b).toString())return b;try{return JSON.parse(a.message),Rg("Internal error: "+a.message),D("An internal error has occurred.").toString()}catch(c){return a.message}}function Ii(a,
b,c){function d(){Z(a,Yh(b,q(a.g.signInWithRedirect,a.g),[g],function(){},e))}function e(a){a.name&&"cancel"==a.name||(Rg("signInWithRedirect: "+a.code),a=Y(a),b.G(a))}var f=V(b),g=Mg[c]&&firebase.auth[Mg[c]]?new firebase.auth[Mg[c]]:null;if(!g)throw Error("Invalid Firebase Auth provider!");c=Fh(a.a,c);if(g&&g.addScope)for(var k=0;k<c.length;k++)g.addScope(c[k]);"redirect"==Gh(a.a)?d():Z(a,a.g.signInWithPopup(g).then(function(c){b.j();R("callback",a,f,Ic(c))},function(c){if(!c.name||"cancel"!=c.name)switch(c.code){case "auth/popup-blocked":d();
break;case "auth/popup-closed-by-user":case "auth/cancelled-popup-request":break;case "auth/network-request-failed":case "auth/too-many-requests":case "auth/user-cancelled":b.G(Y(c));break;default:b.j(),R("callback",a,f,Jc(c))}}))}function Ji(a,b){var c=b.ea(),d=b.Hb();if(c)if(d){var e=firebase.auth.EmailAuthProvider.credential(c,d);Z(a,Yh(b,q(a.g.signInWithEmailAndPassword,a.g),[c,d],function(){Gi(a,b,e)},function(a){if(!a.name||"cancel"!=a.name)switch(a.code){case "auth/email-exists":S(b.u(),!1);
T(b.Fa(),Y(a));break;case "auth/too-many-requests":case "auth/wrong-password":S(b.W(),!1);T(b.Ob(),Y(a));break;default:Rg("verifyPassword: "+a.message),b.G(Y(a))}}))}else b.W().focus();else b.u().focus()}function Ci(a,b,c,d){var e=Eh(a.a);1==e.length&&e[0]==firebase.auth.EmailAuthProvider.PROVIDER_ID?d?R("signIn",a,b,c,d):Ki(a,b,c):R("providerSignIn",a,b,d)}function Li(a,b,c,d){var e=V(b);Z(a,Yh(b,q(a.g.fetchProvidersForEmail,a.g),[c],function(f){var g=Ih(a.a)==vh;qh(mh,g,a.h);b.j();Di(a,e,f,c,void 0,
d)},function(){}))}function Di(a,b,c,d,e,f){c.length?Ja(c,firebase.auth.EmailAuthProvider.PROVIDER_ID)?R("passwordSignIn",a,b,d):(qh(kh,(new Sg(d)).ab(),a.h),R("federatedSignIn",a,b,d,c[0],f)):R("passwordSignUp",a,b,d,e)}function Ki(a,b,c){Ih(a.a)==vh?xi(function(){xg?yi(a,function(){Cg(function(d){zi(a,d?"empty":"unavailable",function(){R("signIn",a,b,c)})},rh(a.h),Ah(a.a))}):Fi(Mi,b,!1,Ah(a.a))},!1):(vi=!1,yi(a,function(){zi(a,"unavailable",function(){R("signIn",a,b,c)})}))}function Ni(a){var b=
window.location.href;a=Ch(a.a);var b=De(b,a)||"",c;for(c in zh)if(zh[c].toLowerCase()==b.toLowerCase())return zh[c];return"callback"}function Oi(a){var b=window.location.href;a=Gg(a.a.a,"queryParameterForSignInSuccessUrl");return De(b,a)}function Pi(){return De(window.location.href,"oobCode")}function Qi(a,b){if(Qf(new Rf)&&Qf(new Sf))Ri(a,b);else{var c=Eg(b),d=new ui(D("The browser you are using does not support Web Storage. Please try again in a different browser.").toString());I(d,c);a.s=d}}function Ri(a,
b){var c=Eg(b);switch(Ni(a)){case "callback":var d=Oi(a);d&&qh(lh,d,a.h);R("callback",a,c);break;case "resetPassword":R("passwordReset",a,c,Pi());break;case "recoverEmail":R("emailChangeRevocation",a,c,Pi());break;case "verifyEmail":R("emailVerification",a,c,Pi());break;case "select":if((d=Oi(a))&&qh(lh,d,a.h),xg){Ci(a,c);break}else{xi(function(){Fi(Mi,c,!0)},!0);return}default:throw Error("Unhandled widget operation.");}(d=Hh(a.a).uiShown||null)&&d()}function Si(a){U.call(this,gg,void 0,a,"callback")}
t(Si,U);function Ti(a,b,c){if(c.user){var d=th(a.h),e=d&&d.D();if(e&&!Ui(c.user,e))Vi(a,b,c.user,c.credential);else{var f=d&&d.sa;f?Z(a,c.user.link(f).then(function(){Wi(a,b,f)},function(c){Xi(a,b,c)})):Wi(a,b,c.credential)}}else c=V(b),b.j(),ph(kh,a.h),Ci(a,c)}function Wi(a,b,c){ph(kh,a.h);Gi(a,b,c)}function Xi(a,b,c){var d=V(b);ph(kh,a.h);c=Y(c);b.j();Ci(a,d,void 0,c)}function Yi(a,b,c,d){var e=V(b);Z(a,a.g.fetchProvidersForEmail(c).then(function(f){b.j();f.length?"password"==f[0]?R("passwordLinking",
a,e,c):R("federatedLinking",a,e,c,f[0],d):(ph(kh,a.h),R("passwordRecovery",a,e,c,!1,tg().toString()))},function(c){Xi(a,b,c)}))}function Vi(a,b,c,d){var e=V(b);Z(a,a.g.signOut().then(function(){b.j();R("emailMismatch",a,e,c,d)},function(a){a.name&&"cancel"==a.name||(a=Y(a.code),b.G(a))}))}function Ui(a,b){if(b==a.email)return!0;if(a.providerData)for(var c=0;c<a.providerData.length;c++)if(b==a.providerData[c].email)return!0;return!1}Q.callback=function(a,b,c){var d=new Si;I(d,b);a.s=d;b=c||a.getRedirectResult();
Z(a,b.then(function(b){Ti(a,d,b)},function(b){if(b&&"auth/account-exists-with-different-credential"==b.code&&b.email&&b.credential){var c=Tg(b);qh(kh,c.ab(),a.h);Yi(a,d,b.email)}else if(b&&"auth/user-cancelled"==b.code){var c=th(a.h),g=Y(b);c&&c.sa?Yi(a,d,c.D(),g):c?Li(a,d,c.D(),g):Xi(a,d,b)}else Xi(a,d,b)}))};function Zi(a,b,c,d){U.call(this,mg,{email:a,H:!!c},d,"emailChangeRevoke");this.vc=b;this.aa=c||null}t(Zi,U);Zi.prototype.l=function(){var a=this;Nh(this,this.C("firebaseui-id-reset-password-link"),
function(){a.vc()});this.aa&&(this.A(this.aa),this.J().focus());Zi.c.l.call(this)};Zi.prototype.b=function(){this.vc=this.aa=null;Zi.c.b.call(this)};r(Zi.prototype,{J:ai,ua:bi,A:ci});function $i(){return this.C("firebaseui-id-new-password")}function aj(){return this.C("firebaseui-id-password-toggle")}function bj(){this.Sb=!this.Sb;var a=aj.call(this),b=$i.call(this);this.Sb?(b.type="text",nf(a,"firebaseui-input-toggle-off"),of(a,"firebaseui-input-toggle-on")):(b.type="password",nf(a,"firebaseui-input-toggle-on"),
of(a,"firebaseui-input-toggle-off"));b.focus()}function cj(){return this.C("firebaseui-id-new-password-error")}function dj(){this.Sb=!1;var a=$i.call(this);a.type="password";var b=cj.call(this);Jh(this,a,function(){Ph(b)&&(S(a,!0),Oh(b))});var c=aj.call(this);nf(c,"firebaseui-input-toggle-on");of(c,"firebaseui-input-toggle-off");Lh(this,a,function(){nf(c,"firebaseui-input-toggle-focus");of(c,"firebaseui-input-toggle-blur")});Mh(this,a,function(){nf(c,"firebaseui-input-toggle-blur");of(c,"firebaseui-input-toggle-focus")});
Nh(this,c,q(bj,this))}function ej(){var a=$i.call(this),b;b=cj.call(this);K(a)?(S(a,!0),Oh(b),b=!0):(S(a,!1),T(b,D("Enter your password").toString()),b=!1);return b?K(a):null}function fj(a,b,c){U.call(this,jg,{email:a},c,"passwordReset");this.o=b}t(fj,U);fj.prototype.l=function(){this.Qb();this.A(this.o);$h(this,this.V(),this.o);this.V().focus();fj.c.l.call(this)};fj.prototype.b=function(){this.o=null;fj.c.b.call(this)};r(fj.prototype,{V:$i,Nb:cj,Xc:aj,Qb:dj,Gb:ej,J:ai,ua:bi,A:ci});function gj(a,
b,c,d){var e=c.Gb();e&&Z(a,Yh(c,q(a.g.confirmPasswordReset,a.g),[d,e],function(){c.j();var d=new ri;I(d,b);a.s=d},function(d){hj(a,b,c,d)}))}function hj(a,b,c,d){"auth/weak-password"==(d&&d.code)?(a=Y(d),S(c.V(),!1),T(c.Nb(),a),c.V().focus()):(c&&c.j(),c=new si,I(c,b),a.s=c)}function ij(a,b,c){var d=new Zi(c,function(){Z(a,Yh(d,q(a.g.sendPasswordResetEmail,a.g),[c],function(){d.j();d=new oi(c);I(d,b);a.s=d},function(){d.G(D("Unable to send password reset code to specified email.").toString())}))});
I(d,b);a.s=d}Q.passwordReset=function(a,b,c){Z(a,a.g.verifyPasswordResetCode(c).then(function(d){var e=new fj(d,function(){gj(a,b,e,c)});I(e,b);a.s=e},function(){hj(a,b)}))};Q.emailChangeRevocation=function(a,b,c){var d=null;Z(a,a.g.checkActionCode(c).then(function(b){d=b.data.email;return a.g.applyActionCode(c)}).then(function(){ij(a,b,d)},function(){var c=new ti;I(c,b);a.s=c}))};Q.emailVerification=function(a,b,c){Z(a,a.g.applyActionCode(c).then(function(){var c=new pi;I(c,b);a.s=c},function(){var c=
new qi;I(c,b);a.s=c}))};function jj(a,b,c,d,e){U.call(this,rg,{zd:a,ld:b},e,"emailMismatch");this.aa=c;this.la=d}t(jj,U);jj.prototype.l=function(){this.A(this.aa,this.la);this.J().focus();jj.c.l.call(this)};jj.prototype.b=function(){this.la=this.o=null;jj.c.b.call(this)};r(jj.prototype,{J:ai,ua:bi,A:ci});Q.emailMismatch=function(a,b,c,d){var e=th(a.h);if(e){var f=new jj(c.email,e.D(),function(){var b=f;ph(kh,a.h);Gi(a,b,d,c)},function(){var b=d.provider,c=V(f);f.j();e.sa?R("federatedLinking",a,c,
e.D(),b):R("federatedSignIn",a,c,e.D(),b)});I(f,b);a.s=f}else Ci(a,b)};function kj(a,b,c,d){U.call(this,ig,{email:a,providerId:b},d,"federatedLinking");this.o=c}t(kj,U);kj.prototype.l=function(){this.A(this.o);this.J().focus();kj.c.l.call(this)};kj.prototype.b=function(){this.o=null;kj.c.b.call(this)};r(kj.prototype,{J:ai,A:ci});Q.federatedLinking=function(a,b,c,d,e){var f=th(a.h);if(f&&f.sa){var g=new kj(c,d,function(){Ii(a,g,d)});I(g,b);a.s=g;e&&g.G(e)}else Ci(a,b)};Q.federatedSignIn=function(a,
b,c,d,e){var f=new kj(c,d,function(){Ii(a,f,d)});I(f,b);a.s=f;e&&f.G(e)};function lj(a,b,c,d){var e=b.Hb();e?Z(a,Yh(b,q(a.g.signInWithEmailAndPassword,a.g),[c,e],function(c){return Z(a,c.link(d).then(function(){Gi(a,b,d)}))},function(a){if(!a.name||"cancel"!=a.name)switch(a.code){case "auth/wrong-password":S(b.W(),!1);T(b.Ob(),Y(a));break;case "auth/too-many-requests":b.G(Y(a));break;default:Rg("signInWithEmailAndPassword: "+a.message),b.G(Y(a))}})):b.W().focus()}Q.passwordLinking=function(a,b,c){var d=
th(a.h);ph(kh,a.h);var e=d&&d.sa;if(e){var f=new hi(c,function(){lj(a,f,c,e)},function(){f.j();R("passwordRecovery",a,b,c)});I(f,b);a.s=f}else Ci(a,b)};function mj(a,b,c,d){U.call(this,eg,{email:c,Cb:!!b},d,"passwordRecovery");this.o=a;this.la=b}t(mj,U);mj.prototype.l=function(){this.xa();this.A(this.o,this.la);K(this.u())||this.u().focus();$h(this,this.u(),this.o);mj.c.l.call(this)};mj.prototype.b=function(){this.la=this.o=null;mj.c.b.call(this)};r(mj.prototype,{u:ii,Fa:ji,xa:ki,D:li,ea:mi,J:ai,
ua:bi,A:ci});function nj(a,b){var c=b.ea();if(c){var d=V(b);Z(a,Yh(b,q(a.g.sendPasswordResetEmail,a.g),[c],function(){b.j();var e=new oi(c,function(){e.j();Ci(a,d)});I(e,d);a.s=e},function(a){S(b.u(),!1);T(b.Fa(),Y(a))}))}else b.u().focus()}Q.passwordRecovery=function(a,b,c,d,e){var f=new mj(function(){nj(a,f)},d?void 0:function(){f.j();Ci(a,b)},c);I(f,b);a.s=f;e&&f.G(e)};Q.passwordSignIn=function(a,b,c){var d=new ni(function(){Ji(a,d)},function(){var c=d.D();d.j();R("passwordRecovery",a,b,c)},c);
I(d,b);a.s=d};function oj(){return this.C("firebaseui-id-name")}function pj(){return this.C("firebaseui-id-name-error")}function qj(a,b,c,d,e,f){U.call(this,dg,{email:d,name:e,Hc:a,Cb:!!c},f,"passwordSignUp");this.o=b;this.la=c}t(qj,U);qj.prototype.l=function(){this.xa();this.cd();this.Qb();this.A(this.o,this.la);Zh(this,this.u(),this.Ua());Zh(this,this.Ua(),this.V());this.o&&$h(this,this.V(),this.o);K(this.u())?K(this.Ua())?this.V().focus():this.Ua().focus():this.u().focus();qj.c.l.call(this)};qj.prototype.b=
function(){this.la=this.o=null;qj.c.b.call(this)};r(qj.prototype,{u:ii,Fa:ji,xa:ki,D:li,ea:mi,Ua:oj,Rd:pj,cd:function(){var a=oj.call(this),b=pj.call(this);Jh(this,a,function(){Ph(b)&&(S(a,!0),Oh(b))})},Oc:function(){var a=oj.call(this),b;b=pj.call(this);var c=K(a),c=!/^[\s\xa0]*$/.test(null==c?"":String(c));S(a,c);c?(Oh(b),b=!0):(T(b,D("Enter your account name").toString()),b=!1);return b?qa(K(a)):null},V:$i,Nb:cj,Xc:aj,Qb:dj,Gb:ej,J:ai,ua:bi,A:ci});function rj(a,b){var c=b.ea(),d=b.Oc(),e=b.Gb();
if(c)if(d)if(e){var f=firebase.auth.EmailAuthProvider.credential(c,e);Z(a,Yh(b,q(a.g.createUserWithEmailAndPassword,a.g),[c,e],function(c){return Z(a,c.updateProfile({displayName:d}).then(function(){Gi(a,b,f)}))},function(d){if(!d.name||"cancel"!=d.name){var e=Y(d);switch(d.code){case "auth/email-already-in-use":return sj(a,b,c,d);case "auth/too-many-requests":e=D("Too many account requests are coming from your IP address. Try again in a few minutes.").toString();case "auth/operation-not-allowed":case "auth/weak-password":S(b.V(),
!1);T(b.Nb(),e);break;default:Rg("setAccountInfo: "+Ye(d)),b.G(e)}}}))}else b.V().focus();else b.Ua().focus();else b.u().focus()}function sj(a,b,c,d){function e(){var a=Y(d);S(b.u(),!1);T(b.Fa(),a);b.u().focus()}var f=a.g.fetchProvidersForEmail(c).then(function(d){d.length?e():(d=V(b),b.j(),R("passwordRecovery",a,d,c,!1,tg().toString()))},function(){e()});Z(a,f);return f}Q.passwordSignUp=function(a,b,c,d,e){function f(){g.j();Ci(a,b)}var g=new qj(a.a.a.get("tosUrl")||null,function(){rj(a,g)},e?void 0:
f,c,d);I(g,b);a.s=g};function tj(a,b,c){U.call(this,sg,{nd:b},c,"providerSignIn");this.uc=a}t(tj,U);tj.prototype.l=function(){this.bd(this.uc);tj.c.l.call(this)};tj.prototype.b=function(){this.uc=null;tj.c.b.call(this)};r(tj.prototype,{bd:function(a){function b(b){a(b)}for(var c=this.Mb("firebaseui-id-idp-button"),d=0;d<c.length;d++){var e=c[d],f=vf&&e.dataset?"providerId"in e.dataset?e.dataset.providerId:null:e.getAttribute("data-"+"providerId".replace(/([A-Z])/g,"-$1").toLowerCase());Nh(this,e,
ka(b,f))}}});Q.providerSignIn=function(a,b,c){var d=new tj(function(c){c==firebase.auth.EmailAuthProvider.PROVIDER_ID?(d.j(),Ki(a,b)):Ii(a,d,c)},Eh(a.a));I(d,b);a.s=d;c&&d.G(c)};function uj(a,b,c){U.call(this,bg,{email:b},c,"signIn");this.Ub=a}t(uj,U);uj.prototype.l=function(){this.xa(this.Ub);this.A(this.Ub);this.u().focus();var a=this.u(),b=(this.u().value||"").length,c;try{c="number"==typeof a.selectionStart}catch(d){c=!1}c?(a.selectionStart=b,a.selectionEnd=b):w&&("textarea"==a.type&&(b=a.value.substring(0,
b).replace(/(\r\n|\r|\n)/g,"\n").length),a=a.createTextRange(),a.collapse(!0),a.move("character",b),a.select());uj.c.l.call(this)};uj.prototype.b=function(){this.Ub=null;uj.c.b.call(this)};r(uj.prototype,{u:ii,Fa:ji,xa:ki,D:li,ea:mi,J:ai,A:ci});Q.signIn=function(a,b,c,d){var e=new uj(function(){var b=e,c=b.ea()||"";c&&Li(a,b,c)},c);I(e,b);a.s=e;d&&e.G(d)};function vj(a,b){this.Mc=a;this.g=firebase.initializeApp({apiKey:a.app.options.apiKey,authDomain:a.app.options.authDomain},a.app.name+"-firebaseui-temp").auth();
this.h=b;this.a=new uh;this.s=this.$b=this.jb=this.ac=null;this.ma=[]}vj.prototype.getRedirectResult=function(){this.jb||(this.jb=Ic(this.g.getRedirectResult()));return this.jb};var wj=null;function Mi(){return wj}vj.prototype.start=function(a,b){function c(){wj&&(th(wj.h)&&Ng&&Ng.log(Ud,"UI Widget is already rendered on the page and is pending some user interaction. Only one widget instance can be rendered per page. The previous instance has been automatically reset.",void 0),wj.reset());wj=d}var d=
this;this.zb(b);if("complete"==l.document.readyState){var e=Eg(a);c();d.$b=e;xj(d,e);Qi(d,a)}else wd(window,"load",function(){var b=Eg(a);c();d.$b=b;xj(d,b);Qi(d,a)})};function Z(a,b){if(b){a.ma.push(b);var c=function(){Na(a.ma,function(a){return a==b})};"function"!=typeof b&&b.then(c,c)}}vj.prototype.reset=function(){this.jb=Ic({user:null,credential:null});wj==this&&(wj=null);this.$b=null;for(var a=0;a<this.ma.length;a++)if("function"==typeof this.ma[a])this.ma[a]();else this.ma[a].cancel&&this.ma[a].cancel();
this.ma=[];ph(kh,this.h);this.s&&(this.s.j(),this.s=null);this.gb=null};function xj(a,b){a.gb=null;a.ac=new Lg(b);a.ac.register();pd(a.ac,"pageEnter",function(b){b=b&&b.Td;if(a.gb!=b){var d=Hh(a.a).uiChanged||null;d&&d(a.gb,b);a.gb=b}})}vj.prototype.zb=function(a){this.a.zb(a)};vj.prototype.td=function(){var a,b=this.a,c=Gg(b.a,"widgetUrl");a=Bh(b,c);if(this.a.a.get("popupMode")){var b=(window.screen.availHeight-600)/2,c=(window.screen.availWidth-500)/2,d=a||"about:blank",b={width:500,height:600,
top:0<b?b:0,left:0<c?c:0,location:!0,resizable:!0,statusbar:!0,toolbar:!1};b.target=b.target||d.target||"google_popup";b.width=b.width||690;b.height=b.height||500;var e;(c=b)||(c={});b=window;a=d instanceof ob?d:sb("undefined"!=typeof d.href?d.href:String(d));var d=c.target||d.target,f=[];for(e in c)switch(e){case "width":case "height":case "top":case "left":f.push(e+"="+c[e]);break;case "target":case "noreferrer":break;default:f.push(e+"="+(c[e]?1:0))}e=f.join(",");(v("iPhone")&&!v("iPod")&&!v("iPad")||
v("iPad")||v("iPod"))&&b.navigator&&b.navigator.standalone&&d&&"_self"!=d?(e=b.document.createElement("A"),a=a instanceof ob?a:sb(a),e.href=qb(a),e.setAttribute("target",d),c.noreferrer&&e.setAttribute("rel","noreferrer"),c=document.createEvent("MouseEvent"),c.initMouseEvent("click",!0,!0,b,1),e.dispatchEvent(c),e={}):c.noreferrer?(e=b.open("",d,e),b=qb(a),e&&(ab&&-1!=b.indexOf(";")&&(b="'"+b.replace(/'/g,"%27")+"'"),e.opener=null,b='<META HTTP-EQUIV="refresh" content="0; url='+ra(b)+'">',e.document.write(wb((new ub).dd(b))),
e.document.close())):e=b.open(qb(a),d,e);e&&e.focus()}else window.location.assign(a)};na("firebaseui.auth.AuthUI",vj);na("firebaseui.auth.AuthUI.prototype.start",vj.prototype.start);na("firebaseui.auth.AuthUI.prototype.setConfig",vj.prototype.zb);na("firebaseui.auth.AuthUI.prototype.signIn",vj.prototype.td);na("firebaseui.auth.AuthUI.prototype.reset",vj.prototype.reset);na("firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM",vh);na("firebaseui.auth.CredentialHelper.NONE","none")})(); })();
|
/*
* Selecter Plugin [Formtone Library]
* @author Ben Plum
* @version 2.2.3
*
* Copyright © 2013 Ben Plum <mr@benplum.com>
* Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
if (jQuery) (function($) {
// Mobile Detect
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1,
isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test( (navigator.userAgent||navigator.vendor||window.opera) );
// Default Options
var options = {
callback: function() {},
cover: false,
customClass: "",
defaultLabel: false,
externalLinks: false,
links: false,
trimOptions: false
};
// Identify each instance
var guid = 0;
// Public Methods
var pub = {
// Set Defaults
defaults: function(opts) {
options = $.extend(options, opts || {});
return $(this);
},
// Disable field
disable: function(option) {
return $(this).each(function(i, input) {
var data = $(input).next(".selecter").data("selecter");
if (typeof option != "undefined") {
var index = data.$items.index( data.$items.filter("[data-value=" + option + "]") );
data.$items.eq(index).addClass("disabled");
data.$optionEls.eq(index).prop("disabled", true);
} else {
if (data.$selecter.hasClass("open")) {
data.$selecter.find(".selecter-selected").trigger("click");
}
data.$selecter.addClass("disabled");
data.$selectEl.prop("disabled", true);
}
});
},
// Enable field
enable: function(option) {
return $(this).each(function(i, input) {
var data = $(input).next(".selecter").data("selecter");
if (typeof option != "undefined") {
var index = data.$items.index( data.$items.filter("[data-value=" + option + "]") )
data.$items.eq(index).removeClass("disabled");
data.$optionEls.eq(index).prop("disabled", false);
} else {
data.$selecter.removeClass("disabled");
data.$selectEl.prop("disabled", false);
}
});
},
// Destroy selecter
destroy: function() {
return $(this).each(function(i, input) {
var $input = $(input),
$selecter = $input.next(".selecter");
if ($selecter.hasClass("open")) {
$selecter.find(".selecter-selected").trigger("click");
}
// Scroller support
if ($.fn.scroller != undefined) {
$selecter.find(".selecter-options").scroller("destroy");
}
$input.off(".selecter")
.removeClass("selecter-element")
.show();
$selecter.off(".selecter")
.remove();
});
}
};
// Private Methods
// Initialize
function _init(opts) {
// Local options
opts = $.extend({}, options, opts || {});
// Apply to each element
var $items = $(this);
for (var i = 0, count = $items.length; i < count; i++) {
_build($items.eq(i), opts);
}
return $items;
}
// Build each
function _build($selectEl, opts) {
if (!$selectEl.hasClass("selecter-element")) {
if (opts.externalLinks) {
opts.links = true;
}
// EXTEND OPTIONS
$.extend(opts, $selectEl.data("selecter-options"));
// Build options array
var $allOptionEls = $selectEl.find("option, optgroup"),
$optionEls = $allOptionEls.filter("option"),
$originalOption = $optionEls.filter(":selected"),
originalIndex = (opts.defaultLabel) ? -1 : $optionEls.index($originalOption),
totalItems = $allOptionEls.length - 1,
wrapperTag = (opts.links) ? "nav" : "div",
itemTag = (opts.links) ? "a" : "span";
opts.multiple = $selectEl.prop("multiple");
opts.disabled = $selectEl.is(":disabled");
// Build HTML
var html = '<' + wrapperTag + ' class="selecter ' + opts.customClass;
// Special case classes
if (isMobile) {
html += ' mobile';
} else if (opts.cover) {
html += ' cover';
}
if (opts.multiple) {
html += ' multiple';
} else {
html += ' closed';
}
if (opts.disabled) {
html += ' disabled';
}
html += '">';
if (!opts.multiple) {
html += '<span class="selecter-selected">';
html += $('<span></span').text( _checkLength(opts.trimOptions, ((opts.defaultLabel != false) ? opts.defaultLabel : $originalOption.text())) ).html();
html += '</span>';
}
html += '<div class="selecter-options">';
var j = 0,
$op = null;
for (var i = 0, count = $allOptionEls.length; i < count; i++) {
$op = $($allOptionEls[i]);
// Option group
if ($op[0].tagName == "OPTGROUP") {
html += '<span class="selecter-group';
// Disabled groups
if ($op.is(":disabled")) {
html += ' disabled';
}
html += '">' + $op.attr("label") + '</span>';
} else {
html += '<' + itemTag + ' class="selecter-item';
// Default selected value - now handles multi's thanks to @kuilkoff
if ($op.is(':selected') && !opts.defaultLabel) {
html += ' selected';
}
// Disabled options
if ($op.is(":disabled")) {
html += ' disabled';
}
// CSS styling classes - might ditch for pseudo selectors
if (i == 0) {
html += ' first';
}
if (i == totalItems) {
html += ' last';
}
html += '" ';
if (opts.links) {
html += 'href="' + $op.val() + '"';
} else {
html += 'data-value="' + $op.val() + '"';
}
html += '>' + $("<span></span>").text( _checkLength(opts.trimOptions, $op.text()) ).html() + '</' + itemTag + '>';
j++;
}
}
html += '</div>';
html += '</' + wrapperTag + '>';
// Modify DOM
$selectEl.addClass("selecter-element")
.after(html);
// Store plugin data
var $selecter = $selectEl.next(".selecter");
opts = $.extend({
$selectEl: $selectEl,
$optionEls: $optionEls,
$selecter: $selecter,
$selected: $selecter.find(".selecter-selected"),
$itemsWrapper: $selecter.find(".selecter-options"),
$items: $selecter.find(".selecter-item"),
index: originalIndex,
guid: guid
}, opts);
// Scroller support
if ($.fn.scroller != undefined) {
opts.$itemsWrapper.scroller();
}
// Bind click events
$selecter.on("click.selecter", ".selecter-selected", opts, _handleClick)
.on("click.selecter", ".selecter-item", opts, _select)
.on("selecter-close", opts, _close)
.data("selecter", opts);
// Bind Blur/focus events
if ((!opts.links && !isMobile) || isMobile) {
$selectEl.on("change", opts, _change)
.on("blur.selecter", opts, _blur);
if (!isMobile) {
$selectEl.on("focus.selecter", opts, _focus);
}
} else {
// Disable browser focus/blur for jump links
$selectEl.hide();
}
guid++;
}
}
// Handle Click
function _handleClick(e) {
e.preventDefault();
e.stopPropagation();
var data = e.data;
if (!data.$selectEl.is(":disabled")) {
$(".selecter").not(data.$selecter).trigger("selecter-close", [data]);
// Handle mobile
if (isMobile) {
var el = data.$selectEl[0];
if (document.createEvent) { // All
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(evt);
} else if (element.fireEvent) { // IE
el.fireEvent("onmousedown");
}
} else {
// Delegate intent
if (data.$selecter.hasClass("closed")) {
_open(e);
} else if (data.$selecter.hasClass("open")) {
_close(e);
}
}
}
}
// Open Options
function _open(e) {
e.preventDefault();
e.stopPropagation();
var data = e.data;
// Make sure it's not alerady open
if (!data.$selecter.hasClass("open")) {
var selectOffset = data.$selecter.offset(),
bodyHeight = $("body").outerHeight(),
optionsHeight = data.$itemsWrapper.outerHeight(true);
// Calculate bottom of document if not mobile
if (selectOffset.top + optionsHeight > bodyHeight && isMobile) {
data.$selecter.addClass("bottom");
} else {
data.$selecter.removeClass("bottom");
}
data.$itemsWrapper.show();
// Bind Events
data.$selecter.removeClass("closed")
.addClass("open");
$("body").on("click.selecter-" + data.guid, ":not(.selecter-options)", data, _closeListener);
/* .on("keydown.selecter-" + data.guid, data, _keypress); */
var selectedOffset = (data.index >= 0) ? data.$items.eq(data.index).position() : { left: 0, top: 0 };
if ($.fn.scroller != undefined) {
data.$itemsWrapper.scroller("scroll", (data.$itemsWrapper.find(".scroller-content").scrollTop() + selectedOffset.top), 0)
.scroller("reset");
} else {
data.$itemsWrapper.scrollTop( data.$itemsWrapper.scrollTop() + selectedOffset.top );
}
}
}
// Close Options
function _close(e) {
e.preventDefault();
e.stopPropagation();
var data = e.data;
// Make sure it's actually open
if (data.$selecter.hasClass("open")) {
data.$itemsWrapper.hide();
data.$selecter.removeClass("open").addClass("closed");
$("body").off(".selecter-" + data.guid);
}
}
// Close listener
function _closeListener(e) {
e.preventDefault();
e.stopPropagation();
if ($(e.currentTarget).parents(".selecter").length == 0) {
_close(e);
}
}
// Select option
function _select(e) {
e.preventDefault();
e.stopPropagation();
var $target = $(this),
data = e.data;
if (!data.$selectEl.is(":disabled")) {
if (data.$itemsWrapper.is(":visible")) {
// Update
var index = data.$items.index($target);
_update(index, data, false);
}
if (!data.multiple) {
// Clean up
_close(e);
}
}
}
// Handle outside changes
function _change(e, internal) {
if (!internal) {
var $target = $(this),
data = e.data;
// Mobile link support
if (data.links) {
if (isMobile) {
_launch($target.val(), data.externalLinks);
} else {
_launch($target.attr("href"), data.externalLinks);
}
} else {
// Otherwise update
var index = data.$optionEls.index(data.$optionEls.filter("[value='" + _escape($target.val()) + "']"));
_update(index, data, false);
}
}
}
// Handle focus
function _focus(e) {
e.preventDefault();
e.stopPropagation();
var data = e.data;
if (!data.$selectEl.is(":disabled") && !data.multiple) {
data.$selecter.addClass("focus");
$(".selecter").not(data.$selecter).trigger("selecter-close", [data]);
$("body").on("keydown.selecter-" + data.guid, data, _keypress);
}
}
// Handle blur
function _blur(e) {
e.preventDefault();
e.stopPropagation();
var data = e.data;
data.$selecter.removeClass("focus");
$(".selecter").not(data.$selecter).trigger("selecter-close", [data]);
$("body").off(".selecter-" + data.guid);
}
// Handle keydown on focus
function _keypress(e) {
var data = e.data;
if (data.$selecter.hasClass("open") && e.keyCode == 13) {
_update(data.index, data, false);
_close(e);
} else if (e.keyCode != 9 && (!e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey)) {
// Ignore modifiers & tabs
e.preventDefault();
e.stopPropagation();
var total = data.$items.length - 1,
index = -1;
// Firefox left/right support thanks to Kylemade
if ($.inArray(e.keyCode, (isFirefox) ? [38, 40, 37, 39] : [38, 40]) > -1) {
// Increment / decrement using the arrow keys
index = data.index + ((e.keyCode == 38 || (isFirefox && e.keyCode == 37)) ? -1 : 1);
if (index < 0) {
index = 0;
}
if (index > total) {
index = total;
}
} else {
var input = String.fromCharCode(e.keyCode).toUpperCase();
// Search for input from original index
for (i = data.index + 1; i <= total; i++) {
var letter = data.$optionEls.eq(i).text().charAt(0).toUpperCase();
if (letter == input) {
index = i;
break;
}
}
// If not, start from the beginning
if (index < 0) {
for (i = 0; i <= total; i++) {
var letter = data.$optionEls.eq(i).text().charAt(0).toUpperCase();
if (letter == input) {
index = i;
break;
}
}
}
}
// Update
if (index >= 0) {
_update(index, data, true /* !data.$selecter.hasClass("open") */);
}
}
}
// Update element value + DOM
function _update(index, data, keypress) {
var $item = data.$items.eq(index),
isSelected = $item.hasClass("selected"),
isDisabled = $item.hasClass("disabled");
// Check for disabled options
if (!isDisabled) {
// Make sure we have a new index to prevent false 'change' triggers
if (!isSelected || data.links) {
var newLabel = $item.html(),
newValue = $item.data("value");
// Modify DOM
if (data.multiple) {
data.$optionEls.eq(index).prop("selected", true);
} else {
data.$selected.html(newLabel);
data.$items.filter(".selected").removeClass("selected");
if (!keypress/* || (keypress && !isFirefox) */) {
data.$selectEl[0].selectedIndex = index;
}
if (data.links && !keypress) {
if (isMobile) {
_launch(data.$selectEl.val(), data.externalLinks);
} else {
_launch($item.attr("href"), data.externalLinks);
}
return;
}
}
data.$selectEl.trigger("change", [ true ]);
$item.addClass("selected");
} else if (data.multiple) {
data.$optionEls.eq(index).prop("selected", null);
$item.removeClass("selected");
}
if (!isSelected || data.multiple) {
// Fire callback
data.callback.call(data.$selecter, data.$selectEl.val(), index);
data.index = index;
}
}
}
// Check label's length
function _checkLength(length, text) {
if (length === false) {
return text;
} else {
if (text.length > length) {
return text.substring(0, length) + "...";
} else {
return text;
}
}
}
// Launch link
function _launch(link, external) {
if (external) {
// Open link in a new tab/window
window.open(link);
} else {
// Open link in same tab/window
window.location.href = link;
}
}
// Escape
function _escape(str) {
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}
// Define Plugin
$.fn.selecter = function(method) {
if (pub[method]) {
return pub[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return _init.apply(this, arguments);
}
return this;
};
})(jQuery);
|
export const VOL_AND_READING_BEGIN_TIME = '2012-10'
export const OTHER_BEGIN_TIME = '2016-01'
export const MONTH_MAP = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.','Jun.',
'Jul.', 'Aug.', 'Sep.', 'Otc.', 'Nov.', 'Dec.']
export const AUDIO_PLAY_TEXT = '收听'
export const AUDIO_PLAY_IMG = '../../../image/audio_play.png'
export const AUDIO_PAUSE_TEXT = '暂停'
export const AUDIO_PAUSE_IMG = '../../../image/audio_pause.png'
export const MUSIC_PALY_IMG = '../../../image/music_play.png'
export const MUSIC_PAUSE_IMG = '../../../image/music_pause.png'
|
describe('SheetClip.stringify', function () {
var UNDEFINED = (function () {
}());
describe('JSON specific - data types', function () {
it('should treat undefined as empty string', function () {
var arr = [
[1, UNDEFINED, 3],
[4, 5, 6]
];
var str = SheetClip.stringify(arr);
var expected = '1\t\t3\n4\t5\t6\n';
expect(str).toEqual(expected);
});
it('should treat null as empty string', function () {
var arr = [
[1, null, 3],
[4, 5, 6]
];
var str = SheetClip.stringify(arr);
var expected = '1\t\t3\n4\t5\t6\n';
expect(str).toEqual(expected);
});
});
describe('test files', function () {
it('should stringify plain text values (01_simple.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/01_simple.txt',
json: 'spec/01_simple.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify fully quoted cell (02_quoted_cell.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/02_quoted_cell.txt',
json: 'spec/02_quoted_cell.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify cell with a quoted word (03_quoted_word.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/03_quoted_word.txt',
json: 'spec/03_quoted_word.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify a multiline cell (04_multiline.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/04_multiline.txt',
json: 'spec/04_multiline.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify a multiline cell with a quoted word (05_quoted_multiline.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/05_quoted_multiline.txt',
json: 'spec/05_quoted_multiline.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify a cell that starts with a quote (06_quote_beginning.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/06_quote_beginning.txt',
json: 'spec/06_quote_beginning.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
it('should stringify a cell that ends with a quote (07_quote_ending.json - output from Excel Starter 2010)', function () {
var test = {
tsv: 'spec/07_quote_ending.txt',
json: 'spec/07_quote_ending.json'
};
var files = {};
waitsFor(filesLoaded(test, files));
runs(function () {
var parsedJson = JSON.parse(files.json);
var stringifiedJson = SheetClip.stringify(parsedJson);
expect(stringifiedJson).toEqual(files.tsv);
});
});
});
});
|
var webpack = require('webpack');
var pkg = require('./webtask.json');
var StringReplacePlugin = require("string-replace-webpack-plugin");
module.exports = {
entry: './src/public/react/app',
output: {
filename: './dist/public/'+pkg.name+'-'+pkg.version+'.min.js'
},
module: {
loaders: [{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
}, {
test: /\metrics.jsx$/,
loader: StringReplacePlugin.replace({
replacements: [
{
pattern: /@segmentKey/ig,
replacement: function (match, p1, offset, string) {
return process.env.SEGMENT_KEY_DEV;
}.bind(this)
},
{
pattern: /@dwhEndpoint/ig,
replacement: function (match, p1, offset, string) {
return process.env.DWH_ENDPOINT_DEV;
}.bind(this)
}
]
})
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: [
new StringReplacePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
};
|
const router = require('express').Router()
const { APP_PERMISSIONS } = require('./constants')
const {
handleDeleteCompanyList,
renderDeleteCompanyListPage,
} = require('./controllers/delete')
const {
renderEditCompanyListPage,
handleEditCompanyList,
} = require('./controllers/edit')
const {
fetchListsCompanyIsOn,
handleAddRemoveCompanyToList,
} = require('./controllers/add-remove')
const { fetchCompanyList } = require('./repos')
const { handleRoutePermissions } = require('../middleware')
router.use(handleRoutePermissions(APP_PERMISSIONS))
const {
renderCreateListForm,
createCompanyList,
} = require('./controllers/create')
const { renderAddRemoveForm } = require('./controllers/add-remove')
router.post('/create', createCompanyList)
router.get('/create', renderCreateListForm)
router.get('/add-remove', fetchListsCompanyIsOn, renderAddRemoveForm)
router.post('/add-remove', handleAddRemoveCompanyToList)
router.get('/:listId/delete', fetchCompanyList, renderDeleteCompanyListPage)
router.post('/:listId/delete', handleDeleteCompanyList)
router.get('/:listId/rename', renderEditCompanyListPage)
router.patch('/:listId/rename', handleEditCompanyList)
module.exports = router
|
var DOCUMENTER_CURRENT_VERSION = "latest";
|
(function ($) {
$.fn.parallax = function () {
var window_width = $(window).width();
// Parallax Scripts
return this.each(function(i) {
var $this = $(this);
$this.addClass('parallax');
function updateParallax(initial) {
var container_height;
if (window_width < 601) {
container_height = ($this.height() > 0) ? $this.height() : $this.children("img").height();
}
else {
container_height = ($this.height() > 0) ? $this.height() : 500;
}
var $img = $this.children("img").first();
var img_height = $img.height();
var parallax_dist = img_height - container_height;
var bottom = $this.offset().top + container_height;
var top = $this.offset().top;
var scrollTop = $(window).scrollTop();
var windowHeight = window.innerHeight;
var windowBottom = scrollTop + windowHeight;
var percentScrolled = (windowBottom - top) / (container_height + windowHeight);
var parallax = Math.round((parallax_dist * percentScrolled));
if (initial) {
$img.css('display', 'block');
}
if ((bottom > scrollTop) && (top < (scrollTop + windowHeight))) {
$img.css('transform', "translate3D(-50%," + parallax + "px, 0)");
}
}
// Wait for image load
$this.children("img").one("load", function() {
updateParallax(true);
}).each(function() {
if(this.complete) $(this).load();
});
$(window).scroll(function() {
window_width = $(window).width();
updateParallax(false);
});
$(window).resize(function() {
window_width = $(window).width();
updateParallax(false);
});
});
};
}( jQuery ));
|
'use strict';
/**
* @ignore
* @suppress {dupicate}
*/
var OutdatedCacheError = /** @type {function(new:OutdatedCacheError, string, string, string, string): undefined} */
(require('../../../src/compiler/OutdatedCacheError.js'));
describe('Class OutdatedCacheError', function () {
describe('can be instantiated', function () {
it('with correct parameters', function () {
var err;
expect(function () {
err = new OutdatedCacheError('unit1', 'unit1#outdated-hash', 'unit1#valid-hash',
'/cache/folder/location');
}).not.toThrow();
expect(err).toBeDefined();
expect(err).not.toBeNull();
expect(err).toEqual(jasmine.any(OutdatedCacheError));
});
it('with incorrect parameters', function () {
var err;
expect(function () {
err = new OutdatedCacheError(123, {}, '???', ['some string value']);
}).not.toThrow();
expect(err).toBeDefined();
expect(err).not.toBeNull();
expect(err).toEqual(jasmine.any(OutdatedCacheError));
});
it('without parameters', function () {
var err;
expect(function () {
err = new OutdatedCacheError();
}).not.toThrow();
expect(err).toBeDefined();
expect(err).not.toBeNull();
expect(err).toEqual(jasmine.any(OutdatedCacheError));
});
});
it('inherits from Error', function () {
expect(new OutdatedCacheError()).toEqual(jasmine.any(Error));
});
describe('the method', function () {
var err;
var unitName = 'unit1';
var outdatedUnitHash = 'unit1#outdated-hash';
var validUnitHash = 'unit1#valid-hash';
var cacheFolder = '/cache/folder/location';
beforeEach(function () {
err = new OutdatedCacheError(unitName, outdatedUnitHash, validUnitHash, cacheFolder);
});
it('.getCompilationUnitName() returns the name of the compilation unit for the error context', function () {
expect(err.getCompilationUnitName()).toBe(unitName);
});
it('.getOutdatedCompilationUnitHash() returns the outdated hash of the compilation unit for the error context',
function () {
expect(err.getOutdatedCompilationUnitHash()).toBe(outdatedUnitHash);
});
it('.getValidCompilationUnitHash() returns the valid hash of the compilation unit for the error context',
function () {
expect(err.getValidCompilationUnitHash()).toBe(validUnitHash);
});
it('.getCacheFolderLocation() returns the name of the cache location for the error context', function () {
expect(err.getCacheFolderLocation()).toBe(cacheFolder);
});
});
});
|
// Load modules
var Hoek = require('hoek');
var Boom = require('boom');
// Declare internals
var internals = {
day: 24 * 60 * 60 * 1000
};
exports = module.exports = internals.Policy = function (options, cache, segment) {
Hoek.assert(this.constructor === internals.Policy, 'Cache Policy must be instantiated using new');
this.rule = internals.Policy.compile(options, !!cache);
this._pendings = {}; // id -> [callbacks]
if (cache) {
var nameErr = cache.validateSegmentName(segment);
Hoek.assert(nameErr === null, 'Invalid segment name: ' + segment + (nameErr ? ' (' + nameErr.message + ')' : ''));
this._cache = cache;
this._segment = segment;
}
};
internals.Policy.prototype.get = function (key, callback, _generateFunc) { // key: string or { id: 'id' }
var self = this;
// Check if request is already pending
var id = (key && typeof key === 'object') ? key.id : key;
if (this._pendings[id]) {
this._pendings[id].push(callback);
return;
}
this._pendings[id] = [callback];
// Lookup in cache
var timer = new Hoek.Timer();
this._get(id, function (err, cached) {
if (cached) {
cached.isStale = (self.rule.staleIn ? (Date.now() - cached.stored) >= self.rule.staleIn : false);
}
// No generate method
if (!self.rule.generateFunc &&
!_generateFunc) {
return self._finalize(id, err, cached); // Pass 'cached' as 'value' and omit other arguments for backwards compatibility
}
// Error / Not found
if (err || !cached) {
return self._generate(id, key, null, { msec: timer.elapsed(), error: err }, callback, _generateFunc);
}
// Found
var report = {
msec: timer.elapsed(),
stored: cached.stored,
ttl: cached.ttl,
isStale: cached.isStale
};
// Check if found and fresh
if (!cached.isStale) {
return self._finalize(id, null, cached.item, cached, report);
}
return self._generate(id, key, cached, report, callback, _generateFunc);
});
};
internals.Policy.prototype._get = function (id, callback) {
if (!this._cache) {
return Hoek.nextTick(callback)(null, null);
}
this._cache.get({ segment: this._segment, id: id }, callback);
};
internals.Policy.prototype._generate = function (id, key, cached, report, callback, _generateFunc) {
var self = this;
if (cached &&
cached.isStale) {
// Set stale timeout
cached.ttl -= this.rule.staleTimeout; // Adjust TTL for when the timeout is invoked (staleTimeout must be valid if isStale is true)
if (cached.ttl > 0) {
setTimeout(function () {
return self._finalize(id, null, cached.item, cached, report);
}, this.rule.staleTimeout);
}
}
else if (this.rule.generateTimeout) {
// Set item generation timeout (when not in cache)
setTimeout(function () {
return self._finalize(id, Boom.serverTimeout(), null, null, report);
}, this.rule.generateTimeout);
}
// Generate new value
try {
(this.rule.generateFunc || _generateFunc).call(null, key, function (err, value, ttl) {
// Error or not cached
if (err ||
ttl === 0) { // null or undefined means use policy
self.drop(id); // Invalidate cache
}
else {
self.set(id, value, ttl); // Lazy save (replaces stale cache copy with late-coming fresh copy)
}
return self._finalize(id, err, value, null, report); // Ignored if stale value already returned
});
}
catch (err) {
this._finalize(id, err, null, null, report);
}
};
internals.Policy.prototype._finalize = function (id, err, value, cached, report) {
var pendings = this._pendings[id];
if (!pendings) {
return;
}
delete this._pendings[id]; // Return only the first callback between stale timeout and generated fresh
for (var i = 0, il = pendings.length; i < il; ++i) {
pendings[i](err, value, cached, report);
}
};
internals.Policy.prototype.getOrGenerate = function (id, generateFunc, callback) { // For backwards compatibility
var self = this;
var generateFuncWrapper = function (id, next) {
return generateFunc(next);
};
return this.get(id, callback, generateFuncWrapper);
};
internals.Policy.prototype.set = function (key, value, ttl, callback) {
callback = callback || Hoek.ignore;
if (!this._cache) {
return callback(null);
}
ttl = ttl || internals.Policy.ttl(this.rule);
var id = (key && typeof key === 'object') ? key.id : key;
this._cache.set({ segment: this._segment, id: id }, value, ttl, callback);
};
internals.Policy.prototype.drop = function (id, callback) {
callback = callback || Hoek.ignore;
if (!this._cache) {
return callback(null);
}
this._cache.drop({ segment: this._segment, id: id }, callback);
};
internals.Policy.prototype.ttl = function (created) {
return internals.Policy.ttl(this.rule, created);
};
internals.Policy.compile = function (options, serverSide) {
/*
{
expiresIn: 30000,
expiresAt: '13:00',
generateFunc: function (id, next) { next(err, result, ttl); }
generateTimeout: 500,
staleIn: 20000,
staleTimeout: 500
}
*/
var rule = {};
if (!options ||
!Object.keys(options).length) {
return rule;
}
// Validate rule
var hasExpiresIn = options.expiresIn !== undefined && options.expiresIn !== null;
var hasExpiresAt = options.expiresAt !== undefined && options.expiresAt !== null;
Hoek.assert(!hasExpiresAt || typeof options.expiresAt === 'string', 'expiresAt must be a string', options);
Hoek.assert(!hasExpiresIn || Hoek.isInteger(options.expiresIn), 'expiresIn must be an integer', options);
Hoek.assert(!hasExpiresIn || !hasExpiresAt, 'Rule cannot include both expiresIn and expiresAt', options); // XOR
Hoek.assert(!hasExpiresAt || !options.staleIn || options.staleIn < 86400000, 'staleIn must be less than 86400000 milliseconds (one day) when using expiresAt');
Hoek.assert(!hasExpiresIn || !options.staleIn || options.staleIn < options.expiresIn, 'staleIn must be less than expiresIn');
Hoek.assert(!options.staleIn || serverSide, 'Cannot use stale options without server-side caching');
Hoek.assert(!(!!options.staleIn ^ !!options.staleTimeout), 'Rule must include both of staleIn and staleTimeout or none'); // XNOR
Hoek.assert(!options.staleTimeout || !hasExpiresIn || options.staleTimeout < options.expiresIn, 'staleTimeout must be less than expiresIn');
Hoek.assert(!options.staleTimeout || !hasExpiresIn || options.staleTimeout < (options.expiresIn - options.staleIn), 'staleTimeout must be less than the delta between expiresIn and staleIn');
// Hoek.assert(options.generateFunc || !options.generateTimeout, 'Rule cannot include generateTimeout without generateFunc'); // Disabled for backwards compatibility
Hoek.assert(!options.generateFunc || typeof options.generateFunc === 'function', 'generateFunc must be a function');
// Expiration
if (hasExpiresAt) {
// expiresAt
var time = /^(\d\d?):(\d\d)$/.exec(options.expiresAt);
Hoek.assert(time && time.length === 3, 'Invalid time string for expiresAt: ' + options.expiresAt);
rule.expiresAt = {
hours: parseInt(time[1], 10),
minutes: parseInt(time[2], 10)
};
}
else {
// expiresIn
rule.expiresIn = options.expiresIn || 0;
}
// generateTimeout
if (options.generateFunc) {
rule.generateFunc = options.generateFunc;
}
if (options.generateTimeout) { // Keep outside options.generateFunc condition for backwards compatibility
rule.generateTimeout = options.generateTimeout;
}
// Stale
if (options.staleIn) { // Keep outside options.generateFunc condition for backwards compatibility
rule.staleIn = options.staleIn;
rule.staleTimeout = options.staleTimeout;
}
return rule;
};
internals.Policy.ttl = function (rule, created, now) {
now = now || Date.now();
created = created || now;
var age = now - created;
if (age < 0) {
return 0; // Created in the future, assume expired/bad
}
if (rule.expiresIn) {
return Math.max(rule.expiresIn - age, 0);
}
if (rule.expiresAt) {
if (age > internals.day) { // If the item was created more than a 24 hours ago
return 0;
}
var expiresAt = new Date(created); // Compare expiration time on the same day
expiresAt.setHours(rule.expiresAt.hours);
expiresAt.setMinutes(rule.expiresAt.minutes);
expiresAt.setSeconds(0);
expiresAt.setMilliseconds(0);
var expires = expiresAt.getTime();
if (expires <= created) {
expires += internals.day; // Move to tomorrow
}
if (now >= expires) { // Expired
return 0;
}
return expires - now;
}
return 0; // No rule
};
|
var AWS = require('../core');
var byteLength = AWS.util.string.byteLength;
var Buffer = AWS.util.Buffer;
/**
* The managed uploader allows for easy and efficient uploading of buffers,
* blobs, or streams, using a configurable amount of concurrency to perform
* multipart uploads where possible. This abstraction also enables uploading
* streams of unknown size due to the use of multipart uploads.
*
* To construct a managed upload object, see the {constructor} function.
*
* ## Tracking upload progress
*
* The managed upload object can also track progress by attaching an
* 'httpUploadProgress' listener to the upload manager. This event is similar
* to {AWS.Request~httpUploadProgress} but groups all concurrent upload progress
* into a single event. See {AWS.S3.ManagedUpload~httpUploadProgress} for more
* information.
*
* ## Handling Multipart Cleanup
*
* By default, this class will automatically clean up any multipart uploads
* when an individual part upload fails. This behavior can be disabled in order
* to manually handle failures by setting the `leavePartsOnError` configuration
* option to `true` when initializing the upload object.
*
* @!event httpUploadProgress(progress)
* Triggered when the uploader has uploaded more data.
* @note The `total` property may not be set if the stream being uploaded has
* not yet finished chunking. In this case the `total` will be undefined
* until the total stream size is known.
* @note This event will not be emitted in Node.js 0.8.x.
* @param progress [map] An object containing the `loaded` and `total` bytes
* of the request and the `key` of the S3 object. Note that `total` may be undefined until the payload
* size is known.
* @context (see AWS.Request~send)
*/
AWS.S3.ManagedUpload = AWS.util.inherit({
/**
* Creates a managed upload object with a set of configuration options.
*
* @note A "Body" parameter is required to be set prior to calling {send}.
* @option options params [map] a map of parameters to pass to the upload
* requests. The "Body" parameter is required to be specified either on
* the service or in the params option.
* @note ContentMD5 should not be provided when using the managed upload object.
* Instead, setting "computeChecksums" to true will enable automatic ContentMD5 generation
* by the managed upload object.
* @option options queueSize [Number] (4) the size of the concurrent queue
* manager to upload parts in parallel. Set to 1 for synchronous uploading
* of parts. Note that the uploader will buffer at most queueSize * partSize
* bytes into memory at any given time.
* @option options partSize [Number] (5mb) the size in bytes for each
* individual part to be uploaded. Adjust the part size to ensure the number
* of parts does not exceed {maxTotalParts}. See {minPartSize} for the
* minimum allowed part size.
* @option options leavePartsOnError [Boolean] (false) whether to abort the
* multipart upload if an error occurs. Set to true if you want to handle
* failures manually.
* @option options service [AWS.S3] an optional S3 service object to use for
* requests. This object might have bound parameters used by the uploader.
* @option options tags [Array<map>] The tags to apply to the uploaded object.
* Each tag should have a `Key` and `Value` keys.
* @example Creating a default uploader for a stream object
* var upload = new AWS.S3.ManagedUpload({
* params: {Bucket: 'bucket', Key: 'key', Body: stream}
* });
* @example Creating an uploader with concurrency of 1 and partSize of 10mb
* var upload = new AWS.S3.ManagedUpload({
* partSize: 10 * 1024 * 1024, queueSize: 1,
* params: {Bucket: 'bucket', Key: 'key', Body: stream}
* });
* @example Creating an uploader with tags
* var upload = new AWS.S3.ManagedUpload({
* params: {Bucket: 'bucket', Key: 'key', Body: stream},
* tags: [{Key: 'tag1', Value: 'value1'}, {Key: 'tag2', Value: 'value2'}]
* });
* @see send
*/
constructor: function ManagedUpload(options) {
var self = this;
AWS.SequentialExecutor.call(self);
self.body = null;
self.sliceFn = null;
self.callback = null;
self.parts = {};
self.completeInfo = [];
self.fillQueue = function() {
self.callback(new Error('Unsupported body payload ' + typeof self.body));
};
self.configure(options);
},
/**
* @api private
*/
configure: function configure(options) {
options = options || {};
this.partSize = this.minPartSize;
if (options.queueSize) this.queueSize = options.queueSize;
if (options.partSize) this.partSize = options.partSize;
if (options.leavePartsOnError) this.leavePartsOnError = true;
if (options.tags) {
if (!Array.isArray(options.tags)) {
throw new Error('Tags must be specified as an array; ' +
typeof options.tags + ' provided.');
}
this.tags = options.tags;
}
if (this.partSize < this.minPartSize) {
throw new Error('partSize must be greater than ' +
this.minPartSize);
}
this.service = options.service;
this.bindServiceObject(options.params);
this.validateBody();
this.adjustTotalBytes();
},
/**
* @api private
*/
leavePartsOnError: false,
/**
* @api private
*/
queueSize: 4,
/**
* @api private
*/
partSize: null,
/**
* @readonly
* @return [Number] the minimum number of bytes for an individual part
* upload.
*/
minPartSize: 1024 * 1024 * 5,
/**
* @readonly
* @return [Number] the maximum allowed number of parts in a multipart upload.
*/
maxTotalParts: 10000,
/**
* Initiates the managed upload for the payload.
*
* @callback callback function(err, data)
* @param err [Error] an error or null if no error occurred.
* @param data [map] The response data from the successful upload:
* * `Location` (String) the URL of the uploaded object
* * `ETag` (String) the ETag of the uploaded object
* * `Bucket` (String) the bucket to which the object was uploaded
* * `Key` (String) the key to which the object was uploaded
* @example Sending a managed upload object
* var params = {Bucket: 'bucket', Key: 'key', Body: stream};
* var upload = new AWS.S3.ManagedUpload({params: params});
* upload.send(function(err, data) {
* console.log(err, data);
* });
*/
send: function(callback) {
var self = this;
self.failed = false;
self.callback = callback || function(err) { if (err) throw err; };
var runFill = true;
if (self.sliceFn) {
self.fillQueue = self.fillBuffer;
} else if (AWS.util.isNode()) {
var Stream = AWS.util.stream.Stream;
if (self.body instanceof Stream) {
runFill = false;
self.fillQueue = self.fillStream;
self.partBuffers = [];
self.body.
on('error', function(err) { self.cleanup(err); }).
on('readable', function() { self.fillQueue(); }).
on('end', function() {
self.isDoneChunking = true;
self.numParts = self.totalPartNumbers;
self.fillQueue.call(self);
if (self.isDoneChunking && self.totalPartNumbers >= 1 && self.doneParts === self.numParts) {
self.finishMultiPart();
}
});
}
}
if (runFill) self.fillQueue.call(self);
},
/**
* @!method promise()
* Returns a 'thenable' promise.
*
* Two callbacks can be provided to the `then` method on the returned promise.
* The first callback will be called if the promise is fulfilled, and the second
* callback will be called if the promise is rejected.
* @callback fulfilledCallback function(data)
* Called if the promise is fulfilled.
* @param data [map] The response data from the successful upload:
* `Location` (String) the URL of the uploaded object
* `ETag` (String) the ETag of the uploaded object
* `Bucket` (String) the bucket to which the object was uploaded
* `Key` (String) the key to which the object was uploaded
* @callback rejectedCallback function(err)
* Called if the promise is rejected.
* @param err [Error] an error or null if no error occurred.
* @return [Promise] A promise that represents the state of the upload request.
* @example Sending an upload request using promises.
* var upload = s3.upload({Bucket: 'bucket', Key: 'key', Body: stream});
* var promise = upload.promise();
* promise.then(function(data) { ... }, function(err) { ... });
*/
/**
* Aborts a managed upload, including all concurrent upload requests.
* @note By default, calling this function will cleanup a multipart upload
* if one was created. To leave the multipart upload around after aborting
* a request, configure `leavePartsOnError` to `true` in the {constructor}.
* @note Calling {abort} in the browser environment will not abort any requests
* that are already in flight. If a multipart upload was created, any parts
* not yet uploaded will not be sent, and the multipart upload will be cleaned up.
* @example Aborting an upload
* var params = {
* Bucket: 'bucket', Key: 'key',
* Body: new Buffer(1024 * 1024 * 25) // 25MB payload
* };
* var upload = s3.upload(params);
* upload.send(function (err, data) {
* if (err) console.log("Error:", err.code, err.message);
* else console.log(data);
* });
*
* // abort request in 1 second
* setTimeout(upload.abort.bind(upload), 1000);
*/
abort: function() {
this.cleanup(AWS.util.error(new Error('Request aborted by user'), {
code: 'RequestAbortedError', retryable: false
}));
},
/**
* @api private
*/
validateBody: function validateBody() {
var self = this;
self.body = self.service.config.params.Body;
if (typeof self.body === 'string') {
self.body = new AWS.util.Buffer(self.body);
} else if (!self.body) {
throw new Error('params.Body is required');
}
self.sliceFn = AWS.util.arraySliceFn(self.body);
},
/**
* @api private
*/
bindServiceObject: function bindServiceObject(params) {
params = params || {};
var self = this;
// bind parameters to new service object
if (!self.service) {
self.service = new AWS.S3({params: params});
} else {
var service = self.service;
var config = AWS.util.copy(service.config);
config.signatureVersion = service.getSignatureVersion();
self.service = new service.constructor.__super__(config);
self.service.config.params =
AWS.util.merge(self.service.config.params || {}, params);
}
},
/**
* @api private
*/
adjustTotalBytes: function adjustTotalBytes() {
var self = this;
try { // try to get totalBytes
self.totalBytes = byteLength(self.body);
} catch (e) { }
// try to adjust partSize if we know payload length
if (self.totalBytes) {
var newPartSize = Math.ceil(self.totalBytes / self.maxTotalParts);
if (newPartSize > self.partSize) self.partSize = newPartSize;
} else {
self.totalBytes = undefined;
}
},
/**
* @api private
*/
isDoneChunking: false,
/**
* @api private
*/
partPos: 0,
/**
* @api private
*/
totalChunkedBytes: 0,
/**
* @api private
*/
totalUploadedBytes: 0,
/**
* @api private
*/
totalBytes: undefined,
/**
* @api private
*/
numParts: 0,
/**
* @api private
*/
totalPartNumbers: 0,
/**
* @api private
*/
activeParts: 0,
/**
* @api private
*/
doneParts: 0,
/**
* @api private
*/
parts: null,
/**
* @api private
*/
completeInfo: null,
/**
* @api private
*/
failed: false,
/**
* @api private
*/
multipartReq: null,
/**
* @api private
*/
partBuffers: null,
/**
* @api private
*/
partBufferLength: 0,
/**
* @api private
*/
fillBuffer: function fillBuffer() {
var self = this;
var bodyLen = byteLength(self.body);
if (bodyLen === 0) {
self.isDoneChunking = true;
self.numParts = 1;
self.nextChunk(self.body);
return;
}
while (self.activeParts < self.queueSize && self.partPos < bodyLen) {
var endPos = Math.min(self.partPos + self.partSize, bodyLen);
var buf = self.sliceFn.call(self.body, self.partPos, endPos);
self.partPos += self.partSize;
if (byteLength(buf) < self.partSize || self.partPos === bodyLen) {
self.isDoneChunking = true;
self.numParts = self.totalPartNumbers + 1;
}
self.nextChunk(buf);
}
},
/**
* @api private
*/
fillStream: function fillStream() {
var self = this;
if (self.activeParts >= self.queueSize) return;
var buf = self.body.read(self.partSize - self.partBufferLength) ||
self.body.read();
if (buf) {
self.partBuffers.push(buf);
self.partBufferLength += buf.length;
self.totalChunkedBytes += buf.length;
}
if (self.partBufferLength >= self.partSize) {
// if we have single buffer we avoid copyfull concat
var pbuf = self.partBuffers.length === 1 ?
self.partBuffers[0] : Buffer.concat(self.partBuffers);
self.partBuffers = [];
self.partBufferLength = 0;
// if we have more than partSize, push the rest back on the queue
if (pbuf.length > self.partSize) {
var rest = pbuf.slice(self.partSize);
self.partBuffers.push(rest);
self.partBufferLength += rest.length;
pbuf = pbuf.slice(0, self.partSize);
}
self.nextChunk(pbuf);
}
if (self.isDoneChunking && !self.isDoneSending) {
// if we have single buffer we avoid copyfull concat
pbuf = self.partBuffers.length === 1 ?
self.partBuffers[0] : Buffer.concat(self.partBuffers);
self.partBuffers = [];
self.partBufferLength = 0;
self.totalBytes = self.totalChunkedBytes;
self.isDoneSending = true;
if (self.numParts === 0 || pbuf.length > 0) {
self.numParts++;
self.nextChunk(pbuf);
}
}
self.body.read(0);
},
/**
* @api private
*/
nextChunk: function nextChunk(chunk) {
var self = this;
if (self.failed) return null;
var partNumber = ++self.totalPartNumbers;
if (self.isDoneChunking && partNumber === 1) {
var params = {Body: chunk};
if (this.tags) {
params.Tagging = this.getTaggingHeader();
}
var req = self.service.putObject(params);
req._managedUpload = self;
req.on('httpUploadProgress', self.progress).send(self.finishSinglePart);
return null;
} else if (self.service.config.params.ContentMD5) {
var err = AWS.util.error(new Error('The Content-MD5 you specified is invalid for multi-part uploads.'), {
code: 'InvalidDigest', retryable: false
});
self.cleanup(err);
return null;
}
if (self.completeInfo[partNumber] && self.completeInfo[partNumber].ETag !== null) {
return null; // Already uploaded this part.
}
self.activeParts++;
if (!self.service.config.params.UploadId) {
if (!self.multipartReq) { // create multipart
self.multipartReq = self.service.createMultipartUpload();
self.multipartReq.on('success', function(resp) {
self.service.config.params.UploadId = resp.data.UploadId;
self.multipartReq = null;
});
self.queueChunks(chunk, partNumber);
self.multipartReq.on('error', function(err) {
self.cleanup(err);
});
self.multipartReq.send();
} else {
self.queueChunks(chunk, partNumber);
}
} else { // multipart is created, just send
self.uploadPart(chunk, partNumber);
}
},
/**
* @api private
*/
getTaggingHeader: function getTaggingHeader() {
var kvPairStrings = [];
for (var i = 0; i < this.tags.length; i++) {
kvPairStrings.push(AWS.util.uriEscape(this.tags[i].Key) + '=' +
AWS.util.uriEscape(this.tags[i].Value));
}
return kvPairStrings.join('&');
},
/**
* @api private
*/
uploadPart: function uploadPart(chunk, partNumber) {
var self = this;
var partParams = {
Body: chunk,
ContentLength: AWS.util.string.byteLength(chunk),
PartNumber: partNumber
};
var partInfo = {ETag: null, PartNumber: partNumber};
self.completeInfo[partNumber] = partInfo;
var req = self.service.uploadPart(partParams);
self.parts[partNumber] = req;
req._lastUploadedBytes = 0;
req._managedUpload = self;
req.on('httpUploadProgress', self.progress);
req.send(function(err, data) {
delete self.parts[partParams.PartNumber];
self.activeParts--;
if (!err && (!data || !data.ETag)) {
var message = 'No access to ETag property on response.';
if (AWS.util.isBrowser()) {
message += ' Check CORS configuration to expose ETag header.';
}
err = AWS.util.error(new Error(message), {
code: 'ETagMissing', retryable: false
});
}
if (err) return self.cleanup(err);
partInfo.ETag = data.ETag;
self.doneParts++;
if (self.isDoneChunking && self.doneParts === self.numParts) {
self.finishMultiPart();
} else {
self.fillQueue.call(self);
}
});
},
/**
* @api private
*/
queueChunks: function queueChunks(chunk, partNumber) {
var self = this;
self.multipartReq.on('success', function() {
self.uploadPart(chunk, partNumber);
});
},
/**
* @api private
*/
cleanup: function cleanup(err) {
var self = this;
if (self.failed) return;
// clean up stream
if (typeof self.body.removeAllListeners === 'function' &&
typeof self.body.resume === 'function') {
self.body.removeAllListeners('readable');
self.body.removeAllListeners('end');
self.body.resume();
}
// cleanup multipartReq listeners
if (self.multipartReq) {
self.multipartReq.removeAllListeners('success');
self.multipartReq.removeAllListeners('error');
self.multipartReq.removeAllListeners('complete');
delete self.multipartReq;
}
if (self.service.config.params.UploadId && !self.leavePartsOnError) {
self.service.abortMultipartUpload().send();
} else if (self.leavePartsOnError) {
self.isDoneChunking = false;
}
AWS.util.each(self.parts, function(partNumber, part) {
part.removeAllListeners('complete');
part.abort();
});
self.activeParts = 0;
self.partPos = 0;
self.numParts = 0;
self.totalPartNumbers = 0;
self.parts = {};
self.failed = true;
self.callback(err);
},
/**
* @api private
*/
finishMultiPart: function finishMultiPart() {
var self = this;
var completeParams = { MultipartUpload: { Parts: self.completeInfo.slice(1) } };
self.service.completeMultipartUpload(completeParams, function(err, data) {
if (err) {
return self.cleanup(err);
}
if (data && typeof data.Location === 'string') {
data.Location = data.Location.replace(/%2F/g, '/');
}
if (Array.isArray(self.tags)) {
self.service.putObjectTagging(
{Tagging: {TagSet: self.tags}},
function(e, d) {
if (e) {
self.callback(e);
} else {
self.callback(e, data);
}
}
);
} else {
self.callback(err, data);
}
});
},
/**
* @api private
*/
finishSinglePart: function finishSinglePart(err, data) {
var upload = this.request._managedUpload;
var httpReq = this.request.httpRequest;
var endpoint = httpReq.endpoint;
if (err) return upload.callback(err);
data.Location =
[endpoint.protocol, '//', endpoint.host, httpReq.path].join('');
data.key = this.request.params.Key; // will stay undocumented
data.Key = this.request.params.Key;
data.Bucket = this.request.params.Bucket;
upload.callback(err, data);
},
/**
* @api private
*/
progress: function progress(info) {
var upload = this._managedUpload;
if (this.operation === 'putObject') {
info.part = 1;
info.key = this.params.Key;
} else {
upload.totalUploadedBytes += info.loaded - this._lastUploadedBytes;
this._lastUploadedBytes = info.loaded;
info = {
loaded: upload.totalUploadedBytes,
total: upload.totalBytes,
part: this.params.PartNumber,
key: this.params.Key
};
}
upload.emit('httpUploadProgress', [info]);
}
});
AWS.util.mixin(AWS.S3.ManagedUpload, AWS.SequentialExecutor);
/**
* @api private
*/
AWS.S3.ManagedUpload.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
this.prototype.promise = AWS.util.promisifyMethod('send', PromiseDependency);
};
/**
* @api private
*/
AWS.S3.ManagedUpload.deletePromisesFromClass = function deletePromisesFromClass() {
delete this.prototype.promise;
};
AWS.util.addPromises(AWS.S3.ManagedUpload);
/**
* @api private
*/
module.exports = AWS.S3.ManagedUpload;
|
/* IIP Protocol Handler
*/
Protocols.IIP = new Class({
/* Return metadata URL
*/
getMetaDataURL: function(server,image){
return server+"?FIF=" + image + "&obj=IIP,1.0&obj=Max-size&obj=Tile-size&obj=Resolution-number";
},
/* Return an individual tile request URL
*/
getTileURL: function(t){
var modifiers = Array( '?FIF=' + t.image );
if( t.contrast ) modifiers.push( 'CNT=' + t.contrast );
if( t.sds ) modifiers.push( 'SDS=' + t.sds );
if( t.rotation ) modifiers.push( 'ROT=' + t.rotation );
if( t.gamma ) modifiers.push( 'GAM=' + t.gamma );
if( t.shade ) modifiers.push( 'SHD=' + t.shade );
modifiers.push( 'JTL=' + t.resolution + ',' + t.tileindex );
return t.server+modifiers.join('&');
},
/* Parse an IIP protocol metadata request
*/
parseMetaData: function(response){
var tmp = response.split( "Max-size" );
if(!tmp[1]) return null;
var size = tmp[1].split(" ");
var max_size = { w: parseInt(size[0].substring(1,size[0].length)),
h: parseInt(size[1]) };
tmp = response.split( "Tile-size" );
if(!tmp[1]) return null;
size = tmp[1].split(" ");
var tileSize = { w: parseInt(size[0].substring(1,size[0].length)),
h: parseInt(size[1]) };
tmp = response.split( "Resolution-number" );
var num_resolutions = parseInt( tmp[1].substring(1,tmp[1].length) );
var result = {
'max_size': max_size,
'tileSize': tileSize,
'num_resolutions': num_resolutions
};
return result;
},
/* Return URL for a full view
*/
getRegionURL: function(server,image,region,width){
var rgn = region.x + ',' + region.y + ',' + region.w + ',' + region.h;
return server+'?FIF='+image+'&WID='+width+'&RGN='+rgn+'&CVT=jpeg';
},
/* Return thumbnail URL
*/
getThumbnailURL: function(server,image,width){
return server+'?FIF='+image+'&WID='+width+'&QLT=98&CVT=jpeg';
}
});
|
js.extend('lsn.hashtable.view', function (js) {
var CComboBox = js.hubb.ui.ComboBox;
this.FileCombo = function () {
CComboBox.apply(this);
};
var FileCombo = this.FileCombo.prototype = js.lang.createMethods(CComboBox);
FileCombo.canExpand = function (tnode) {
return tnode.data.isDirectory();
};
FileCombo.canDisplay = function (tnode) {
return tnode.getKey() != 'index.hf';
};
});
|
const BaseCardSelector = require('./BaseCardSelector.js');
class ExactlyXCardSelector extends BaseCardSelector {
constructor(numCards, properties) {
super(properties);
this.numCards = numCards;
}
defaultActivePromptTitle() {
return this.numCards === 1 ? 'Select a character' : `Select ${this.numCards} characters`;
}
hasEnoughSelected(selectedCards) {
return selectedCards.length === 0 && this.optional || selectedCards.length === this.numCards;
}
hasEnoughTargets(context) {
let numMatchingCards = context.game.allCards.reduce((total, card) => {
if(this.canTarget(card, context)) {
return total + 1;
}
return total;
}, 0);
return this.optional || numMatchingCards >= this.numCards;
}
hasReachedLimit(selectedCards) {
return selectedCards.length >= this.numCards;
}
}
module.exports = ExactlyXCardSelector;
|
/**
* app/controllers/product.js
* @type {exports}
*/
var InvalidArgumentError = require('../errors/invalidArgument'),
InternalServerError = require('../errors/internal'),
ProductModel = require('../models/product');
var ProductController = function () {};
/**
* Find one Product by Id
*
* @param req
* @param res
* @param next
*/
ProductController.prototype.getOne = function (req, res, next) {
var id = req.params.id;
ProductModel.findOne({_id: id}, function (err, product) {
if (err) {
var error = new InternalServerError('Internal Server Error: problem finding row');
return next(error);
}
res.status(200).send(product);
});
};
/**
* Get a collection of Products
*
* @param req
* @param res
* @param next
*/
ProductController.prototype.get = function (req, res, next) {
var shop = req.query.shop || null;
var model = req.query.model || null;
var manufacturer = req.query.manufacturer || null;
var category = req.query.category || null;
var query = {};
if (shop) query.shop = shop;
if (model) query.model = model;
if (manufacturer) query.manufacturer = manufacturer;
if (category) query.category = category;
ProductModel.find(query,
function (err, data) {
if (err) {
var error = new InternalServerError('Internal Server Error: problem saving product to DB');
return next(error);
}
return res.status(200).send(data);
});
};
/**
* Create a Product
*
* @param req
* @param res
* @param next
* @returns {*}
*/
ProductController.prototype.create = function (req, res, next) {
var name = req.body.name || '';
var model = req.body.model || '';
var manufacturer = req.body.manufacturer || '';
var category = req.body.category || '';
var description = req.body.description || '';
var comments = req.body.comments || '';
var partno = req.body.partno || '';
var ean = req.body.ean || '';
var upc = req.body.upc || '';
if (name == '' || model == '' || manufacturer == '') {
var err = new InvalidArgumentError('Name, Model, Manufacturer fields are required');
return next(err);
}
var newProduct = new ProductModel({
name: name,
model: model,
manufacturer: manufacturer,
category: category,
description: description,
comments: comments,
partno: partno,
ean: ean,
upc: upc
});
newProduct.save(function (err, data) {
if (err) {
var error = new InternalServerError('Internal Server Error: problem saving product to DB');
return next(error);
}
return res.status(200).send({'id': data._id});
});
};
/**
* Update a Product
*
* @param req
* @param res
* @param next
*/
ProductController.prototype.update = function (req, res, next) {
var id = req.params.id;
var name = req.body.name || '';
var model = req.body.model || '';
var manufacturer = req.body.manufacturer || '';
var category = req.body.category || '';
var description = req.body.description || '';
var comments = req.body.comments || '';
var partno = req.body.partno || '';
var ean = req.body.ean || '';
var upc = req.body.upc || '';
var doc = {};
if (name) doc.name = name;
if (model) doc.model = model;
if (manufacturer) doc.manufacturer = manufacturer;
if (category) doc.category = category;
if (description) doc.description = description;
if (comments) doc.comments = comments;
if (partno) doc.partno = partno;
if (ean) doc.ean = ean;
if (upc) doc.upc = upc;
ProductModel.update({_id: id}, doc, function (err) {
if (err) {
var error = new InternalServerError('Internal Server Error: problem updating row');
return next(error);
}
res.status(200).send();
});
};
/**
* Remove a Product
*
* @param req
* @param res
* @param next
*/
ProductController.prototype.remove = function (req, res, next) {
var id = req.params.id;
ProductModel.findOne({_id: id}).remove(function (err) {
if (err) {
var error = new InternalServerError('Internal Server Error: problem finding row');
return next(error);
}
res.status(200).send();
});
};
module.exports = new ProductController();
|
export default function transformAngleBracketComponents(/* env */) {
return {
name: 'transform-angle-bracket-components',
visitor: {
ComponentNode(node) {
node.tag = `<${node.tag}>`;
},
},
};
}
|
'use strict';
const iconv = require('iconv-lite');
const encodingJapanese = require('encoding-japanese');
const charsets = require('./charsets');
/**
* Character set encoding and decoding functions
*/
const charset = (module.exports = {
/**
* Encodes an unicode string into an Buffer object as UTF-8
*
* We force UTF-8 here, no strange encodings allowed.
*
* @param {String} str String to be encoded
* @return {Buffer} UTF-8 encoded typed array
*/
encode(str) {
return Buffer.from(str, 'utf-8');
},
/**
* Decodes a string from Buffer to an unicode string using specified encoding
* NB! Throws if unknown charset is used
*
* @param {Buffer} buf Binary data to be decoded
* @param {String} [fromCharset='UTF-8'] Binary data is decoded into string using this charset
* @return {String} Decded string
*/
decode(buf, fromCharset) {
fromCharset = charset.normalizeCharset(fromCharset || 'UTF-8');
if (/^(us-)?ascii|utf-8|7bit$/i.test(fromCharset)) {
return buf.toString('utf-8');
}
try {
if (/^jis|^iso-?2022-?jp|^EUCJP/i.test(fromCharset)) {
if (typeof buf === 'string') {
buf = Buffer.from(buf);
}
try {
let output = encodingJapanese.convert(buf, {
to: 'UNICODE',
from: fromCharset,
type: 'string'
});
if (typeof output === 'string') {
output = Buffer.from(output);
}
return output;
} catch (err) {
// ignore, defaults to iconv-lite on error
}
}
return iconv.decode(buf, fromCharset);
} catch (err) {
// enforce utf-8, data loss might occur
return buf.toString();
}
},
/**
* Convert a string from specific encoding to UTF-8 Buffer
*
* @param {String|Buffer} str String to be encoded
* @param {String} [fromCharset='UTF-8'] Source encoding for the string
* @return {Buffer} UTF-8 encoded typed array
*/
convert(data, fromCharset) {
fromCharset = charset.normalizeCharset(fromCharset || 'UTF-8');
let bufString;
if (typeof data !== 'string') {
if (/^(us-)?ascii|utf-8|7bit$/i.test(fromCharset)) {
return data;
}
bufString = charset.decode(data, fromCharset);
return charset.encode(bufString);
}
return charset.encode(data);
},
/**
* Converts well known invalid character set names to proper names.
* eg. win-1257 will be converted to WINDOWS-1257
*
* @param {String} charset Charset name to convert
* @return {String} Canoninicalized charset name
*/
normalizeCharset(charset) {
charset = charset.toLowerCase().trim();
// first pass
if (charsets.hasOwnProperty(charset) && charsets[charset]) {
return charsets[charset];
}
charset = charset
.replace(/^utf[-_]?(\d+)/, 'utf-$1')
.replace(/^(?:us[-_]?)ascii/, 'windows-1252')
.replace(/^win(?:dows)?[-_]?(\d+)/, 'windows-$1')
.replace(/^(?:latin|iso[-_]?8859)?[-_]?(\d+)/, 'iso-8859-$1')
.replace(/^l[-_]?(\d+)/, 'iso-8859-$1');
// updated pass
if (charsets.hasOwnProperty(charset) && charsets[charset]) {
return charsets[charset];
}
return charset.toUpperCase();
}
});
|
/*jshint eqeqeq:true, proto:true, laxcomma:true, undef:true, node:true, expr: true*/
/* chat.io
* (c) 2012 Daniel Baulig <daniel.baulig@gmx.de>
* MIT Licensed
*/
var EventEmitter = process.EventEmitter
, channelPrefix = '#'
, userPrefix = '@'
, first = require('first');
// hack until socket.disconnect is fixed
function disconnect(socket) {
if (socket.namespace.name === '') return socket.disconnect();
socket.packet({type:'disconnect'});
socket.manager.onLeave(socket, socket.namespace.name);
socket.$emit('disconnect', 'booted');
}
function Chat(namespace, options) {
options = options || {};
this.namespace = namespace;
this.settings = {
lobby: '',
'channel join permission': true,
'handshake nickname property': 'nickname'
};
for (var o in options) {
this.settings[o] = options[o];
}
function onWhisper(target, message, ack) {
this.get('nickname', function (err, nickname) {
if (err || !nickname) return ack && ack('Internal error');
if (namespace.clients(userPrefix + target).length) {
namespace.to(userPrefix + target).emit('whisper', nickname, message);
} else ack && ack('Unknown user');
});
}
var chat = this;
function onSay(message) {
var socket = this;
first(function () {
socket.get('nickname', this);
}).whilst(function () {
socket.get('channel', this);
}).then(function (nick, chan) {
if (nick[0] || chan[0] || !nick[1]) return;
namespace.to(channelPrefix + chan[1]).emit('say', nick[1], message);
});
}
function onChannelJoin(channel, ack) {
var socket = this;
if (!chat.settings['channel join permission']) return ack && ack('Not permitted');
if (chat.settings.lobby === channel) return ack && ack('Can\'t join lobby, please leave room instead');
first(function () {
socket.get('nickname', this);
}).whilst(function () {
socket.get('channel', this);
}).then(function (nick, chan) {
var errnick = nick[0]
, nickname = nick[1]
, errchannel = chan[0]
, oldchannel = chan[1];
if (errnick || errchannel || !nickname) return ack && ack('Internal error');
function onJoinAllow(allow) {
if (!allow) return ack && ack('Not permitted');
if (null !== oldchannel) {
socket.leave(channelPrefix + oldchannel);
if (oldchannel !== chat.settings.lobby)
socket.broadcast.to(channelPrefix + oldchannel).emit('leave', nickname);
}
socket.join(channelPrefix + channel);
socket.set('channel', channel, function (err) {
if (ack) ack(err && 'Can\'t change channel');
if (err) {
socket.log.warn('error joining', channel, 'with', err, 'for client', socket.id);
onLeave.call(socket);
} else socket.broadcast.to(channelPrefix + channel).emit('join', nickname);
});
}
if ('function' === typeof chat.settings['channel join permission']) {
chat.settings['channel join permission'](nickname, channel, onJoinAllow);
} else {
onJoinAllow.call(undefined, true);
}
});
}
function onLeave(ack) {
var socket = this;
first(function () {
socket.get('nickname', this);
}).whilst(function () {
socket.get('channel', this);
}).then(function (nick, chan) {
var errnick = nick[0]
, nickname = nick[1]
, errchannel = chan[0]
, channel = chan[1];
if (errnick || errchannel || !nickname) return ack && ack('Internal error');
if (chat.lobby !== channel) {
socket.leave(channelPrefix + channel);
socket.broadcast.to(channelPrefix + channel).emit('leave', nickname);
}
socket.join(channelPrefix + chat.settings.lobby);
socket.set('channel', chat.settings.lobby, function (err) {
if (ack) ack(err && 'Can\'t join lobby');
if (err) {
socket.log.warn('error joining lobby with', err, 'for client', socket.id);
// state of this connection is not healthy anymore
disconnect(socket);
}
});
});
}
namespace.on('connection', function (socket) {
var nickname = socket.handshake[chat.settings['handshake nickname property']];
// we cannot handle clients without nicknames
if (!nickname) {
socket.log.warn('no nickname given for client', socket.id);
return disconnect(socket);
}
socket.join(userPrefix + nickname);
socket.on('whisper', onWhisper);
socket.on('say', onSay);
socket.on('join', onChannelJoin);
socket.on('leave', onLeave);
socket.set('nickname', nickname, function (err) {
if (err) {
socket.send('Can\'t set nickname');
socket.log.warn('error setting nickname', nickname, 'with', err, 'for client', socket.id);
disconnect(socket);
return;
} else {
// join lobby
onLeave.call(socket, function (err) {
if (err) {
return;
}
chat.emit('connection', nickname);
});
}
});
});
}
Chat.createChat = function (sio, options) {
return new Chat(sio, options);
};
Chat.prototype.__proto__ = EventEmitter.prototype;
Chat.prototype.kick = function (nickname) {
this.user(nickname).forEach(function (v) {
disconnect(v);
});
return this;
};
Chat.prototype.sendChannel = function (channel, message) {
this.namespace.to(channelPrefix+channel).send(message);
return this;
};
Chat.prototype.sendSystem = function (message) {
this.namespace.send(message);
return this;
};
Chat.prototype.sendUser = function (nickname, message) {
this.namespace.to(userPrefix + nickname).send(message);
return this;
};
Chat.prototype.user = function (nickname) {
return this.namespace.clients(userPrefix + nickname);
};
Chat.prototype.channel = function (channel) {
return this.namespace.clients(channelPrefix + channel);
};
Chat.prototype.set = function (key, value) {
this.namespace.settings[key] = value;
return this;
};
Chat.prototype.get = function (key) {
return this.namespace.settings[key];
};
module.exports = Chat;
|
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery', 'jquery-ui'], factory);
} else {
factory(jQuery);
}
}(function ($) {
$("<span>" + $.trim("foo") + "</span>"); // OK
}));
|
var rewritePattern = require("regexpu/rewrite-pattern");
var _ = require("lodash");
exports.Literal = function (node) {
var regex = node.regex;
if (!regex) return;
var flags = regex.flags.split("");
if (regex.flags.indexOf("u") < 0) return;
_.pull(flags, "u");
regex.pattern = rewritePattern(regex.pattern, regex.flags);
regex.flags = flags.join("");
};
|
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
linkTo(url) {
window.open(url);
},
transitionTo(routeName) {
const nameParts = routeName.split('-');
const [ one, two, three ] = nameParts;
const oneCapitalized = Ember.String.capitalize(one);
this.transitionTo(routeName);
this.controller.set('pageTitle', `${oneCapitalized}s ${two} ${three}s`);
},
},
});
|
import {deleteActivity} from '@webex/redux-module-conversation';
export const UPDATE_WIDGET_STATE = 'widget-message/UPDATE_WIDGET_STATE';
export const SET_SCROLL_POSITION = 'widget-message/SET_SCROLL_POSITION';
export const RESET_WIDGET_STATE = 'widget-message/RESET_WIDGET_STATE';
export function updateWidgetState(state) {
return {
type: UPDATE_WIDGET_STATE,
payload: {
state
}
};
}
export function setScrollPosition(scrollPosition) {
return {
type: SET_SCROLL_POSITION,
payload: {
scrollPosition
}
};
}
export function resetWidgetState() {
return {
type: RESET_WIDGET_STATE
};
}
export function showScrollToBottomButton(isVisible) {
return (dispatch) => {
dispatch(updateWidgetState({
showScrollToBottomButton: isVisible
}));
};
}
/**
* Sets if the widget has been scrolled up from the bottom
*
* @export
* @param {boolean} isScrolledUp
* @returns {Thunk}
*/
export function setScrolledUp(isScrolledUp) {
return (dispatch, getState) => {
const {widgetMessage} = getState();
// Since we are triggering this every scroll, let's not attack
// our store if we don't need to
if (!isScrolledUp) {
/* eslint-disable operator-linebreak */
if (
widgetMessage.get('hasNewMessage') ||
widgetMessage.get('hasScrolledUp') ||
widgetMessage.get('showScrollToBottomButton')
) {
dispatch(updateWidgetState({
hasNewMessage: false,
hasScrolledUp: false,
showScrollToBottomButton: false
}));
}
}
/* eslint-disable operator-linebreak */
else if (
!widgetMessage.get('hasScrolledUp') ||
!widgetMessage.get('showScrollToBottomButton')
) {
dispatch(updateWidgetState({
hasScrolledUp: true,
showScrollToBottomButton: true
}));
}
};
}
export function updateHasNewMessage(hasNew) {
return (dispatch) => {
dispatch(updateWidgetState({
hasNewMessage: hasNew
}));
};
}
export function confirmDeleteActivity(activityId) {
return (dispatch) => {
dispatch(updateWidgetState({
deletingActivityId: activityId,
showAlertModal: true
}));
};
}
export function hideDeleteModal() {
return (dispatch) => {
dispatch(updateWidgetState({
deletingActivityId: null,
showAlertModal: false
}));
};
}
export function deleteActivityAndDismiss(conversation, activity, spark) {
return (dispatch) => {
dispatch(deleteActivity(conversation, activity, spark))
.then(() => {
dispatch(hideDeleteModal());
});
};
}
|
const electron = require('electron');
const contextMenu = require('electron-context-menu');
const fs = require('fs');
const os = require('os');
const path = require('path');
const url = require('url');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
contextMenu();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function isDev() {
return process.env.ELECTRON_ENV === 'development';
}
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1000,
height: 600,
minWidth: 1000,
minHeight: 600,
titleBarStyle: 'hidden-inset',
webPreferences: {
webSecurity: false
}
});
// TODO Clean this
let appUrl;
if (isDev()) {
appUrl = 'http://localhost:3000';
} else {
appUrl = url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
});
}
// and load the index.html of the app.
mainWindow.loadURL(appUrl);
// Add React DevTools extension
if (isDev()) {
const extDir = path.join(
os.homedir(),
'Library/Application Support/Google/Chrome/Default/Extensions/fmkadmapgofadopljbjfkapdkoienihi'
);
const version = fs.readdirSync(extDir).shift();
BrowserWindow.addDevToolsExtension(path.join(extDir, version));
}
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
|
var frontdoor = require("../../frontdoor");
var errors = require("http-error");
module.exports = function() {
var api = frontdoor("TODO app");
var todo = new Todo();
todo.add({description: "get a hair cut"}, function() {});
todo.add({description: "buy milk"}, function() {});
todo.update({id: 1, done: true}, function() {});
api.section("todo")
.get("/", todo.list.bind(todo))
.put(
"/",
{
params: {
description: {
type: "string",
source: "body",
},
},
},
todo.add.bind(todo)
)
.post(
"/:id",
{
params: {
id: "int",
done: {
type: "boolean",
source: "body",
optional: true,
},
description: {
type: "string",
source: "body",
optional: true,
},
},
},
todo.update.bind(todo)
)
.delete(
"/:id",
{
params: {id: "int"},
},
todo.remove.bind(todo)
);
api.get("/inspect.json", frontdoor.middleware.describeApi(api));
return api;
};
function Todo() {
this.items = {};
this._id = 1;
}
Todo.prototype.list = function(params, callback) {
var res = {items: []};
for (var id in this.items) res.items.push(this.items[id]);
callback(null, res);
};
Todo.prototype.add = function(params, callback) {
var id = this._id++;
this.items[id] = {
id: id,
done: false,
description: params.description,
};
callback(null, {id: params.id});
};
Todo.prototype.update = function(params, callback) {
var item = this.items[params.id];
if (!item)
return callback(new errors.NotFound("No such entry " + params.id));
if ("done" in params) item.done = params.done;
if ("description" in params) item.description = params.description;
callback(null, {id: params.id});
};
Todo.prototype.remove = function(params, callback) {
var item = this.items[params.id];
if (!item)
return callback(new errors.NotFound("No such entry " + params.id));
delete this.items[params.id];
callback(null, {id: params.id});
};
|
exports.jsonrpc2 = require('./jsonrpc2');
exports.xmlrpc = require('./xmlrpc');
if(process.title !== 'browser') {
//@browserify-ignore
exports.node_xmlrpc = require('./node-xmlrpc');
//@browserify-ignore
exports.mainline = require('./mainline');
}
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* An Impact.js compatible physics world, body and solver, for those who are used
* to the Impact way of defining and controlling physics bodies. Also works with
* the new Loader support for Weltmeister map data.
*
* World updated to run off the Phaser main loop.
* Body extended to support additional setter functions.
*
* To create the map data you'll need Weltmeister, which comes with Impact
* and can be purchased from http://impactjs.com
*
* My thanks to Dominic Szablewski for his permission to support Impact in Phaser.
*
* @namespace Phaser.Physics.Impact
*/
module.exports = {
Body: require('./Body'),
COLLIDES: require('./COLLIDES'),
CollisionMap: require('./CollisionMap'),
Factory: require('./Factory'),
Image: require('./ImpactImage'),
ImpactBody: require('./ImpactBody'),
ImpactPhysics: require('./ImpactPhysics'),
Sprite: require('./ImpactSprite'),
TYPE: require('./TYPE'),
World: require('./World')
};
|
//browserify client/app.js -o public/bundle.js
//jquery items
|
#!/usr/bin/env node
/**
* DNSServer service, 19.11.2014 Spaceify Inc.
*
*/
var Config = require("./config")();
var DNSServer = require("./dnsserver");
var url2ip = {};
url2ip[Config.EDGE_HOSTNAME] = {ip: Config.EDGE_IP, ttl: 0};
var dnsserver = new DNSServer();
dnsserver.connect({ port: Config.DNS_PORT, // The port and address to listen
v4_address: Config.EDGE_IP,
v6_address: null,//Config.EDGE_IP_V6
url2ip: url2ip, // Redirects URLs to IPs
default_ip: Config.EDGE_IP, // If DNS fails return the default URL and address
default_hostname: Config.EDGE_HOSTNAME,
external_dns: "8.8.8.8", // For making DNS questions from external server, use local IP if local resolv.conf adress(es) is used
ttl: 600, // Time To Live period the clients should cache the returned answers,
subnet: Config.EDGE_SUBNET //
});
|
'use strict';
var _ = require('underscore');
var sanitise = {
booleanParameter: function(variable){
if(_.isString(variable)){
if(variable === 'true'){
return true;
} else if(variable === 'false'){
return false;
}
}
return variable;
},
numberParameter: function(variable){
return variable*1;
},
parameter: function(variable, type){
if(type === 'boolean'){
return sanitise.booleanParameter(variable);
} else if(type === 'number'){
return sanitise.numberParameter(variable);
}
return variable;
}
};
module.exports = {
sanitiseComponentParameters: function(requestParameters, expectedParameters){
var result = {};
_.forEach(requestParameters, function(requestParameter, requestParameterName){
if(_.has(expectedParameters, requestParameterName)){
var expectedType = expectedParameters[requestParameterName].type,
sanitised = sanitise.parameter(requestParameter, expectedType);
result[requestParameterName] = sanitised;
} else {
result[requestParameterName] = requestParameter;
}
}, this);
return result;
}
};
|
require('bootstrap/dist/css/bootstrap.css');
require('bootstrap/dist/js/bootstrap');
require('font-awesome/css/font-awesome.css');
require('../stylesheets/base.css');
|
version https://git-lfs.github.com/spec/v1
oid sha256:a85ddc891dc23e6e052493b7db06ff6276560aaf40148ecbeab01b14c048d990
size 9646
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from '../utils/griddleConnect';
import getContext from 'recompose/getContext';
import mapProps from 'recompose/mapProps';
import compose from 'recompose/compose';
import {
customComponentSelector,
cellValueSelector,
cellPropertiesSelectorFactory,
classNamesForComponentSelector,
stylesForComponentSelector
} from '../selectors/dataSelectors';
import { valueOrResult } from '../utils/valueUtils';
function hasWidthOrStyles(cellProperties) {
return cellProperties.hasOwnProperty('width') || cellProperties.hasOwnProperty('styles');
}
function getCellStyles(cellProperties, originalStyles) {
if (!hasWidthOrStyles(cellProperties)) { return originalStyles; }
let styles = originalStyles;
// we want to take griddle style object styles, cell specific styles
if (cellProperties.hasOwnProperty('style')) {
styles = Object.assign({}, styles, originalStyles, cellProperties.style);
}
if (cellProperties.hasOwnProperty('width')) {
styles = Object.assign({}, styles, { width: cellProperties.width });
}
return styles;
}
const mapStateToProps = () => {
const cellPropertiesSelector = cellPropertiesSelectorFactory();
return (state, props) => {
return {
value: cellValueSelector(state, props),
customComponent: customComponentSelector(state, props),
cellProperties: cellPropertiesSelector(state, props),
className: classNamesForComponentSelector(state, 'Cell'),
style: stylesForComponentSelector(state, 'Cell'),
};
};
}
const ComposedCellContainer = OriginalComponent => compose(
connect(mapStateToProps),
mapProps(props => {
return ({
...props.cellProperties.extraData,
...props,
className: valueOrResult(props.cellProperties.cssClassName, props) || props.className,
style: getCellStyles(props.cellProperties, props.style),
value: props.customComponent ?
<props.customComponent {...props.cellProperties.extraData} {...props} /> :
props.value
})}),
)(props =>
<OriginalComponent
{...props}
/>
);
export default ComposedCellContainer;
|
var mage = require('../../../mage');
var logger = mage.core.logger.context('archivist');
function executeOperation(archivist, change) {
switch (change.operation) {
case 'add':
archivist.add(change.topic, change.index, change.data,
change.mediaType, change.encoding, change.expirationTime);
break;
case 'set':
archivist.set(change.topic, change.index, change.data,
change.mediaType, change.encoding, change.expirationTime);
break;
case 'touch':
archivist.touch(change.topic, change.index, change.expirationTime);
break;
case 'del':
archivist.del(change.topic, change.index);
break;
}
}
exports.acl = ['*'];
exports.execute = function (state, changes, cb) {
if (!Array.isArray(changes)) {
return state.error(null, 'archivist.distribute expected an array of changes', cb);
}
var issues = [];
var i, change;
var toLoad = [];
var diffs = [];
// to apply diffs, we need to load their values first
// for other operations, execute them synchronously
for (i = 0; i < changes.length; i++) {
change = changes[i] || {};
if (change.diff) {
// we need to load the document before we can apply the diff
if (Array.isArray(change.diff) && change.diff.length > 0) {
toLoad.push({ topic: change.topic, index: change.index });
diffs.push(change.diff);
}
} else {
// execute a synchronous change
try {
executeOperation(state.archivist, change);
} catch (error) {
logger.error('Error during archivist operation:', error);
issues.push({
topic: change.topic,
index: change.index,
operation: change.operation,
error: error.message
});
}
}
}
// if there is nothing to do asynchronously, bail out now
if (toLoad.length === 0) {
state.respond(issues);
return cb();
}
// load all required values, so we can apply diffs on them
state.archivist.mgetValues(toLoad, { optional: true }, function (error, values) {
if (error) {
return cb(error);
}
for (var i = 0; i < values.length; i++) {
var value = values[i];
var diff = diffs[i];
if (!value) {
logger.error('Could not load value for diff on:', toLoad[i]);
issues.push({
topic: value.topic,
index: value.index,
operation: 'diff',
error: 'Value not found'
});
continue;
}
try {
value.applyDiff(diff);
} catch (err) {
logger.error('Error during VaultValue#applyDiff:', err);
issues.push({
topic: value.topic,
index: value.index,
operation: 'diff',
error: err.message
});
}
}
state.respond(issues);
cb();
});
};
|
var mutators = {
cmd: {
parent: true,
options: false,
commands: false,
sections: true,
names: false,
key: true,
name: true,
extra: true,
options: true,
commands: true,
last: true
},
arg: {
names: false,
key: true,
name: true,
optional: true,
multiple: true,
value: true,
converter: true,
extra: true,
converter: true,
action: true
},
prg: {
converter: true,
configure: true,
}
}
module.exports = mutators;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.