<commit_before>/*
The MIT License (MIT)

Copyright (c) 2016 mourip

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function puti_write(normal_drink,normal_drink_dif,half_drink,half_drink_dif)
{
  var DD = new Date();
  var Year = DD.getYear()+1900;
  var Month = DD.getMonth() + 1;
  var Day = DD.getDate();
  var Hours = DD.getHours();
  var Minutes = DD.getMinutes();
  var Seconds = DD.getSeconds();
  var date = new Array(Year,Month,Day,Hours,Minutes,Seconds);
  var dates=date.join("/");
  // console.log(dates);
  var utf8normal = unescape(encodeURIComponent(normal_drink));
  var utf8normal_dif = unescape(encodeURIComponent(normal_drink_dif));
  var utf8half=unescape(encodeURIComponent(half_drink));
  var utf8half_dif=unescape(encodeURIComponent(half_drink_dif));

  // PRESISTENTで勝手に削除されないようにする
  webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

    fileSystem.root.getFile("event_items/puti.txt", {'create':true}, function(fileEntry){
      fileEntry.createWriter(function(fileWriter){

        //  ファイルの書き込み位置は、一番最後とする
        fileWriter.seek(fileWriter.length);
        //  出力行
        var lines = '';

        //  0バイトファイルの場合、ヘッダ行を作成する
        if (fileWriter.length == 0)
        {
          var headers = new Array("time","normal_drink","normal_dif","half_drink","half_dif");
          lines = headers.join(",") + "\n";

        }

        //  データ行の作成

       var details = new Array(dates,utf8normal,utf8normal_dif,utf8half,utf8half_dif);
       lines += details.join(",") + "\n";
       var blob = new Blob([lines],{type: 'text/plain'});

        fileWriter.write(blob);

        fileWriter.onwriteend = function(e) {
          console.log('Write completed.');
        };

        fileWriter.onerror = function(e) {
          console.log('Write failed: ' + e.toString());
        };

      });
    });
  });
}

function puti_checker(normal_drink,half_drink)
{
  navigator.webkitPersistentStorage.requestQuota(1024*1024*10, function(bytes)
   {
         window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs)
          {
           // ファイル取得
           fs.root.getFile("event_items/puti.txt", {create: true}, function(fileEntry)
          {
             fileEntry.file(function(file)
              {
                  var reader = new FileReader();
                  reader.onloadend = function(e)
                  {
                    data = e.target.result;
                    // console.log(data);
                    if(!data)
                    {
                      console.log("白紙なので、作成します");
                      puti_write(normal_drink,0,half_drink,0);

                    }
                    else if(data)
                    {
                      var array_temp=data.split("\n");
                      // console.log(array_temp);
                      // var last_time=array_temp[array_temp.length-2].split(",")[0];
                      var last_normal_drink=array_temp[array_temp.length-2].split(",")[1];
                      var last_half_drink=array_temp[array_temp.length-2].split(",")[3];
                      // console.log(last_item_num+","+last_half_drink);

                      //ここからアップデートが必要かを判断する関数に飛ばす
                      // console.log(last_time);
                      // var flag=update_checker(last_time);
                      if(String(last_normal_drink)!=String(normal_drink) || String(last_half_drink)!=String(half_drink))
                      {
                        console.log("更新します");
                        puti_write(normal_drink,Number(normal_drink)-Number(last_normal_drink),half_drink,Number(half_drink)-Number(last_half_drink));
                      }
                      else
                      {
                        console.log("更新しない");
                      }
                    }
                  };
                  reader.readAsText(file);
              });
          });
    });
  });
}

function pt_checker_puti(pt)
{
  navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
      window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
          fs.root.getDirectory("event_pt", {
                  create: true
              },
              function(dirEntry) {
                  var text = "ディレクトリパス：" + dirEntry.fullPath;
                  console.log(text);
                  //text += "ディレクトリ名："+dirEntry.name+"
";
                  //document.getElementById("result").innerHTML = text;
              },
              function(err) { // 失敗時のコールバック関数
                  console.log(err);
              });
      });
  });

  navigator.webkitPersistentStorage.requestQuota(1024*1024*10, function(bytes)
   {
         window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs)
          {
           // ファイル取得
           fs.root.getFile("event_pt/puti.txt", {create: true}, function(fileEntry)
          {
             fileEntry.file(function(file)
              {
                  var reader = new FileReader();
                  reader.onloadend = function(e)
                  {
                    data = e.target.result;
                    // console.log(data);
                    if(!data)
                    {
                      console.log("白紙なので、作成します");
                      puti_write(normal_drink,0,half_drink,0);

                    }
                    else if(data)
                    {
                      var array_temp=data.split("\n");
                      // console.log(array_temp);
                      // var last_time=array_temp[array_temp.length-2].split(",")[0];
                      var last_normal_drink=array_temp[array_temp.length-2].split(",")[1];
                      var last_half_drink=array_temp[array_temp.length-2].split(",")[3];
                      // console.log(last_item_num+","+last_half_drink);

                      //ここからアップデートが必要かを判断する関数に飛ばす
                      // console.log(last_time);
                      // var flag=update_checker(last_time);
                      if(String(last_normal_drink)!=String(normal_drink) || String(last_half_drink)!=String(half_drink))
                      {
                        console.log("更新します");
                        puti_write(normal_drink,Number(normal_drink)-Number(last_normal_drink),half_drink,Number(half_drink)-Number(last_half_drink));
                      }
                      else
                      {
                        console.log("更新しない");
                      }
                    }
                  };
                  reader.readAsText(file);
              });
          });
    });
  });
}

function puti_log()
{
  var puti_check=document.querySelector("#top > div.m-Top10 > a > div > span");

  if(!puti_check)
  {
    console.log("プチトップページじゃないですね");
  }
  // console.log(puti_check.innerText);
  else if(puti_check.innerText=="ぷちデレラコレクション演出設定")
  {
    //このときはプチコレのページである
    //よってアイテムを記録することができる
    var normal_drink=document.querySelector("#event_main_graphic > div.event_items > div:nth-child(1)");
    var normal_drink_num=normal_drink.innerText.substr(1);
    console.log(normal_drink_num);

    var half_drink=document.querySelector("#event_main_graphic > div.event_items > div:nth-child(2)");
    var half_drink_num=half_drink.innerText.substr(1);
    console.log(half_drink_num);
    puti_checker(normal_drink_num,half_drink_num);
    var pt_selector=document.querySelector("#top > section:nth-child(25) > div.area_tab_2 > section > ul:nth-child(2) > li:nth-child(2)");
    //,区切りが嫌であるのでなんとかして変更する
    var pt_str=pt_selector.innerText.split(":")[1].split(" ")[1];
    var pt_array=pt_str.split(",");
    var pt="";
    for(var i=0;i<pt_array.length;i++)
    {
      pt+=String(pt_array[i]);
    }
    console.log(pt);
    // pt_checker_puti(pt);
  }
}

function delete_files_puti() {
  // PRESISTENTで勝手に削除されないようにする
  var txt_name="puti.txt";
  webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

    fileSystem.root.getFile(txt_name, {'create':false}, function(fileEntry){
      fileEntry.remove(function() {
      console.log('File removed.');
    });
  });
});
}

function write_copy_puti(data) {
    console.log(data);
    var txt_name = "event_items/puti.txt";
    // PRESISTENTで勝手に削除されないようにする
    webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

      fileSystem.root.getFile(txt_name, {'create':true}, function(fileEntry){
        fileEntry.createWriter(function(fileWriter){

          //  出力行
          var lines = data;
          //  データ行の作成
         var blob = new Blob([lines],{type: 'text/plain'});

          fileWriter.write(blob);
          fileWriter.onwriteend = function(e) {
            console.log('puti:copy completed.');
          };
          fileWriter.onerror = function(e) {
            console.log('puti:copy failed: ' + e.toString());
          };

        });
      });
    });

    delete_files_puti();
}

function copy_data_read_puti() {
    //var txt_name = "puti.txt";
    navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
      //  var txt_t = txt;
        window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
            // var txt_name1 = txt_t;
            // ファイル取得
            fs.root.getFile("puti.txt", {
                    create: false
                },
                function(fileEntry) {
                    // var txt_name2 = txt_name1;
                    fileEntry.file(function(file) {
                        var reader = new FileReader();
                        reader.onloadend = function(e) {
                            data = e.target.result;
                            console.log(data);
                            // console.log(String(txt_name2));
                            write_copy_puti(data);
                            // delete_files(txt_name2);

                        };
                        reader.readAsText(file);
                    });
                },
                function(err) {
                    // console.log(err);
                });
        });
    });

}

function directry_root_puti() {

    navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
        window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
            fs.root.getDirectory("event_items", {
                    create: true
                },
                function(dirEntry) {
                    var text = "ディレクトリパス：" + dirEntry.fullPath;
                    console.log(text);
                    //text += "ディレクトリ名："+dirEntry.name+"
";
                    //document.getElementById("result").innerHTML = text;
                },
                function(err) { // 失敗時のコールバック関数
                    console.log(err);
                });
        });
    });
    copy_data_read_puti();

}

directry_root_puti();
puti_log();
<commit_msg>event_item_puti.jsのdirectry_root（）をコメントアウト<commit_after>/*
The MIT License (MIT)

Copyright (c) 2016 mourip

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function puti_write(normal_drink,normal_drink_dif,half_drink,half_drink_dif)
{
  var DD = new Date();
  var Year = DD.getYear()+1900;
  var Month = DD.getMonth() + 1;
  var Day = DD.getDate();
  var Hours = DD.getHours();
  var Minutes = DD.getMinutes();
  var Seconds = DD.getSeconds();
  var date = new Array(Year,Month,Day,Hours,Minutes,Seconds);
  var dates=date.join("/");
  // console.log(dates);
  var utf8normal = unescape(encodeURIComponent(normal_drink));
  var utf8normal_dif = unescape(encodeURIComponent(normal_drink_dif));
  var utf8half=unescape(encodeURIComponent(half_drink));
  var utf8half_dif=unescape(encodeURIComponent(half_drink_dif));

  // PRESISTENTで勝手に削除されないようにする
  webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

    fileSystem.root.getFile("event_items/puti.txt", {'create':true}, function(fileEntry){
      fileEntry.createWriter(function(fileWriter){

        //  ファイルの書き込み位置は、一番最後とする
        fileWriter.seek(fileWriter.length);
        //  出力行
        var lines = '';

        //  0バイトファイルの場合、ヘッダ行を作成する
        if (fileWriter.length == 0)
        {
          var headers = new Array("time","normal_drink","normal_dif","half_drink","half_dif");
          lines = headers.join(",") + "\n";

        }

        //  データ行の作成

       var details = new Array(dates,utf8normal,utf8normal_dif,utf8half,utf8half_dif);
       lines += details.join(",") + "\n";
       var blob = new Blob([lines],{type: 'text/plain'});

        fileWriter.write(blob);

        fileWriter.onwriteend = function(e) {
          console.log('Write completed.');
        };

        fileWriter.onerror = function(e) {
          console.log('Write failed: ' + e.toString());
        };

      });
    });
  });
}

function puti_checker(normal_drink,half_drink)
{
  navigator.webkitPersistentStorage.requestQuota(1024*1024*10, function(bytes)
   {
         window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs)
          {
           // ファイル取得
           fs.root.getFile("event_items/puti.txt", {create: true}, function(fileEntry)
          {
             fileEntry.file(function(file)
              {
                  var reader = new FileReader();
                  reader.onloadend = function(e)
                  {
                    data = e.target.result;
                    // console.log(data);
                    if(!data)
                    {
                      console.log("白紙なので、作成します");
                      puti_write(normal_drink,0,half_drink,0);

                    }
                    else if(data)
                    {
                      var array_temp=data.split("\n");
                      // console.log(array_temp);
                      // var last_time=array_temp[array_temp.length-2].split(",")[0];
                      var last_normal_drink=array_temp[array_temp.length-2].split(",")[1];
                      var last_half_drink=array_temp[array_temp.length-2].split(",")[3];
                      // console.log(last_item_num+","+last_half_drink);

                      //ここからアップデートが必要かを判断する関数に飛ばす
                      // console.log(last_time);
                      // var flag=update_checker(last_time);
                      if(String(last_normal_drink)!=String(normal_drink) || String(last_half_drink)!=String(half_drink))
                      {
                        console.log("更新します");
                        puti_write(normal_drink,Number(normal_drink)-Number(last_normal_drink),half_drink,Number(half_drink)-Number(last_half_drink));
                      }
                      else
                      {
                        console.log("更新しない");
                      }
                    }
                  };
                  reader.readAsText(file);
              });
          });
    });
  });
}

function pt_checker_puti(pt)
{
  navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
      window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
          fs.root.getDirectory("event_pt", {
                  create: true
              },
              function(dirEntry) {
                  var text = "ディレクトリパス：" + dirEntry.fullPath;
                  console.log(text);
                  //text += "ディレクトリ名："+dirEntry.name+"
";
                  //document.getElementById("result").innerHTML = text;
              },
              function(err) { // 失敗時のコールバック関数
                  console.log(err);
              });
      });
  });

  navigator.webkitPersistentStorage.requestQuota(1024*1024*10, function(bytes)
   {
         window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs)
          {
           // ファイル取得
           fs.root.getFile("event_pt/puti.txt", {create: true}, function(fileEntry)
          {
             fileEntry.file(function(file)
              {
                  var reader = new FileReader();
                  reader.onloadend = function(e)
                  {
                    data = e.target.result;
                    // console.log(data);
                    if(!data)
                    {
                      console.log("白紙なので、作成します");
                      puti_write(normal_drink,0,half_drink,0);

                    }
                    else if(data)
                    {
                      var array_temp=data.split("\n");
                      // console.log(array_temp);
                      // var last_time=array_temp[array_temp.length-2].split(",")[0];
                      var last_normal_drink=array_temp[array_temp.length-2].split(",")[1];
                      var last_half_drink=array_temp[array_temp.length-2].split(",")[3];
                      // console.log(last_item_num+","+last_half_drink);

                      //ここからアップデートが必要かを判断する関数に飛ばす
                      // console.log(last_time);
                      // var flag=update_checker(last_time);
                      if(String(last_normal_drink)!=String(normal_drink) || String(last_half_drink)!=String(half_drink))
                      {
                        console.log("更新します");
                        puti_write(normal_drink,Number(normal_drink)-Number(last_normal_drink),half_drink,Number(half_drink)-Number(last_half_drink));
                      }
                      else
                      {
                        console.log("更新しない");
                      }
                    }
                  };
                  reader.readAsText(file);
              });
          });
    });
  });
}

function puti_log()
{
  var puti_check=document.querySelector("#top > div.m-Top10 > a > div > span");

  if(!puti_check)
  {
    console.log("プチトップページじゃないですね");
  }
  // console.log(puti_check.innerText);
  else if(puti_check.innerText=="ぷちデレラコレクション演出設定")
  {
    //このときはプチコレのページである
    //よってアイテムを記録することができる
    var normal_drink=document.querySelector("#event_main_graphic > div.event_items > div:nth-child(1)");
    var normal_drink_num=normal_drink.innerText.substr(1);
    console.log(normal_drink_num);

    var half_drink=document.querySelector("#event_main_graphic > div.event_items > div:nth-child(2)");
    var half_drink_num=half_drink.innerText.substr(1);
    console.log(half_drink_num);
    puti_checker(normal_drink_num,half_drink_num);
    var pt_selector=document.querySelector("#top > section:nth-child(25) > div.area_tab_2 > section > ul:nth-child(2) > li:nth-child(2)");
    //,区切りが嫌であるのでなんとかして変更する
    var pt_str=pt_selector.innerText.split(":")[1].split(" ")[1];
    var pt_array=pt_str.split(",");
    var pt="";
    for(var i=0;i<pt_array.length;i++)
    {
      pt+=String(pt_array[i]);
    }
    console.log(pt);
    // pt_checker_puti(pt);
  }
}

function delete_files_puti() {
  // PRESISTENTで勝手に削除されないようにする
  var txt_name="puti.txt";
  webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

    fileSystem.root.getFile(txt_name, {'create':false}, function(fileEntry){
      fileEntry.remove(function() {
      console.log('File removed.');
    });
  });
});
}

function write_copy_puti(data) {
    console.log(data);
    var txt_name = "event_items/puti.txt";
    // PRESISTENTで勝手に削除されないようにする
    webkitRequestFileSystem(PERSISTENT, 1024*1024*10, function(fileSystem){

      fileSystem.root.getFile(txt_name, {'create':true}, function(fileEntry){
        fileEntry.createWriter(function(fileWriter){

          //  出力行
          var lines = data;
          //  データ行の作成
         var blob = new Blob([lines],{type: 'text/plain'});

          fileWriter.write(blob);
          fileWriter.onwriteend = function(e) {
            console.log('puti:copy completed.');
          };
          fileWriter.onerror = function(e) {
            console.log('puti:copy failed: ' + e.toString());
          };

        });
      });
    });

    delete_files_puti();
}

function copy_data_read_puti() {
    //var txt_name = "puti.txt";
    navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
      //  var txt_t = txt;
        window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
            // var txt_name1 = txt_t;
            // ファイル取得
            fs.root.getFile("puti.txt", {
                    create: false
                },
                function(fileEntry) {
                    // var txt_name2 = txt_name1;
                    fileEntry.file(function(file) {
                        var reader = new FileReader();
                        reader.onloadend = function(e) {
                            data = e.target.result;
                            console.log(data);
                            // console.log(String(txt_name2));
                            write_copy_puti(data);
                            // delete_files(txt_name2);

                        };
                        reader.readAsText(file);
                    });
                },
                function(err) {
                    // console.log(err);
                });
        });
    });

}

function directry_root_puti() {

    navigator.webkitPersistentStorage.requestQuota(1024 * 1024 * 5, function(bytes) {
        window.webkitRequestFileSystem(window.PERSISTENT, bytes, function(fs) {
            fs.root.getDirectory("event_items", {
                    create: true
                },
                function(dirEntry) {
                    var text = "ディレクトリパス：" + dirEntry.fullPath;
                    console.log(text);
                    //text += "ディレクトリ名："+dirEntry.name+"
";
                    //document.getElementById("result").innerHTML = text;
                },
                function(err) { // 失敗時のコールバック関数
                    console.log(err);
                });
        });
    });
    copy_data_read_puti();

}

// directry_root_puti();
puti_log();
<|endoftext|>


<commit_before>$( function () {

	$.ajax( {
		type: "GET",
		url: "/messages/feed?offset=&limit=&sort_by=&sort_order=dsc"

	} ).done( function ( result ) {

		var html = "";

		_.each( result.data, function(d) {

			html += '
';

				html += '
' + d.message;
					html += '' + d.date_created + '';
				html += '
';

				html += '
' + d.place_tag + ", " + d.sender + '
';

				html += '

';

        	html += '
';

		});

        $( "#msg" ).append( html );
        $( ".timestamp" ).prettyDate();

	});

	setInterval( function() {
      $( ".timestamp" ).prettyDate();
    }, 10000);

    $( ".timestamp" ).prettyDate();

});<commit_msg>script updates<commit_after>$( function () {

	$.ajax( {
		type: "GET",
		url: "/messages/feed?offset=&limit=&sort_by=&sort_order=dsc"

	} ).done( function ( result ) {

		var html = "";
		var d = "";

		for ( var i = 0; i < result_count; i++ ) {

			d = result.data[ i ];

			html += '
';

				html += '
' + d.message;
					html += '' + d.date_created + '';
				html += '
';

				html += '
' + d.place_tag + ", " + d.sender + '
';

				html += '

';

        	html += '
';

		};

        $( "#msg" ).append( html );
        $( ".timestamp" ).prettyDate();

	});

	setInterval( function() {
      $( ".timestamp" ).prettyDate();
    }, 10000);

    $( ".timestamp" ).prettyDate();

});<|endoftext|>


<commit_before>$(document).ready(function(){
	particle_element = document.createElement('div');
	$(particle_element).addClass('snowflake');

	$('body').particles({
		'parent': 'div#header',
		'base_elements': [particle_element],
		'update_particle':
		{
			'top': 4,
			'left': function(ps)
			{
				return parseInt((Math.random()*5)+1);
			}
		},
		'init_particle':
		{
			'top': function()
			{
				return Math.random()*($(this).parent().height());
			},
			'left': function()
			{
				return Math.random()*($(this).parent().width());
			},
			'background': function()
			{
				return function() { return 'url(./images/snowflake_0' + String(parseInt(Math.random()*2)+1) + '.png)'; }
			}
		},
		'count': 20,
		'incrementor': $.particles.generic_incrementors.bound_by_parent
	});
});

<commit_msg>Added a pretty little fade effect to the snowflakes.<commit_after>$(document).ready(function(){
	particle_element = document.createElement('div');
	$(particle_element).addClass('snowflake').hide();

	$('body').particles({
		'parent': 'div#header',
		'base_elements': [particle_element],
		'update_particle':
		{
			'top': 4,
			'left': function(ps)
			{
				return parseInt((Math.random()*5)+1);
			}
		},
		'init_particle':
		{
			'top': function()
			{
				$(this).fadeIn(10000);

				return Math.random()*($(this).parent().height());
			},
			'left': function()
			{
				return Math.random()*($(this).parent().width());
			},
			'background': function()
			{
				return function() { return 'url(./images/snowflake_0' + String(parseInt(Math.random()*2)+1) + '.png)'; }
			}
		},
		'count': 20,
		'incrementor': $.particles.generic_incrementors.bound_by_parent
	});
});

<|endoftext|>


<commit_before>// Import nunjucks
var nunjucks = require('nunjucks');
// Import the plugin
var nunjucksDate = require('nunjucks-date');

// Define a custom default date format. Any valid format works.
// The date format defaults to "YYYY"
// http://momentjs.com/docs/#/displaying/format/
nunjucksDate.setDefaultFormat('MMMM Do YYYY, h:mm:ss a');

// Initialize your Nunjucks enironment
var env = new nunjucks.Environment();

// Pass the environment & a custom filter name
nunjucksDate.install(env, 'mySpecialDateFilter');

// Print out environment filters to ensure filter is present
console.log('Now your filter should be listed here: ', env.filters);
<commit_msg>Update example.js<commit_after>// Import nunjucks
var nunjucks = require('nunjucks');

// Import the plugin
var nunjucksDate = require('nunjucks-date');
var moment = require('moment');

// Define a custom default date format. Any valid format works.
// The date format defaults to "YYYY"
// http://momentjs.com/docs/#/displaying/format/
nunjucksDate.setDefaultFormat('MMMM Do YYYY, h:mm:ss a');

// Initialize your Nunjucks enironment
var env = new nunjucks.Environment();

// Pass the environment & a custom filter name
nunjucksDate.install(env, 'mySpecialDateFilter');

// Print out environment filters to ensure filter is present
console.log('Now your filter should be listed here: ', env.filters);

// Example Usage
var dateStringTest = '1995-12-25';
var currentDate = env.renderString(`
  Present: {{ present | mySpecialDateFilter}} & Past: {{ past }}
`, {
  present: moment(),
  past: moment(dateStringTest).fromNow()
});

console.log('currentDate', currentDate);
<|endoftext|>


<commit_before>const log = require('t-log');
const express = require('express');
const swig = require('swig'); // eslint-disable-line
const coc = require('../index');
const apiMap = require('./api-map');

const app = express();

app.engine('swig', swig.renderFile);

require('marko/node-require').install();  // eslint-disable-line
app.engine('marko', (filePath, data, callback) => {
  const template = require(filePath); // eslint-disable-line

  template.renderToString(data, callback);
});

app.use('/favicon.ico', (req, res) => res.send('ok'));

// 子目录挂载应放在全局的前面
const stageB = coc(app, {
  mount: '/b-plan',
  routerDir: `${__dirname}/routers-b`,
  ajaxCache: false
});

stageB.set('view engine', '.njk'); // can startsWith dot or not dot

const stage = coc(app, {
  interceptorDir: `${__dirname}/interceptors`,
  routerDir: `${__dirname}/routers`,
  viewDir: `${__dirname}/views`,
  handleAPI(apiUrl) {
    const apiDomain = apiMap[apiUrl] || '';

    return apiDomain + apiUrl;
  }
});

// 查看阶段列表，每个阶段都可以用before,after处理
log.info(stage.stageNames);

stage.before('pageInfo', function beforePageInfo(req, res, next) {
  req.reqCircle = log.time();
  next();
});
stage.before('initHttpRequest', function beforeInitHttpRequest(req, res, next) {
  let timeout = 5 * 1000;

  if (req.router && req.router.timeout) {
    timeout = req.router.timeout;
  }
  req.httpRequestConfig = { timeout };

  next();
});

// forward has been test
stage.after('requestProxy', function afterRequestProxy(req, res, next) {
  const pathname = req.pathname;
  log.debug('param:', req.param);
  log.debug('path:', pathname);

  if (pathname === '/forward') {
    res.forward('/proxy');
    // res.redirect('http://www.163.com');
    // res.status(200).send('hello 200 ok!');
    // next已经可以正确处理forward情况
    // 类似redirect，res.send等已经响应了服务器的情况
    next();
    return;
  }

  next();
});
stage.before('response', function beforeResponse(req, res, next) {
  const apiInfo = res.apiInfo;

  Object.keys(apiInfo).map(name => {
    const info = apiInfo[name];
    return log.info(info.method, info.api, info.consumeTime, 'ms');
  });
  log.warn('cost time: ', req.reqCircle.end());

  next();
});

app.use((req, res) => {
  res.status(404).send('404 not found!');
});

app.use((error, req, res, next) => { // eslint-disable-line
  res.status(500).send(`<pre>${error.stack}</pre>`);
});

app.listen(8080, () => {
  const startInfo = 'server run at http://localhost:8080';

  log.info(startInfo);
});

module.exports = app;
<commit_msg>update stage.engine marko<commit_after>const log = require('t-log');
const express = require('express');
const swig = require('swig'); // eslint-disable-line
const coc = require('../index');
const apiMap = require('./api-map');

const app = express();

app.engine('swig', swig.renderFile);

app.use('/favicon.ico', (req, res) => res.send('ok'));

// 子目录挂载应放在全局的前面
const stageB = coc(app, {
  mount: '/b-plan',
  routerDir: `${__dirname}/routers-b`,
  ajaxCache: false
});

stageB.set('view engine', '.njk'); // can startsWith dot or not dot

const stage = coc(app, {
  interceptorDir: `${__dirname}/interceptors`,
  routerDir: `${__dirname}/routers`,
  viewDir: `${__dirname}/views`,
  handleAPI(apiUrl) {
    const apiDomain = apiMap[apiUrl] || '';

    return apiDomain + apiUrl;
  }
});

require('marko/node-require').install();  // eslint-disable-line
stage.engine('marko', (filePath, data, callback) => {
  const template = require(filePath); // eslint-disable-line

  template.renderToString(data, callback);
});

// 查看阶段列表，每个阶段都可以用before,after处理
log.info(stage.stageNames);

stage.before('pageInfo', function beforePageInfo(req, res, next) {
  req.reqCircle = log.time();
  next();
});
stage.before('initHttpRequest', function beforeInitHttpRequest(req, res, next) {
  let timeout = 5 * 1000;

  if (req.router && req.router.timeout) {
    timeout = req.router.timeout;
  }
  req.httpRequestConfig = { timeout };

  next();
});

// forward has been test
stage.after('requestProxy', function afterRequestProxy(req, res, next) {
  const pathname = req.pathname;
  log.debug('param:', req.param);
  log.debug('path:', pathname);

  if (pathname === '/forward') {
    res.forward('/proxy');
    // res.redirect('http://www.163.com');
    // res.status(200).send('hello 200 ok!');
    // next已经可以正确处理forward情况
    // 类似redirect，res.send等已经响应了服务器的情况
    next();
    return;
  }

  next();
});
stage.before('response', function beforeResponse(req, res, next) {
  const apiInfo = res.apiInfo;

  Object.keys(apiInfo).map(name => {
    const info = apiInfo[name];
    return log.info(info.method, info.api, info.consumeTime, 'ms');
  });
  log.warn('cost time: ', req.reqCircle.end());

  next();
});

app.use((req, res) => {
  res.status(404).send('404 not found!');
});

app.use((error, req, res, next) => { // eslint-disable-line
  res.status(500).send(`<pre>${error.stack}</pre>`);
});

app.listen(8080, () => {
  const startInfo = 'server run at http://localhost:8080';

  log.info(startInfo);
});

module.exports = app;
<|endoftext|>


<commit_before>/* jshint node:true */

/**
 * js2xmlparser
 * Copyright © 2012 Michael Kourlas and other contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

(function() {
    "use strict";

    var js2xmlparser = require("../lib/js2xmlparser.js");

    console.log("EXAMPLE 1");
    console.log("=========");

    var example1 = {
        "firstName": "John",
        "lastName": "Smith"
    };

    console.log(js2xmlparser("person", example1));
    console.log();

    console.log("EXAMPLE 2");
    console.log("=========");

    var example2 = {
        "@": {
            "type": "individual"
        },
        "firstName": "John",
        "lastName": "Smith",
        "dateOfBirth": new Date(1964, 7, 26),
        "address": {
            "@": {
                "type": "home"
            },
            "streetAddress": "3212 22nd St",
            "city": "Chicago",
            "state": "Illinois",
            "zip": 10000
        },
        "phone": [
            {
                "@": {
                    "type": "home"
                },
                "#": "123-555-4567"
            },
            {
                "@": {
                    "type": "cell"
                },
                "#": "456-555-7890"
            }
        ],
        "email": function() {return "john@smith.com";},
        "notes": "John's profile is not complete."
    };

    console.log(js2xmlparser("person", example2));
    console.log();

    console.log("EXAMPLE 3");
    console.log("=========");

    var example3 = {
        "notes": "John's profile is not complete."
    };

    var example3Options = {
        useCDATA: true
    };

    console.log(js2xmlparser("person", example3, example3Options));
    console.log();

    console.log("EXAMPLE 4");
    console.log("=========");

    var example4 = {
        "email": function() {return "john@smith.com";},
        "dateOfBirth": new Date(1964, 7, 26)
    };

    var example4Options = {
        convertMap: {
            "[object Date]": function(date) {
                return date.toISOString();
            },
            "[object Function]": function(func) {
                return func.toString();
            }
        }
    };

    console.log(js2xmlparser("person", example4, example4Options));
})();
<commit_msg>Update example.js to match readme<commit_after>/* jshint node:true */

/**
 * js2xmlparser
 * Copyright © 2012 Michael Kourlas and other contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

(function() {
    "use strict";

    var js2xmlparser = require("../lib/js2xmlparser.js");

    console.log("EXAMPLE 1");
    console.log("=========");

    var example1 = {
        "firstName": "John",
        "lastName": "Smith"
    };

    console.log(js2xmlparser("person", example1));
    console.log();

    console.log("EXAMPLE 2");
    console.log("=========");

    var example2 = {
        "@": {
            "type": "individual"
        },
        "firstName": "John",
        "lastName": "Smith",
        "dateOfBirth": new Date(1964, 7, 26),
        "address": {
            "@": {
                "type": "home"
            },
            "streetAddress": "3212 22nd St",
            "city": "Chicago",
            "state": "Illinois",
            "zip": 10000
        },
        "phone": [
            {
                "@": {
                    "type": "home"
                },
                "#": "123-555-4567"
            },
            {
                "@": {
                    "type": "cell"
                },
                "#": "456-555-7890"
            }
        ],
        "email": function() {return "john@smith.com";},
        "notes": "John's profile is not complete."
    };

    console.log(js2xmlparser("person", example2));
    console.log();

    console.log("EXAMPLE 3");
    console.log("=========");

    var example3 = {
        "email": function() {return "john@smith.com";},
        "dateOfBirth": new Date(1964, 7, 26)
    };

    var example3Options = {
        convertMap: {
            "[object Date]": function(date) {
                return date.toISOString();
            },
            "[object Function]": function(func) {
                return func.toString();
            }
        }
    };

    console.log(js2xmlparser("person", example3, example3Options));
    console.log();

    console.log("EXAMPLE 4");
    console.log("=========");

    var example4 = {
        "notes": "John's profile is not complete."
    };

    var example4Options = {
        useCDATA: true
    };

    console.log(js2xmlparser("person", example4, example4Options));
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const BaseArray = require('../../base/BaseArray.js').BaseArray;
const documentationTypes = require('./index.js');

/**
 * @class
 * @memberOf model.docmentation
 * @extends {Base}
 */
class DocumentationArray extends BaseArray
{
    /**
     * The namespaced class name
     *
     * @type {string}
     * @static
     */
    static get className()
    {
        return 'model.documentation/DocumentationArray';
    }

    /**
     * @param {Class} type
     * @returns {Array}
     */
    getByType(type)
    {
        const classType = typeof type === 'string' ? documentationTypes[type] : type;
        const result = this.filter(function(item)
        {
            return item instanceof classType;
        });
        return result;
    }

    /**
     * @param {Class} type
     * @returns {Array}
     */
    getFirstByType(type)
    {
        return this.getByType(type).shift();
    }

    /**
     * @param {string} kind
     * @returns {Array}
     */
    getByContentKind(kind)
    {
        const contentKind = kind.toLowerCase();
        const result = this.filter(function(item)
        {
            return item.contentKind.toLowerCase() === contentKind;
        });
        return result;
    }

    /**
     * @param {Class} kind
     * @returns {Array}
     */
    getFirstByContentKind(kind)
    {
        return this.getByContentKind(kind).shift();
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.DocumentationArray = DocumentationArray;
<commit_msg>feat(model.documentation.DocumentationArray): use SearchableArray as base class<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const SearchableArray = require('../../base/SearchableArray.js').SearchableArray;
const documentationTypes = require('./index.js');

/**
 * @class
 * @memberOf model.docmentation
 * @extends {Base}
 */
class DocumentationArray extends SearchableArray
{
    /**
     * The namespaced class name
     *
     * @type {string}
     * @static
     */
    static get className()
    {
        return 'model.documentation/DocumentationArray';
    }

    /**
     * @param {Class} type
     * @returns {Array}
     */
    getByType(type)
    {
        const classType = typeof type === 'string' ? documentationTypes[type] : type;
        const result = this.filter(function(item)
        {
            return item instanceof classType;
        });
        return result;
    }

    /**
     * @param {Class} type
     * @returns {Array}
     */
    getFirstByType(type)
    {
        return this.getByType(type).shift();
    }

    /**
     * @param {string} kind
     * @returns {Array}
     */
    getByContentKind(kind)
    {
        const contentKind = kind.toLowerCase();
        const result = this.filter(function(item)
        {
            return item.contentKind.toLowerCase() === contentKind;
        });
        return result;
    }

    /**
     * @param {Class} kind
     * @returns {Array}
     */
    getFirstByContentKind(kind)
    {
        return this.getByContentKind(kind).shift();
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.DocumentationArray = DocumentationArray;
<|endoftext|>


<commit_before>/**
 *  Use aysnc script loader, configure the application module (for AngularJS)
 *  and initialize the application ( which configures routing )
 *
 *  @author Thomas Burleson
 */

 (function( window, head ) {
    "use strict";

    head.js(

      // Pre-load these for splash-screen progress bar...

      { require    : "./vendor/requirejs/require.js",                  size: "80196"   },
      { underscore : "./vendor/underscore/underscore.js",              size: "43568"   },

      { angular    : "./vendor/angular/angular.js",                    size: "551057"  },
      { ngRoute    : "./vendor/angular-route/angular-route.js",        size: "30052"   },
      { ngSanitize : "./vendor/angular-sanitize/angular-sanitize.js",  size: "19990"   },

      { quizzler   : "./assets/js/quizzler.js"                                         }

    )
    .ready("ALL", function()
    {
        // All application code is concat/uglified in 1 file:  `quizzler.js`

        require( [ "main" ], function( app )
        {
            // Application has bootstrapped and started...
        });

    });

}( window, head ));
<commit_msg>Delete boot.js<commit_after><|endoftext|>


<commit_before>const randomBackground = () => {
  let bgImg = document.getElementById('bg')
  let baseURL = 'https://source.unsplash.com/random/'
  let resolution = `${screen.width}x${screen.height}`
  let imageURL = baseURL.concat(resolution)

  caches.match(imageURL).then(response => {
    bgImg.src = response.url
  }).catch(() => {
    fetch(imageURL).then(response => {
      if (response.ok) {
        bgImg.src = response.url
        caches.open('bg-next').then(cache => {
          cache.put(imageURL, response)
        })
      }
    })
  })

  fetch(imageURL).then(response => {
    caches.open('bg-next').then(cache => {
      cache.put(imageURL, response)
    })
  })
}

const vimLike = () => {
  let home = document.getElementById('logo')
  let postlist = document.getElementById('postlist')
  let sections = document.getElementsByName('section')
  let article = document.getElementById('article')

  if (postlist) { // In post list
    let i = -1
    window.addEventListener('keypress', event => {
      if (event.key == 'j' && i < sections.length - 1) {
        sections[++i].focus()
      } else if (event.key == 'k') {
        i = (i == 0 || i == -1) ? 1 : i
        sections[--i].focus()
      } else if (event.key == 'G') {
        i = sections.length - 1
        sections[i].focus()
      } else if (event.key == 'o') {
        sections[i].click()
      } else if (event.key == 'u') {
        home.click()
      }
    })

    let previous = document.getElementById('previous')
    let next = document.getElementById('next')
    window.addEventListener('keydown', event => {
      if (event.key == 'h' && previous) {
        previous.focus()
      }
      if (event.key == 'l' && next) {
        next.focus()
      }
    })
    window.addEventListener('keyup', event => {
      if (event.key == 'h' && previous) {
        previous.click()
      }
      if (event.key == 'l' && next) {
        next.click()
      }
    })
  } else { // In article page
    window.addEventListener('keypress', event => {
      if (event.key == 'j') {
        scrollBy(0, 27)
      } else if (event.key == 'k') {
        scrollBy(0, -27)
      } else if (event.key == 'J') {
        scrollBy({
          top: 250,
          behavior: "smooth"
        })
      } else if (event.key == 'K') {
        scrollBy({
          top: -250,
          behavior: "smooth"
        })
      } else if (event.key == 'G') {
        scroll({
          top: article.offsetHeight,
          behavior: "smooth"
        })
      } else if (event.key == 'u') {
        home.click()
      }
    })
  }
}

const lightUp = () => {
  let bg = document.getElementById('bg')
  bg.style.animation = "fadein 4s"
  bg.style.opacity = 1
  let article = document.getElementById('article')
  if (article) {
    article.classList.add('light')
  }
  greeting.style.color = "#eeeeee"
  greeting.style.transition = "opacity 1.5s"
  greeting.style.opacity = 0
}

window.desktopInit = () => {
  randomBackground()
  vimLike()
  let inners = [
    "It's my personal blog",
    "Anyway..",
    "Have a good time!!"
  ]
  let greeting = document.getElementById('greeting')
  greeting.style.transition = "color 1s"
  let i = 0
  if (sessionStorage.getItem('light')) {
    lightUp()
  } else {
    greeting.addEventListener('click', () => {
      if (i < inners.length) {
        greeting.innerHTML = inners[i++]
      }
      if (i == inners.length) {
        lightUp()
        sessionStorage.setItem('light', true)
      }
    })
  }
}

if (screen.width > 480) {
  window.desktopInit()
}

// Register Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      console.log('ServiceWorker registration successful.')
    }).catch(error => {
      console.log('ServiceWorker registration failed: ', error)
    })
  })
}

// Tips
console.log(
  'If you are a loyal vimer, tell you a good news!\n' +
  'You can actually use vim-like shortcuts to control this web page.\n\n' +
  'j - Scroll down / Select below\n' +
  'k - Scroll up / Select above\n' +
  'h - Previous page\n' +
  'l - Next page\n' +
  'o - Open the selected post\n' +
  'u - Up to the home URL\n\n' +
  'And in article pages, you can also press J/K to scroll faster.\n' +
  'More shortcuts and features are comming soon!\n' +
  'If you have a better idea about this blog,\n' +
  'just tell me on https://github.com/m8524769/m8524769.github.io/issues.\n' +
  'I would really appreciate it!\n' +
  'Have a good day! :)'
)<commit_msg>Feature: Comment function, powered by HyperComments<commit_after>const randomBackground = () => {
  let bgImg = document.getElementById('bg')
  let baseURL = 'https://source.unsplash.com/random/'
  let resolution = `${screen.width}x${screen.height}`
  let imageURL = baseURL.concat(resolution)

  caches.match(imageURL).then(response => {
    bgImg.src = response.url
  }).catch(() => {
    fetch(imageURL).then(response => {
      if (response.ok) {
        bgImg.src = response.url
        caches.open('bg-next').then(cache => {
          cache.put(imageURL, response)
        })
      }
    })
  })

  fetch(imageURL).then(response => {
    caches.open('bg-next').then(cache => {
      cache.put(imageURL, response)
    })
  })
}

const vimLike = () => {
  let home = document.getElementById('logo')
  let postlist = document.getElementById('postlist')
  let sections = document.getElementsByName('section')
  let article = document.getElementById('article')

  if (postlist) { // In post list
    let i = -1
    window.addEventListener('keypress', event => {
      if (event.key == 'j' && i < sections.length - 1) {
        sections[++i].focus()
      } else if (event.key == 'k') {
        i = (i == 0 || i == -1) ? 1 : i
        sections[--i].focus()
      } else if (event.key == 'G') {
        i = sections.length - 1
        sections[i].focus()
      } else if (event.key == 'o') {
        sections[i].click()
      } else if (event.key == 'u') {
        home.click()
      }
    })

    let previous = document.getElementById('previous')
    let next = document.getElementById('next')
    window.addEventListener('keydown', event => {
      if (event.key == 'h' && previous) {
        previous.focus()
      }
      if (event.key == 'l' && next) {
        next.focus()
      }
    })
    window.addEventListener('keyup', event => {
      if (event.key == 'h' && previous) {
        previous.click()
      }
      if (event.key == 'l' && next) {
        next.click()
      }
    })
  } else { // In article page
    window.addEventListener('keypress', event => {
      if (event.key == 'j') {
        scrollBy(0, 27)
      } else if (event.key == 'k') {
        scrollBy(0, -27)
      } else if (event.key == 'J') {
        scrollBy({
          top: 250,
          behavior: "smooth"
        })
      } else if (event.key == 'K') {
        scrollBy({
          top: -250,
          behavior: "smooth"
        })
      } else if (event.key == 'G') {
        scroll({
          top: article.offsetHeight,
          behavior: "smooth"
        })
      } else if (event.key == 'u') {
        home.click()
      }
    })
  }
}

const loadComment = () => {
  _hcwp = window._hcwp || []
  _hcwp.push({ widget: "Stream", widget_id: 104126 })
  if ("HC_LOAD_INIT" in window)
    return;
  HC_LOAD_INIT = true
  let hcc = document.createElement("script")
  hcc.src = "https://w.hypercomments.com/widget/hc/104126/en/widget.js"
  hcc.async = true
  let s = document.getElementsByTagName("script")[0]
  s.parentNode.insertBefore(hcc, s.nextSibling)
}

const lightUp = () => {
  let bg = document.getElementById('bg')
  bg.style.animation = "fadein 4s"
  bg.style.opacity = 1
  let article = document.getElementById('article')
  if (article) {
    article.classList.add('light')
  }
  greeting.style.color = "#eeeeee"
  greeting.style.transition = "opacity 1.5s"
  greeting.style.opacity = 0
}

if (screen.width > 480) {
  randomBackground()
  vimLike()
  loadComment()
  let inners = [
    "It's my personal blog",
    "Anyway..",
    "Have a good time!!"
  ]
  let greeting = document.getElementById('greeting')
  greeting.style.transition = "color 1s"
  let i = 0
  if (sessionStorage.getItem('light')) {
    lightUp()
  } else {
    greeting.addEventListener('click', () => {
      if (i < inners.length) {
        greeting.innerHTML = inners[i++]
      }
      if (i == inners.length) {
        lightUp()
        sessionStorage.setItem('light', true)
      }
    })
  }
}

// Register Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then(registration => {
      console.log('ServiceWorker registration successful.')
    }).catch(error => {
      console.log('ServiceWorker registration failed: ', error)
    })
  })
}

// Tips
console.log(
  'If you are a loyal vimer, tell you a good news!\n' +
  'You can actually use vim-like shortcuts to control this web page.\n\n' +
  'j - Scroll down / Select below\n' +
  'k - Scroll up / Select above\n' +
  'h - Previous page\n' +
  'l - Next page\n' +
  'o - Open the selected post\n' +
  'u - Up to the home URL\n\n' +
  'And in article pages, you can also press J/K to scroll faster.\n' +
  'More shortcuts and features are comming soon!\n' +
  'If you have a better idea about this blog,\n' +
  'just tell me on https://github.com/m8524769/m8524769.github.io/issues.\n' +
  'I would really appreciate it!\n' +
  'Have a good day! :)'
)<|endoftext|>


<commit_before>(function(window, document) {
    "use strict";

    var WoopraScript = function(_src, _hook, _async) {
        this.scriptObject = false;
        this.src = _src;
        this.hook = _hook;
        this.async = _async;
    };

    WoopraScript.prototype.clear = function() {
        this.scriptObject.parentNode.removeChild(this.scriptObject);
    };

    WoopraScript.prototype.load = function() {
        var script = document.createElement('script'),
            ssc,
            _hook = this.hook;

        script.src = this.src;
        script.async = this.async;

        if (_hook) {
            if (typeof script.onreadystatechange !== 'undefined') {
                script.onreadystatechange = function() {
                    if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                        window.setTimeout(_hook, 400);
                    }
                };
            }
            else {
                script.onload = function() {
                    window.setTimeout(function() {
                        _hook.apply();
                    }, 400);
                };
            }
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    var WoopraEvent = function(name, ce, cv, file) {
        this.name = name || 'unknown';
        this.ce = ce || {};
        this.cv = cv || {};
        this.file = file || 'ce';
        this.requestString = '';
        this.attachCampaignData();
    };

    WoopraEvent.prototype.attachCampaignData = function() {
        var vars = this.getUrlVars(),
            i,
            key,
            value,
            campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];

        for (i = 0; i < campaignKeys.length; i++) {
            key = campaignKeys[i];
            value = vars['utm_' + key] || vars['woo_' + key];

            if (typeof value !== 'undefined') {
                this.ce['woo_' + key] = value;
            }
        }
    };

    WoopraEvent.prototype.getUrlVars = function() {
        var vars = {};

        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    };

    WoopraEvent.prototype.addProperty = function(key, value) {
        this.ce[key] = value;
    };

    WoopraEvent.prototype.serialize = function(v, prefix) {
        var i,
            itemKey;

        if (this.requestString.length > 4000 ||
            typeof v === 'undefined' ||
            typeof v === 'function') {
            return;
        }

        if (typeof v === 'string' ||
            typeof v === 'number' ||
            typeof v === 'boolean') {
            this.requestString += '&' + encodeURIComponent(prefix) +
                                  '=' + encodeURIComponent(v);
            return;
        }

        if (v instanceof Array) {
            for (i=0; i < v.length; i++) {
                this.serialize(v[i], prefix + '[' + i + ']');
            }
            return;
        }

        for (itemKey in v) {
            if (v.hasOwnProperty(itemKey)) {
                this.serialize(v[itemKey], prefix + '.' + itemKey);
            }
        }
    };

    WoopraEvent.prototype.fire = function(tracker) {
        var t = tracker,
            key,
            rd = t.getRequestData() || {};

        t.ensure();

        this.addProperty('name', this.name);
        this.requestString = '';

        for (key in rd) {
            if (rd.hasOwnProperty(key)){
                this.serialize(rd[key], key);
            }
        }
        for (key in this.cv) {
            if (this.cv.hasOwnProperty(key)){
                this.serialize(this.cv[key], 'cv_'+key);
            }
        }

        for (key in this.ce){
            if (this.ce.hasOwnProperty(key)){
                this.serialize(this.ce[key], 'ce_'+key);
            }
        }

        new WoopraScript(t.getEndpoint(this.file)+'?ra='+t.randomstring()+this.requestString, function(){}, true ).load();

    };

    var WoopraTracker = function() {
        this.chat = false;
        this.alias = '';
        this.vs = 0;
        this.props = {};
        this.cv = {};
        this.cs = {};
        this.pint = false;
        this.ctr = 0;
        this.version = 20;
        this.last_activity = new Date();
        this.idle = 0;
        this.inited = 0;
        this._loaded  =  false;
        this.initialize.apply(this, arguments);
    };

    WoopraTracker.prototype.initialize = function() {
        var i,
            a,
            _wpt = window._wpt,
            _this = this;

        this._setOptions();

        this._processQueue();
        this._loaded = true;
        this.ready.apply(this, arguments);
    };

    /**
     * Called when WoopraTracker is ready.
     * Extend this.
     */
    WoopraTracker.prototype.ready = function() {};

    /**
     * Processes the tracker queue in case user tries to push events
     * before tracker is ready.
     */
    WoopraTracker.prototype._processQueue = function() {
        var i, a,
            _wpt = window._wpt;

        if (_wpt && _wpt._e) {
            for (i = 0; i < _wpt._e.length; i++) {
                a = _wpt._e[i];
                this[_wpt._e[i][0]].apply(this, Array.prototype.slice.call(a, 1));
            }
        }
        window._wpt = this;
    };

    /**
     * Sets the initial options
     */
    WoopraTracker.prototype._setOptions = function() {
        var t = this,
            exp = new Date();

        t.option('domain', window.location.hostname);
        t.option('cookie_name', 'wooTracker');
        t.option('cookie_domain', window.location.hostname);
        t.option('cookie_path', '/');
        exp.setDate(exp.getDate()+365);
        t.option('cookie_expire', exp);
        t.option('ping', true);
        t.option('ping_interval', 12000);
        t.option('idle_timeout', 300000);
        t.option('download_pause', 200);
        t.option('outgoing_pause', 400);
        t.option('download_tracking', true);
        t.option('outgoing_tracking', true);
    };

    WoopraTracker.prototype.ensure = function() {
        var t = this,
            name,
            _c;

        if (t.inited === 0) {
            t.inited = 1;

            name = t.option('cookie_name');
            _c = t.readcookie(name);
            if (!_c || _c.length <= 0) {
                _c = t.randomstring();
            }
            t.createcookie(name, _c);

            window.setInterval(function() {
                t.next();
            }, 1000);

            if (typeof document.attachEvent !== 'undefined') {
                document.attachEvent("onmousedown", function() {
                    t.clicked.apply(t, arguments);
                });
                document.attachEvent("onmousemove", function() {
                    t.moved.apply(t, arguments);
                });
                document.attachEvent("onkeydown", function() {
                    t.typed.apply(t, arguments);
                });
            } else {
                document.addEventListener("mousedown", function() {
                    t.clicked.apply(t, arguments);
                }, false);
                document.addEventListener("mousemove", function() {
                    t.moved.apply(t, arguments);
                }, false);
                document.addEventListener("keydown", function() {
                    t.typed.apply(t, arguments);
                }, false);
            }
        }
    };

    WoopraTracker.prototype.getEndpoint = function(file) {
        return window.location.protocol + '//www.woopra.com/track/' + file + '/';
    };

    WoopraTracker.prototype.sleep = function(millis) {
        var date = new Date(),
            curDate = new Date();

        while (curDate-date < millis) {
            curDate = new Date();
        }
    };

    WoopraTracker.prototype.randomstring = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    WoopraTracker.prototype.readcookie = function(k) {
        var c = document.cookie + '',
            ind,
            ind1;

        ind = c.indexOf(k);
        if (ind === -1 || k === '') {
            return '';
        }

        ind1 = c.indexOf(';', ind);
        if (ind1 === -1) {
            ind1 = c.length;
        }

        return window.unescape(c.substring(ind + k.length + 1, ind1));
    };

    WoopraTracker.prototype.createcookie = function(k, v) {
        var t = this,
            cookieval;

        cookieval = k + '=' + v + '; ' + 'expires=' + t.option('cookie_expire') + ';' + 'path='+t.option('cookie_path')+';domain=.'+t.option('cookie_domain');
        document.cookie = cookieval;
    };

    WoopraTracker.prototype.getRequestData = function(){
        var t = this,
            r = {};

        r.alias = t.option('domain');
        r.cookie = t.readcookie(t.option('cookie_name'));
        r.meta = t.readcookie('wooMeta') || '';
        r.screen = window.screen.width + 'x' + window.screen.height;
        r.language = (window.navigator.browserLanguage || window.navigator.language || "");
        r.referer = document.referrer;
        r.idle = parseInt(t.idle/1000, 10) + '';

        if (t.vs === 2) {
            r.vs = 'w';
            t.vs = 0;
        } else {
            if (t.idle == 0) {
                r.vs = 'r';
            } else{
                r.vs = 'i';
            }
        }

        return r;
    };

    /**
     * Sends a pageview event to the server
     *
     * Alias for `track('pv', options)`
     */
    WoopraTracker.prototype.pageview = function(options) {
        var _options = options || {},
            e;

        if (typeof _options.visitor !== 'undefined') {
            this.cv = _options.visitor;
            delete _options.visitor;
        }

        e = new WoopraEvent('pv', _options, this.cv, 'visit');
        e.fire(this);
    };

    /**
     * Sends a custom event to the server
     *
     * If you pass a `visitor` object to options, then the custom visitor
     * data in `visitor` will be sent along with the custom event
     *
     * This is equivalent to calling `_wpt.visitor(data)` before
     * calling `track()`
     */
    WoopraTracker.prototype.track = function(name, options) {
        var _options = options || {},
            e;

        if (typeof _options.visitor !== 'undefined') {
            this.cv = _options.visitor;
            delete _options.visitor;
        }

        e = new WoopraEvent(name, _options, this.cv, 'ce');
        e.fire(this);
    };

    /**
     * Attach custom visitor data and then sends data to server
     * Use `visitor()` to attach
     */
    WoopraTracker.prototype.identify = function(name, value) {
        var e;

        this.visitor.apply(this, arguments);
        e = new WoopraEvent('identify', {}, this.cv, 'identify');
        e.fire(this);
    };

    /**
     * Gets/sets tracker options
     */
    WoopraTracker.prototype.option = function(k, v) {
        if (typeof v === 'undefined') {
            return this.props[k];
        }

        this.props[k] = v;
        return v;
    };

    /**
     * Attach custom visitor data without sending the server an event.
     * Use identify to sync the visitor data to the server
     */
    WoopraTracker.prototype.visitor = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cv[name] = value;
        }
        else if (typeof name === 'object') {
            this.cv = name;
        }
    };

    /**
     * Use to attach custom visit data that doesn't stick to visitor
     * ** Not in use yet
     */
    WoopraTracker.prototype.visit = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cs[name] = value;
        }
        else if (typeof name === 'object') {
            this.cs = name;
        }
    };

    /** Compatibility with old tracker methods **/
    /**
     * Shortcut to set domain
     */
    WoopraTracker.prototype.setDomain = function(domain) {
        this.option('domain', domain);
        this.option('cookie_domain', domain);
    };

    WoopraTracker.prototype.setIdleTimeout = function(timeout) {
        this.option('idle_timeout', timeout);
    };

    // XXX
    WoopraTracker.prototype.pingServer = function() {
        var e = new WoopraEvent('x', {}, this.cv, 'ping');
        e.fire(this);
    };

    WoopraTracker.prototype.typed = function(e) {
        this.vs = 2;
    };

    WoopraTracker.prototype.clicked=function(e) {
        var t = this;

        t.moved();

        var cElem = e.srcElement || e.target;
        while (typeof cElem !== 'undefined' && cElem !== null){
            if (cElem.tagNam === 'A') {
                break;
            }
            cElem = cElem.parentNode;
        }

        if (typeof cElem !== 'undefined' && cElem !== null){
            var link=cElem;
            var _download = link.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/);
            var ev=false;
            if(t.option('download_tracking')){
                if(_download && (link.href.toString().indexOf('woopra-ns.com')<0)){
                    ev=new WoopraEvent('download', {url:link.href});
                    ev.addProperty('url',link.href);
                    ev.fire(this);
                    t.sleep(t.option('download_pause'));
                }
            }
            if (t.option('outgoing_tracking')) {
                if (!_download &&
                    link.hostname !== window.location.host &&
                    link.hostname.indexOf('javascript') === -1 &&
                    link.hostname !== '') {
                    ev = new WoopraEvent('outgoing', {url:link.href});
                    ev.fire(this);
                    t.sleep(t.option('outgoing_pause'));
                }
            }
        }
    };

    WoopraTracker.prototype.moved = function() {
        var t = this;
        t.last_activity = new Date();
        t.idle = 0;
    };

    WoopraTracker.prototype.next = function(){
        var now,
            t = this;

        //clocks every 1 second
        t.ctr++;

        if (t.ctr * 1000 > t.option('ping_interval')) {
            t.ctr = 0;
            if (t.option('ping') && t.idle < t.option('idle_timeout')) {
                t.pingServer();
            }
        }

        now = new Date();
        if (now-t.last_activity > 10000) {
            t.idle = now - t.last_activity;
        }
    };

    var woopraTracker = new WoopraTracker();

    if (typeof exports !== 'undefined') {
        exports.WoopraTracker = WoopraTracker;
        exports.WoopraEvent = WoopraEvent;
    }
}(window, document));

<commit_msg>Change identify() to accept id, properties where id needs to be email<commit_after>(function(window, document) {
    "use strict";

    var WoopraScript = function(_src, _hook, _async) {
        this.scriptObject = false;
        this.src = _src;
        this.hook = _hook;
        this.async = _async;
    };

    WoopraScript.prototype.clear = function() {
        this.scriptObject.parentNode.removeChild(this.scriptObject);
    };

    WoopraScript.prototype.load = function() {
        var script = document.createElement('script'),
            ssc,
            _hook = this.hook;

        script.src = this.src;
        script.async = this.async;

        if (_hook) {
            if (typeof script.onreadystatechange !== 'undefined') {
                script.onreadystatechange = function() {
                    if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                        window.setTimeout(_hook, 400);
                    }
                };
            }
            else {
                script.onload = function() {
                    window.setTimeout(function() {
                        _hook.apply();
                    }, 400);
                };
            }
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    var WoopraEvent = function(name, ce, cv, file) {
        this.name = name || 'unknown';
        this.ce = ce || {};
        this.cv = cv || {};
        this.file = file || 'ce';
        this.requestString = '';
        this.attachCampaignData();
    };

    WoopraEvent.prototype.attachCampaignData = function() {
        var vars = this.getUrlVars(),
            i,
            key,
            value,
            campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];

        for (i = 0; i < campaignKeys.length; i++) {
            key = campaignKeys[i];
            value = vars['utm_' + key] || vars['woo_' + key];

            if (typeof value !== 'undefined') {
                this.ce['woo_' + key] = value;
            }
        }
    };

    WoopraEvent.prototype.getUrlVars = function() {
        var vars = {};

        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    };

    WoopraEvent.prototype.addProperty = function(key, value) {
        this.ce[key] = value;
    };

    WoopraEvent.prototype.serialize = function(v, prefix) {
        var i,
            itemKey;

        if (this.requestString.length > 4000 ||
            typeof v === 'undefined' ||
            typeof v === 'function') {
            return;
        }

        if (typeof v === 'string' ||
            typeof v === 'number' ||
            typeof v === 'boolean') {
            this.requestString += '&' + encodeURIComponent(prefix) +
                                  '=' + encodeURIComponent(v);
            return;
        }

        if (v instanceof Array) {
            for (i=0; i < v.length; i++) {
                this.serialize(v[i], prefix + '[' + i + ']');
            }
            return;
        }

        for (itemKey in v) {
            if (v.hasOwnProperty(itemKey)) {
                this.serialize(v[itemKey], prefix + '.' + itemKey);
            }
        }
    };

    WoopraEvent.prototype.fire = function(tracker) {
        var t = tracker,
            key,
            rd = t.getRequestData() || {};

        t.ensure();

        this.addProperty('name', this.name);
        this.requestString = '';

        for (key in rd) {
            if (rd.hasOwnProperty(key)){
                this.serialize(rd[key], key);
            }
        }
        for (key in this.cv) {
            if (this.cv.hasOwnProperty(key)){
                this.serialize(this.cv[key], 'cv_'+key);
            }
        }

        for (key in this.ce){
            if (this.ce.hasOwnProperty(key)){
                this.serialize(this.ce[key], 'ce_'+key);
            }
        }

        new WoopraScript(t.getEndpoint(this.file)+'?ra='+t.randomstring()+this.requestString, function(){}, true ).load();

    };

    var WoopraTracker = function() {
        this.chat = false;
        this.alias = '';
        this.vs = 0;
        this.props = {};
        this.cv = {};
        this.cs = {};
        this.pint = false;
        this.ctr = 0;
        this.version = 20;
        this.last_activity = new Date();
        this.idle = 0;
        this.inited = 0;
        this._loaded  =  false;
        this.initialize.apply(this, arguments);
    };

    WoopraTracker.prototype.initialize = function() {
        var i,
            a,
            _wpt = window._wpt,
            _this = this;

        this._setOptions();

        this._processQueue();
        this._loaded = true;
        this.ready.apply(this, arguments);
    };

    /**
     * Called when WoopraTracker is ready.
     * Extend this.
     */
    WoopraTracker.prototype.ready = function() {};

    /**
     * Processes the tracker queue in case user tries to push events
     * before tracker is ready.
     */
    WoopraTracker.prototype._processQueue = function() {
        var i, a,
            _wpt = window._wpt;

        if (_wpt && _wpt._e) {
            for (i = 0; i < _wpt._e.length; i++) {
                a = _wpt._e[i];
                this[_wpt._e[i][0]].apply(this, Array.prototype.slice.call(a, 1));
            }
        }
        window._wpt = this;
    };

    /**
     * Sets the initial options
     */
    WoopraTracker.prototype._setOptions = function() {
        var t = this,
            exp = new Date();

        t.option('domain', window.location.hostname);
        t.option('cookie_name', 'wooTracker');
        t.option('cookie_domain', window.location.hostname);
        t.option('cookie_path', '/');
        exp.setDate(exp.getDate()+365);
        t.option('cookie_expire', exp);
        t.option('ping', true);
        t.option('ping_interval', 12000);
        t.option('idle_timeout', 300000);
        t.option('download_pause', 200);
        t.option('outgoing_pause', 400);
        t.option('download_tracking', true);
        t.option('outgoing_tracking', true);
    };

    WoopraTracker.prototype.ensure = function() {
        var t = this,
            name,
            _c;

        if (t.inited === 0) {
            t.inited = 1;

            name = t.option('cookie_name');
            _c = t.readcookie(name);
            if (!_c || _c.length <= 0) {
                _c = t.randomstring();
            }
            t.createcookie(name, _c);

            window.setInterval(function() {
                t.next();
            }, 1000);

            if (typeof document.attachEvent !== 'undefined') {
                document.attachEvent("onmousedown", function() {
                    t.clicked.apply(t, arguments);
                });
                document.attachEvent("onmousemove", function() {
                    t.moved.apply(t, arguments);
                });
                document.attachEvent("onkeydown", function() {
                    t.typed.apply(t, arguments);
                });
            } else {
                document.addEventListener("mousedown", function() {
                    t.clicked.apply(t, arguments);
                }, false);
                document.addEventListener("mousemove", function() {
                    t.moved.apply(t, arguments);
                }, false);
                document.addEventListener("keydown", function() {
                    t.typed.apply(t, arguments);
                }, false);
            }
        }
    };

    WoopraTracker.prototype.getEndpoint = function(file) {
        return window.location.protocol + '//www.woopra.com/track/' + file + '/';
    };

    WoopraTracker.prototype.sleep = function(millis) {
        var date = new Date(),
            curDate = new Date();

        while (curDate-date < millis) {
            curDate = new Date();
        }
    };

    WoopraTracker.prototype.randomstring = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    WoopraTracker.prototype.readcookie = function(k) {
        var c = document.cookie + '',
            ind,
            ind1;

        ind = c.indexOf(k);
        if (ind === -1 || k === '') {
            return '';
        }

        ind1 = c.indexOf(';', ind);
        if (ind1 === -1) {
            ind1 = c.length;
        }

        return window.unescape(c.substring(ind + k.length + 1, ind1));
    };

    WoopraTracker.prototype.createcookie = function(k, v) {
        var t = this,
            cookieval;

        cookieval = k + '=' + v + '; ' + 'expires=' + t.option('cookie_expire') + ';' + 'path='+t.option('cookie_path')+';domain=.'+t.option('cookie_domain');
        document.cookie = cookieval;
    };

    WoopraTracker.prototype.getRequestData = function(){
        var t = this,
            r = {};

        r.alias = t.option('domain');
        r.cookie = t.readcookie(t.option('cookie_name'));
        r.meta = t.readcookie('wooMeta') || '';
        r.screen = window.screen.width + 'x' + window.screen.height;
        r.language = (window.navigator.browserLanguage || window.navigator.language || "");
        r.referer = document.referrer;
        r.idle = parseInt(t.idle/1000, 10) + '';

        if (t.vs === 2) {
            r.vs = 'w';
            t.vs = 0;
        } else {
            if (t.idle == 0) {
                r.vs = 'r';
            } else{
                r.vs = 'i';
            }
        }

        return r;
    };

    /**
     * Sends a pageview event to the server
     *
     * Alias for `track('pv', options)`
     */
    WoopraTracker.prototype.pageview = function(options) {
        var _options = options || {},
            e;

        if (typeof _options.visitor !== 'undefined') {
            this.cv = _options.visitor;
            delete _options.visitor;
        }

        e = new WoopraEvent('pv', _options, this.cv, 'visit');
        e.fire(this);
    };

    /**
     * Sends a custom event to the server
     *
     * If you pass a `visitor` object to options, then the custom visitor
     * data in `visitor` will be sent along with the custom event
     *
     * This is equivalent to calling `_wpt.visitor(data)` before
     * calling `track()`
     */
    WoopraTracker.prototype.track = function(name, options) {
        var _options = options || {},
            e;

        if (typeof _options.visitor !== 'undefined') {
            this.cv = _options.visitor;
            delete _options.visitor;
        }

        e = new WoopraEvent(name, _options, this.cv, 'ce');
        e.fire(this);
    };

    /**
     * Attach custom visitor data and then sends data to server
     * Use `visitor()` to attach
     */
    WoopraTracker.prototype.identify = function(id, properties) {
        var e;
        if (typeof properties !== 'undefined') {
            this.cv = properties;
        }
        if (typeof id !== 'undefined') {
            this.visitor('email', id);
        }

        e = new WoopraEvent('identify', {}, this.cv, 'identify');
        e.fire(this);
    };

    /**
     * Gets/sets tracker options
     */
    WoopraTracker.prototype.option = function(k, v) {
        if (typeof v === 'undefined') {
            return this.props[k];
        }

        this.props[k] = v;
        return v;
    };

    /**
     * Attach custom visitor data without sending the server an event.
     * Use identify to sync the visitor data to the server
     */
    WoopraTracker.prototype.visitor = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cv[name] = value;
        }
        else if (typeof name === 'object') {
            this.cv = name;
        }
    };

    /**
     * Use to attach custom visit data that doesn't stick to visitor
     * ** Not in use yet
     */
    WoopraTracker.prototype.visit = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cs[name] = value;
        }
        else if (typeof name === 'object') {
            this.cs = name;
        }
    };

    /** Compatibility with old tracker methods **/
    /**
     * Shortcut to set domain
     */
    WoopraTracker.prototype.setDomain = function(domain) {
        this.option('domain', domain);
        this.option('cookie_domain', domain);
    };

    WoopraTracker.prototype.setIdleTimeout = function(timeout) {
        this.option('idle_timeout', timeout);
    };

    // XXX
    WoopraTracker.prototype.pingServer = function() {
        var e = new WoopraEvent('x', {}, this.cv, 'ping');
        e.fire(this);
    };

    WoopraTracker.prototype.typed = function(e) {
        this.vs = 2;
    };

    WoopraTracker.prototype.clicked=function(e) {
        var t = this;

        t.moved();

        var cElem = e.srcElement || e.target;
        while (typeof cElem !== 'undefined' && cElem !== null){
            if (cElem.tagNam === 'A') {
                break;
            }
            cElem = cElem.parentNode;
        }

        if (typeof cElem !== 'undefined' && cElem !== null){
            var link=cElem;
            var _download = link.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/);
            var ev=false;
            if(t.option('download_tracking')){
                if(_download && (link.href.toString().indexOf('woopra-ns.com')<0)){
                    ev=new WoopraEvent('download', {url:link.href});
                    ev.addProperty('url',link.href);
                    ev.fire(this);
                    t.sleep(t.option('download_pause'));
                }
            }
            if (t.option('outgoing_tracking')) {
                if (!_download &&
                    link.hostname !== window.location.host &&
                    link.hostname.indexOf('javascript') === -1 &&
                    link.hostname !== '') {
                    ev = new WoopraEvent('outgoing', {url:link.href});
                    ev.fire(this);
                    t.sleep(t.option('outgoing_pause'));
                }
            }
        }
    };

    WoopraTracker.prototype.moved = function() {
        var t = this;
        t.last_activity = new Date();
        t.idle = 0;
    };

    WoopraTracker.prototype.next = function(){
        var now,
            t = this;

        //clocks every 1 second
        t.ctr++;

        if (t.ctr * 1000 > t.option('ping_interval')) {
            t.ctr = 0;
            if (t.option('ping') && t.idle < t.option('idle_timeout')) {
                t.pingServer();
            }
        }

        now = new Date();
        if (now-t.last_activity > 10000) {
            t.idle = now - t.last_activity;
        }
    };

    var woopraTracker = new WoopraTracker();

    if (typeof exports !== 'undefined') {
        exports.WoopraTracker = WoopraTracker;
        exports.WoopraEvent = WoopraEvent;
    }
}(window, document));

<|endoftext|>


<commit_before>import 'jquery';

let tpl_property = require('../templates/propertyTween.tpl.html');

export default class PropertyTween {
  // instance_property: The current property on the data object.
  // lineData: The line data object.
  constructor(instance_property, lineData, editor, key_val = false, timeline = false) {
    this.instance_property = instance_property;
    this.lineData = lineData;
    this.editor = editor;
    this.key_val = key_val;
    this.timeline = timeline;

    this.onChange = this.onChange.bind(this);

    this.timer = this.editor.timer;
    this.$time = false;
    this.$el = false;
    this.render();
  }

  remove() {
    delete this.$el;
    delete this.instance_property;
    delete this.lineData;
    delete this.editor;
    delete this.key_val;
    delete this.timeline;

    delete this.timer;
    delete this.$time;
  }

  render() {
    var self = this;
    if (!this.key_val.ease) {
      this.key_val.ease = 'Quad.easeOut';
    }
    var data = {
      id: this.instance_property.name + '_tween',
      val: this.key_val.ease,
      time: this.key_val.time.toFixed(3),
      options: ['Linear.easeNone'],
      selected: function() {
        if (this.toString() === self.key_val.ease) {
          return 'selected';
        }
        return '';
      }
    };

    var tweens = ['Quad', 'Cubic', 'Quart', 'Quint', 'Strong'];
    for (var i = 0; i < tweens.length; i++) {
      var tween = tweens[i];
      data.options.push(tween + '.easeOut');
      data.options.push(tween + '.easeIn');
      data.options.push(tween + '.easeInOut');
    }

    this.$el = $(tpl_property(data));
    this.$time = this.$el.find('.property__key-time strong');
    this.$time.keypress((e) => {
      if (e.charCode === 13) {
        // Enter
        e.preventDefault();
        this.$time.blur();
        this.updateKeyTime(this.$time.text());
      }
    });

    this.$time.on('click', () => document.execCommand('selectAll', false, null));
    this.$el.find('select').change(this.onChange);
  }

  updateKeyTime(time) {
    let time2 = parseFloat(time);
    if (isNaN(time2)) {
      time2 = this.key_val.time;
    }
    this.$time.text(time2);
    this.key_val.time = time2;
    this.onChange();
  }

  onChange() {
    var ease = this.$el.find('select').val();
    this.key_val.ease = ease;
    this.editor.undoManager.addState();
    this.lineData._isDirty = true;
    this.timeline._isDirty = true;
  }

  update() {
    // todo: use mustache instead...
    this.$time.html(this.key_val.time.toFixed(3));
  }
}
<commit_msg>Remove old strong easing<commit_after>import 'jquery';

let tpl_property = require('../templates/propertyTween.tpl.html');

export default class PropertyTween {
  // instance_property: The current property on the data object.
  // lineData: The line data object.
  constructor(instance_property, lineData, editor, key_val = false, timeline = false) {
    this.instance_property = instance_property;
    this.lineData = lineData;
    this.editor = editor;
    this.key_val = key_val;
    this.timeline = timeline;

    this.onChange = this.onChange.bind(this);

    this.timer = this.editor.timer;
    this.$time = false;
    this.$el = false;
    this.render();
  }

  remove() {
    delete this.$el;
    delete this.instance_property;
    delete this.lineData;
    delete this.editor;
    delete this.key_val;
    delete this.timeline;

    delete this.timer;
    delete this.$time;
  }

  render() {
    var self = this;
    if (!this.key_val.ease) {
      this.key_val.ease = 'Quad.easeOut';
    }
    var data = {
      id: this.instance_property.name + '_tween',
      val: this.key_val.ease,
      time: this.key_val.time.toFixed(3),
      options: ['Linear.easeNone'],
      selected: function() {
        if (this.toString() === self.key_val.ease) {
          return 'selected';
        }
        return '';
      }
    };

    var tweens = ['Quad', 'Cubic', 'Quart', 'Quint'];
    for (var i = 0; i < tweens.length; i++) {
      var tween = tweens[i];
      data.options.push(tween + '.easeOut');
      data.options.push(tween + '.easeIn');
      data.options.push(tween + '.easeInOut');
    }

    this.$el = $(tpl_property(data));
    this.$time = this.$el.find('.property__key-time strong');
    this.$time.keypress((e) => {
      if (e.charCode === 13) {
        // Enter
        e.preventDefault();
        this.$time.blur();
        this.updateKeyTime(this.$time.text());
      }
    });

    this.$time.on('click', () => document.execCommand('selectAll', false, null));
    this.$el.find('select').change(this.onChange);
  }

  updateKeyTime(time) {
    let time2 = parseFloat(time);
    if (isNaN(time2)) {
      time2 = this.key_val.time;
    }
    this.$time.text(time2);
    this.key_val.time = time2;
    this.onChange();
  }

  onChange() {
    var ease = this.$el.find('select').val();
    this.key_val.ease = ease;
    this.editor.undoManager.addState();
    this.lineData._isDirty = true;
    this.timeline._isDirty = true;
  }

  update() {
    // todo: use mustache instead...
    this.$time.html(this.key_val.time.toFixed(3));
  }
}
<|endoftext|>


<commit_before>$.fn.wordClock = function() {
    this.append('\

\

\
                iteisftlvne
jquartercko
twentyxfive
halfcteneto
pastbsevenl
onetwothree
fourfivesix
ninektwelve
eighteleven
tenyo\'clock
\

\

');

    var h_labels = [$('#wc-one'), $('#wc-two'), $('#wc-three'), $('#wc-four'), $('#wc-hfive'), $('#wc-six'), $('#wc-seven'), $('#wc-eight'), $('#wc-nine'), $('#wc-tenh'), $('#wc-eleven'), $('#wc-twelve')]

    function update_time() {
        $('.wc-clock-label-active').removeClass('wc-clock-label-active');
        $('#wc-it').addClass('wc-clock-label-active');
        $('#wc-is').addClass('wc-clock-label-active');

        var h = new Date().getHours() % 12;
        var m = new Date().getMinutes();

        if (m <= 57 && m > 3) {
            if (m <= 35) $('#wc-past').addClass('wc-clock-label-active');
            else { $('#wc-to').addClass('wc-clock-label-active'); h++; }
        }

        h_labels[h-1].addClass('wc-clock-label-active');

             if (m <= 3)  $('#wc-oclock').addClass('wc-clock-label-active');
        else if (m <= 8)  $('#wc-fivem').addClass('wc-clock-label-active');
        else if (m <= 13) $('#wc-tenm').addClass('wc-clock-label-active');
        else if (m <= 17) $('#wc-quarter').addClass('wc-clock-label-active');
        else if (m <= 23) $('#wc-twenty').addClass('wc-clock-label-active');
        else if (m <= 28) { $('#wc-twenty').addClass('wc-clock-label-active'); $('#wc-fivem').addClass('wc-clock-label-active'); }
        else if (m <= 35) $('#wc-half').addClass('wc-clock-label-active');
        else if (m <= 37) { $('#wc-twenty').addClass('wc-clock-label-active'); $('#wc-fivem').addClass('wc-clock-label-active'); }
        else if (m <= 43) $('#wc-twenty').addClass('wc-clock-label-active');
        else if (m <= 48) $('#wc-quarter').addClass('wc-clock-label-active');
        else if (m <= 52) $('#wc-tenm').addClass('wc-clock-label-active');
        else if (m <= 57) $('#wc-fivem').addClass('wc-clock-label-active');
        else if (m <= 60) $('#wc-oclock').addClass('wc-clock-label-active');

    }

    update_time();
    setInterval(update_time, 4000);

    return this;
}
<commit_msg>Fix wrong id bug<commit_after>$.fn.wordClock = function() {
    this.append('\

\

\
                iteisftlvne
jquartercko
twentyxfive
halfcteneto
pastbsevenl
onetwothree
fourfivesix
ninektwelve
eighteleven
tenyo\'clock
\

\

');

    var h_labels = [$('#wc-one'), $('#wc-two'), $('#wc-three'), $('#wc-four'), $('#wc-fiveh'), $('#wc-six'), $('#wc-seven'), $('#wc-eight'), $('#wc-nine'), $('#wc-tenh'), $('#wc-eleven'), $('#wc-twelve')]

    function update_time() {
        $('.wc-clock-label-active').removeClass('wc-clock-label-active');
        $('#wc-it').addClass('wc-clock-label-active');
        $('#wc-is').addClass('wc-clock-label-active');

        var h = new Date().getHours() % 12;
        var m = new Date().getMinutes();

        if (m <= 57 && m > 3) {
            if (m <= 35) $('#wc-past').addClass('wc-clock-label-active');
            else { $('#wc-to').addClass('wc-clock-label-active'); h++; }
        }

        h_labels[h-1].addClass('wc-clock-label-active');

             if (m <= 3)  $('#wc-oclock').addClass('wc-clock-label-active');
        else if (m <= 8)  $('#wc-fivem').addClass('wc-clock-label-active');
        else if (m <= 13) $('#wc-tenm').addClass('wc-clock-label-active');
        else if (m <= 17) $('#wc-quarter').addClass('wc-clock-label-active');
        else if (m <= 23) $('#wc-twenty').addClass('wc-clock-label-active');
        else if (m <= 28) { $('#wc-twenty').addClass('wc-clock-label-active'); $('#wc-fivem').addClass('wc-clock-label-active'); }
        else if (m <= 35) $('#wc-half').addClass('wc-clock-label-active');
        else if (m <= 37) { $('#wc-twenty').addClass('wc-clock-label-active'); $('#wc-fivem').addClass('wc-clock-label-active'); }
        else if (m <= 43) $('#wc-twenty').addClass('wc-clock-label-active');
        else if (m <= 48) $('#wc-quarter').addClass('wc-clock-label-active');
        else if (m <= 52) $('#wc-tenm').addClass('wc-clock-label-active');
        else if (m <= 57) $('#wc-fivem').addClass('wc-clock-label-active');
        else if (m <= 60) $('#wc-oclock').addClass('wc-clock-label-active');

    }

    update_time();
    setInterval(update_time, 4000);

    return this;
}
<|endoftext|>


<commit_before>kindling.module(function () {
   'use strict';

   var input = $('#input');
   var form = $('#chat_form');
   var abbreviation_pattern = /(?:\/\/|@)([^\s.:;,-]+)(?=[\s.:;,-]+|$)/ig;
   var _participants;

   function onOptionsChanged(e, options) {
      if (!options) {
         return;
      }

      input.bind('keyup keydown', function(){
         expandUsersOfMessage();
      });
   }

   function expandUsersOfMessage(){
      var abbreviations = getAbbreviationsFromMessage();
      var index = 0;
      for(index in abbreviations) {
         var abbreviation = abbreviations[index];
         replaceAbbreviation(abbreviation, findAbbreviation(abbreviation.replace(/^@|\/\//, '')));
      }
   }

   function replaceAbbreviation(abbreviation, userName){
      input.val([input.val().replace(abbreviation, userName), " "].join(''));
   }

   function getAbbreviationsFromMessage(){
      return input.val().match(abbreviation_pattern);
   }

   function findAbbreviation(abbreviation) {
      var initials    = new RegExp("^" + abbreviation.split("").join(".*\\W"), "i");
      var succession  = new RegExp(abbreviation.split("").join(".*"), "i");
      var participant = findParticipantBy(initials) || findParticipantBy(succession);
      return participant;
   }

   function findParticipantBy(pattern) {
      var match =  $.grep(participants(), function(element) {
         return element.match(pattern);
      });
      return match[0];
   }

   function participants(){
      return _participants || getParticipantList();

   }

   function getParticipantList(){
      _participants = [];
      $('.participant-list li').each(function(){
         _participants.push($(this).find('span.name').text());
      });
      return _participants;
   }

   return {
      init: function () {
         $.subscribe('loaded optionsChanged', onOptionsChanged);
      }
   };
}());
<commit_msg>improve something, feature ok<commit_after>kindling.module(function () {
  'use strict';

  var input = $('#input');
  var form = $('#chat_form');
  var abbreviation_pattern = /(?:\/\/|@)([^\s.:;,-]+)(?=[\s.:;,-]+|$)/ig;
  var _participants = [];

  function onOptionsChanged(e, options) {
    if (!options) {
      return;
    }

    input.bind('keyup keydown', function(){
      if(event.which == 9) {
        expandAllAbbreviations();
        return false
      }
    });
  }

  function expandAllAbbreviations(){
    var abbreviations = getAbbreviationsFromMessage();
    var index = 0;
    for(index in abbreviations) {
      var abbreviation = abbreviations[index];
      replaceAbbreviation(abbreviation, findAbbreviation(abbreviation.replace(/^@|\/\//, '')));
    }
  }

  function getAbbreviationsFromMessage() {
    return input.val().match(abbreviation_pattern);
  }

  function replaceAbbreviation(abbreviation, userName) {
    if(userName){
      input.val([input.val().replace(abbreviation, userName), " "].join(''));
    }
  }

  function findAbbreviation(abbreviation) {
    var initials    = new RegExp("^" + abbreviation.split("").join(".*\\W"), "i");
    var succession  = new RegExp(abbreviation.split("").join(".*"), "i");
    return findPattern(initials) || findPattern(succession);
  }

  function findPattern(pattern) {
    var match =  $.grep(participants(), function(element) {
      return element.match(pattern);
    });
    return match[0] || false;
  }

  function participants(){
    if(_participants.lenght != $('.participant-list li').length) {
      getParticipantList();
    }
    return _participants;
  }

  function getParticipantList(){
    _participants = [];
    $('.participant-list li').each(function(){
      _participants.push($(this).find('span.name').text());
    });
    return _participants;
  }

  return {
    init: function () {
      $.subscribe('loaded optionsChanged', onOptionsChanged);
    }
  };
}());
<|endoftext|>