<commit_before>const parse = require('co-busboy');
const sendfile = require('koa-sendfile');
const path = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs-extra'));
const azure = require('azure-storage');
const config = require('config');
const gm = require('gm');
const logger = require('./logger');
const util = require('./util');

Promise.promisifyAll(Object.getPrototypeOf(gm()));
const blobService = azure.createBlobService();
let containers = [];

function getFilePath(param) {
  logger.info(`param: ${param}`);

  const result = /(\d+)(.*)/.exec(param);
  logger.info(result);
  if (!result) {
    return null;
  }

  const containerIndex = parseInt(result[1], 10);
  const container = containers[containerIndex];
  if (!container) {
    return null;
  }

  let subdir = result[2];
  if (subdir.length > 0) {
    if (subdir[0] !== '/') {
      return null;
    }

    subdir = subdir.substr(1);
  }
  const path = subdir ? `${container.name}/${subdir}` : container.name;
  return path;
}

function getImageInfo(filepath) {
  const fileparts = [];
  fileparts[0] = filepath.substring(0, filepath.indexOf('/'));
  fileparts[1] = filepath.substring(filepath.indexOf('/') + 1);
  const info = {};
  return new Promise((resolve, reject) => {
    blobService.getBlobToStream(
      fileparts[0],
      fileparts[1],
      fs.createWriteStream('output.jpeg'),
      (error, result, response) => {
        if (!error) {
          const img = gm('output.jpeg');
          img.size((err, value) => {
            if (err) {
              reject(err);
              return;
            }

            info.size = value;
            img.orientation((err2, value2) => {
              if (err2) {
                reject(err2);
                return;
              }

              info.orientation = value2;
              resolve(info);
            });
          });
        }
      },
    );
  });
}
let blobs = [];

function aggregateContainers(err, result, cb) {
  if (err) {
    cb(err);
  } else {
    containers = containers.concat(result.entries);
    if (result.continuationToken !== null) {
      blobService.listContainersSegmented(result.continuationToken, aggregateContainers);
    } else {
      cb(null, containers);
    }
  }
}

function getContainersAsync() {
  containers = [];
  return new Promise((resolve, reject) => {
    blobService.listContainersSegmented(null, (err, result) => {
      aggregateContainers(err, result, (err, containers) => {
        if (err) {
          logger.warn(err);
          reject(err);
        } else {
          resolve(containers);
        }
      });
    });
  });
}

function aggregateBlobs(containerName, err, result, cb) {
  if (err) {
    cb(err);
  } else {
    blobs = blobs.concat(result.entries);
    if (result.continuationToken !== null) {
      blobService.listBlobsSegmented(containerName, result.continuationToken, aggregateBlobs);
    } else {
      cb(null, blobs);
    }
  }
}

function getBlobsAsync(containerName) {
  blobs = [];
  return new Promise((resolve, reject) => {
    blobService.listBlobsSegmented(containerName, null, (err, result) => {
      aggregateBlobs(containerName, err, result, (err, blobs) => {
        if (err) {
          logger.warn(err);
          reject(err);
        } else {
          resolve(blobs);
        }
      });
    });
  });
}

const funcs = {
  * storageaccount() {
    this.body = JSON.stringify(process.env.AZURE_STORAGE_ACCOUNT);
  },

  * bookmarks() {
    const bookmarks = config.get('bookmarks');
    this.body = JSON.stringify(bookmarks.map(b => b.name));
  },

  * containers() {
    containers = yield getContainersAsync();
    this.body = JSON.stringify(containers.map(c => c.name));
  },

  * dir(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid directory';
      return;
    }
    let files = [];
    logger.info(`dir: ${dir}`);
    const containerFiles = yield getBlobsAsync(dir);
    files = files.concat(containerFiles);

    const data = files.reduce((result, file) => {
      // const stats = fs.lstatSync(path.resolve(dir, file));
      if (file.name.indexOf('.flac') > -1) {
        result.push({
          name: file.name,
          isDirectory: false, // file.name.indexOf('/') > -1,
          size: file.contentLength,
          mtime: file.lastModified,
        });
      }
      return result;
    }, []);
    this.body = data;
  },

  * imageInfo(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
      return;
    }

    this.body = yield getImageInfo(filepath);
  },

  * download(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
    }
  },

  * image(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
      return;
    }

    if (!config.cacheDir) {
      yield sendfile(this, filepath);
      return;
    }

    const type = this.query.type;
    if (type !== 'sq100' && type !== 'max800') {
      this.body = 'invalid type';
      return;
    }

    const cacheFilepath = util.getImageCacheFilepath(filepath, type);
    yield util.createImageCache(type, filepath, cacheFilepath);

    yield sendfile(this, cacheFilepath);
    if (!this.status) {
      this.throw(404);
    }
  },

  * upload(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const parts = parse(this);
    let part = yield parts;
    while (part) {
      const filename = path.resolve(dir, part.filename);
      const readStream = part;
      const writeStream = fs.createWriteStream(filename);
      yield new Promise((resolve, reject) => {
        readStream.on('error', reject);
        writeStream.on('error', reject);
        writeStream.on('finish', resolve);
        readStream.pipe(writeStream);
      });

      part = yield parts;
    }

    this.status = 200;
  },

  * createFolder(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const folderName = this.request.body.name;

    const folderFilepath = path.resolve(dir, folderName);
    yield fs.mkdirAsync(folderFilepath);

    this.body = '{}';
  },

  * delete(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const files = this.request.body;

    if (!config.trashDir) {
      for (const file of files) {
        yield fs.unlinkAsync(path.resolve(dir, file));
      }
      this.body = '{}';
      return;
    }

    for (const file of files) {
      const sourceFilepath = path.resolve(dir, file);
      const trashFilename = `${Date.now()}_${file}`;
      const trashFilepath = path.resolve(config.trashDir, trashFilename);
      yield fs.moveAsync(sourceFilepath, trashFilepath);
    }
    this.body = '{}';
  },
};

function init(app) {
  app.use(function* apiHandler(next) {
    const reqPath = decodeURIComponent(this.path);
    const result = /^\/api\/(\w+)\/?(.*)/.exec(reqPath);
    if (!result) {
      yield next;
      return;
    }

    const apiName = result[1];
    const param = result[2];
    if (!funcs[apiName]) {
      logger.warn(`Invalid api: ${apiName}`);
      return;
    }

    try {
      yield* funcs[apiName].call(this, param);
    } catch (err) {
      logger.warn(`Failed to handle api: ${apiName}`, err, err.stack);
      this.status = 500;
    }
  });
}

module.exports = init;
<commit_msg>Fix regression<commit_after>const parse = require('co-busboy');
const sendfile = require('koa-sendfile');
const path = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs-extra'));
const azure = require('azure-storage');
const config = require('config');
const gm = require('gm');
const logger = require('./logger');
const util = require('./util');

Promise.promisifyAll(Object.getPrototypeOf(gm()));
const blobService = azure.createBlobService();
let containers = [];

function getFilePath(param) {
  logger.info(`param: ${param}`);

  const result = /(\d+)(.*)/.exec(param);
  logger.info(result);
  if (!result) {
    return null;
  }

  const containerIndex = parseInt(result[1], 10);
  const container = containers[containerIndex];
  if (!container) {
    return null;
  }

  let subdir = result[2];
  if (subdir.length > 0) {
    if (subdir[0] !== '/') {
      return null;
    }

    subdir = subdir.substr(1);
  }
  const path = subdir ? `${container.name}/${subdir}` : container.name;
  return path;
}

function getImageInfo(filepath) {
  const fileparts = [];
  fileparts[0] = filepath.substring(0, filepath.indexOf('/'));
  fileparts[1] = filepath.substring(filepath.indexOf('/') + 1);
  const info = {};
  return new Promise((resolve, reject) => {
    blobService.getBlobToStream(
      fileparts[0],
      fileparts[1],
      fs.createWriteStream('output.jpeg'),
      (error, result, response) => {
        if (!error) {
          const img = gm('output.jpeg');
          img.size((err, value) => {
            if (err) {
              reject(err);
              return;
            }

            info.size = value;
            img.orientation((err2, value2) => {
              if (err2) {
                reject(err2);
                return;
              }

              info.orientation = value2;
              resolve(info);
            });
          });
        }
      }
    );
  });
}
let blobs = [];

function aggregateContainers(err, result, cb) {
  if (err) {
    cb(err);
  } else {
    containers = containers.concat(result.entries);
    if (result.continuationToken !== null) {
      blobService.listContainersSegmented(result.continuationToken, aggregateContainers);
    } else {
      cb(null, containers);
    }
  }
}

function getContainersAsync() {
  containers = [];
  return new Promise((resolve, reject) => {
    blobService.listContainersSegmented(null, (err, result) => {
      aggregateContainers(err, result, (err, containers) => {
        if (err) {
          logger.warn(err);
          reject(err);
        } else {
          resolve(containers);
        }
      });
    });
  });
}

function aggregateBlobs(containerName, err, result, cb) {
  if (err) {
    cb(err);
  } else {
    blobs = blobs.concat(result.entries);
    if (result.continuationToken !== null) {
      blobService.listBlobsSegmented(containerName, result.continuationToken, aggregateBlobs);
    } else {
      cb(null, blobs);
    }
  }
}

function getBlobsAsync(containerName) {
  blobs = [];
  return new Promise((resolve, reject) => {
    blobService.listBlobsSegmented(containerName, null, (err, result) => {
      aggregateBlobs(containerName, err, result, (err, blobs) => {
        if (err) {
          logger.warn(err);
          reject(err);
        } else {
          resolve(blobs);
        }
      });
    });
  });
}

const funcs = {
  * storageaccount() {
    this.body = JSON.stringify(process.env.AZURE_STORAGE_ACCOUNT);
  },

  * bookmarks() {
    const bookmarks = config.get('bookmarks');
    this.body = JSON.stringify(bookmarks.map(b => b.name));
  },

  * containers() {
    containers = yield getContainersAsync();
    this.body = JSON.stringify(containers.map(c => c.name));
  },

  * dir(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid directory';
      return;
    }
    let files = [];
    logger.info(`dir: ${dir}`);
    const containerFiles = yield getBlobsAsync(dir);
    files = files.concat(containerFiles);

    const data = files.reduce((result, file) => {
      // const stats = fs.lstatSync(path.resolve(dir, file));
      if (file.name.indexOf('.flac') > -1) {
        result.push({
          name: file.name,
          isDirectory: false, // file.name.indexOf('/') > -1,
          size: file.contentLength,
          mtime: file.lastModified,
        });
      }
      return result;
    }, []);
    this.body = data;
  },

  * imageInfo(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
      return;
    }

    this.body = yield getImageInfo(filepath);
  },

  * download(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
    }
  },

  * image(param) {
    const filepath = getFilePath(param);
    if (!filepath) {
      this.body = 'invalid location';
      return;
    }

    if (!config.cacheDir) {
      yield sendfile(this, filepath);
      return;
    }

    const type = this.query.type;
    if (type !== 'sq100' && type !== 'max800') {
      this.body = 'invalid type';
      return;
    }

    const cacheFilepath = util.getImageCacheFilepath(filepath, type);
    yield util.createImageCache(type, filepath, cacheFilepath);

    yield sendfile(this, cacheFilepath);
    if (!this.status) {
      this.throw(404);
    }
  },

  * upload(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const parts = parse(this);
    let part = yield parts;
    while (part) {
      const filename = path.resolve(dir, part.filename);
      const readStream = part;
      const writeStream = fs.createWriteStream(filename);
      yield new Promise((resolve, reject) => {
        readStream.on('error', reject);
        writeStream.on('error', reject);
        writeStream.on('finish', resolve);
        readStream.pipe(writeStream);
      });

      part = yield parts;
    }

    this.status = 200;
  },

  * createFolder(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const folderName = this.request.body.name;

    const folderFilepath = path.resolve(dir, folderName);
    yield fs.mkdirAsync(folderFilepath);

    this.body = '{}';
  },

  * delete(param) {
    const dir = getFilePath(param);
    if (!dir) {
      this.body = 'invalid location';
      return;
    }

    const files = this.request.body;

    if (!config.trashDir) {
      for (const file of files) {
        yield fs.unlinkAsync(path.resolve(dir, file));
      }
      this.body = '{}';
      return;
    }

    for (const file of files) {
      const sourceFilepath = path.resolve(dir, file);
      const trashFilename = `${Date.now()}_${file}`;
      const trashFilepath = path.resolve(config.trashDir, trashFilename);
      yield fs.moveAsync(sourceFilepath, trashFilepath);
    }
    this.body = '{}';
  },
};

function init(app) {
  app.use(function* apiHandler(next) {
    const reqPath = decodeURIComponent(this.path);
    const result = /^\/api\/(\w+)\/?(.*)/.exec(reqPath);
    if (!result) {
      yield next;
      return;
    }

    const apiName = result[1];
    const param = result[2];
    if (!funcs[apiName]) {
      logger.warn(`Invalid api: ${apiName}`);
      return;
    }

    try {
      yield* funcs[apiName].call(this, param);
    } catch (err) {
      logger.warn(`Failed to handle api: ${apiName}`, err, err.stack);
      this.status = 500;
    }
  });
}

module.exports = init;
<|endoftext|>


<commit_before><commit_msg>Fix rendering; add tag and title properties<commit_after><|endoftext|>


<commit_before>$(function() {
	$(".screenshotframe").dialog({
			autoOpen: false,
			draggable: false,
			resizable: false,
			show: "clip",
			hide: "clip",
			speed: "fast",
			closeOnEscape: true,
			width: 790,
			height: "auto"
		});
	$("#maincontent").accordion({
		heightStyle: "content",
		animate: "easeOutCubic"
	});

	$("#headercontent").click(function(){
		$("#maincontent").accordion("option", "active" , 0);
	});

	$(".projtitle").click(function(){
		displayFull(this.id);
	});
});

$(document).ready(function() {
	drawSkills("skills");
	displayFull("oom");
});

function showDialog(id) {
	$("#"+id ).dialog("open");
}

function displayFull(id) {
	var idhtml = $("#"+id+"txtfull").html();
	$("#projectdetails").html(idhtml);
	$("h2.projtitle").removeClass("whiteonblue").addClass("blueonwhite");
	$("#"+id ).addClass("whiteonblue");
	$("#"+id+"screen").click(function(){
		showDialog(id+"frame");
	});
}

function drawSkills(parent) {
	var skills = ["Java","Ruby","JavaScript","PHP","Lua","C++","C#","Perl","MySQL","MongoDB","JSP","jQuery","GWT","AWS","Rails","Apex","CSS","Tomcat"];
	var exp = [/*"Java"*/5,/*"Ruby"*/3,/*"JavaScript"*/4,/*"PHP"*/4,/*"Lua"*/2,/*"C++"*/2,/*"C#"*/2,/*"Perl"*/2,/*"MySQL"*/4,/*"MongoDB"*/3,/*"JSP"*/1,/*"jQuery"*/4,/*"GWT"*/2,/*"AWS"*/1,/*"Rails"*/3,/*"Apex"*/2,/*"CSS"*/4,/*"Tomcat"*/1];

	var html = "";
	for (var i=0; i<skills.length; i++) {
		html += drawSkill(skills[i], exp[i]);
	}

	$("#"+parent).html(html);
}

function drawSkill(skill, exp) {
	var html = 	"
"+
			    ""+skill+""+
				"
";
	for (var i=0; i<5; i++) {
		if (exp > i) {
			html += "

"
		} else {
			html += "

"
		}
	}
	html += "

";
	return html;
}
<commit_msg>close dialog on outside click<commit_after>$(function() {
	$(".screenshotframe").dialog({
			autoOpen: false,
			draggable: false,
			resizable: false,
			show: "clip",
			hide: "clip",
			speed: "fast",
			closeOnEscape: true,
			width: 790,
			height: "auto"
		});
	$("#maincontent").accordion({
		heightStyle: "content",
		animate: "easeOutCubic"
	});

	$("#headercontent").click(function(){
		$("#maincontent").accordion("option", "active" , 0);
	});

	$(".projtitle").click(function(){
		displayFull(this.id);
	});
});

$(document).ready(function() {
	drawSkills("skills");
	displayFull("oom");
});

function showDialog(id) {
	$("#"+id).dialog("open");
	$("#"+id).click(function(event) {
		event.stopPropagation();
	});
}

function hideDialog(id) {
	$("#"+id).dialog("close");
}

function displayFull(id) {
	var idhtml = $("#"+id+"txtfull").html();
	$("#projectdetails").html(idhtml);
	$("h2.projtitle").removeClass("whiteonblue").addClass("blueonwhite");
	$("#"+id ).addClass("whiteonblue");
	$("body").click(function() {
		hideDialog(id+"frame");
	});
	$("#"+id+"screen").click(function(event) {
		event.stopPropagation();
		showDialog(id+"frame");
	});
}

function drawSkills(parent) {
	var skills = ["Java","Ruby","JavaScript","PHP","Lua","C++","C#","Perl","MySQL","MongoDB","JSP","jQuery","GWT","AWS","Rails","Apex","CSS","Tomcat"];
	var exp = [/*"Java"*/5,/*"Ruby"*/3,/*"JavaScript"*/4,/*"PHP"*/4,/*"Lua"*/2,/*"C++"*/2,/*"C#"*/2,/*"Perl"*/2,/*"MySQL"*/4,/*"MongoDB"*/3,/*"JSP"*/1,/*"jQuery"*/4,/*"GWT"*/2,/*"AWS"*/1,/*"Rails"*/3,/*"Apex"*/2,/*"CSS"*/4,/*"Tomcat"*/1];

	var html = "";
	for (var i=0; i<skills.length; i++) {
		html += drawSkill(skills[i], exp[i]);
	}

	$("#"+parent).html(html);
}

function drawSkill(skill, exp) {
	var html = 	"
"+
			    ""+skill+""+
				"
";
	for (var i=0; i<5; i++) {
		if (exp > i) {
			html += "

"
		} else {
			html += "

"
		}
	}
	html += "

";
	return html;
}
<|endoftext|>


<commit_before>//= require "../chrome/storage"

var libraries = [
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
        "label": "jQuery latest",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-git.js",
        "label": "jQuery WIP (via git)",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.7.2.min.js",
        "label": "jQuery 1.7.2",
        "group": "jQuery"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js",
        "label": "jQuery 1.6.4",
        "group": "jQuery"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css",
            "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"
        ],
        "label": "jQuery UI 1.8.13",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/latest/jquery.mobile.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/latest/jquery.mobile.js"
        ],
        "label": "jQuery Mobile Latest",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.js"
        ],
        "label": "jQuery Mobile 1.1.0",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.1.min.js"
        ],
        "label": "jQuery Mobile 1.0.1",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/jquery.min.js",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap.css",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css",
            "http://twitter.github.com/bootstrap/assets/js/bootstrap.js"
        ],
        "label": "Bootstrap latest",
        "group": "Bootstrap"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
        "label": "Prototype latest",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js",
        "label": "Prototype 1.7.0.0",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js",
        "label": "Prototype 1.6.1.0",
        "group": "Prototype"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
            "http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js"
        ],
        "label": "script.aculo.us 1.8.3",
        "group": "Prototype"
    },
    {
        "url": "http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js",
        "label": "YUI 3.5.1",
        "group": "YUI"
    },
    {
        "url": "http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js",
        "label": "YUI 2.9.0",
        "group": "YUI"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js",
        "label": "Mootools 1.3.2",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js",
        "label": "Mootools 1.2.4",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js",
        "label": "Dojo 1.6.0",
        "group": "Dojo"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js",
        "label": "Dojo 1.4.1",
        "group": "Dojo"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.7.1.min.js",
            "http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q2 2012",
        "group": "Kendo UI"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.7.1.min.js",
            "http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q1 2012",
        "group": "Kendo UI"
    },
    {
        "url" : [
            "http://code.jquery.com/qunit/qunit-git.css",
            "http://code.jquery.com/qunit/qunit-git.js"
        ],
        "label": "QUnit",
        "group": "Testing"
    },
    {
        "url":"http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js",
        "label": "Angular 1.0.1"
    },
    {
        "url": [
            "http://documentcloud.github.com/underscore/underscore-min.js",
            "http://documentcloud.github.com/backbone/backbone-min.js"
        ],
        "label": "Backbone 0.9.2"
    },
    {
        "url": "http://jashkenas.github.com/coffee-script/extras/coffee-script.js",
        "label": "CoffeeScript"
    },
    {
        "url": "https://github.com/downloads/emberjs/ember.js/ember-0.9.8.1.min.js",
        "label": "Ember.js 0.9.8.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/es5-shim/1.2.4/es5-shim.min.js",
        "label": "ES5 shim 1.2.4"
    },
    {
        "url": [
            "http://extjs.cachefly.net/ext-3.1.0/resources/css/ext-all.css",
            "http://cdnjs.cloudflare.com/ajax/libs/ext-core/3.1.0/ext-core.js"
        ],
        "label": "ext-core 3.1.0"
    },
    {
        "url": "http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js",
        "label": "Knockout 2.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/less.js/1.1.3/less-1.1.3.min.js",
        "label": "Less 1.1.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.4.2/lodash.min.js",
        "label": "lodash 0.4.2"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.5.3/modernizr.min.js",
        "label": "Modernizr 2.5.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.6/prefixfree.min.js",
        "label": "Prefixfree 1.0.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.2.3/processing-api.min.js",
        "label": "Processing 1.2.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/raphael/2.0.0/raphael-min.js",
        "label": "Raphaël 2.0.0"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/sammy.js/0.6.3/sammy.min.js",
        "label": "Sammy 0.6.3"
    },
    {
        "url": [
            "http://cdn.sencha.io/touch/1.1.0/resources/css/sencha-touch.css",
            "http://cdn.sencha.io/touch/1.1.0/sencha-touch.js"
        ],
        "label": "Sencha Touch"
    },
    {
        "url": [
            "http://traceur-compiler.googlecode.com/git/src/traceur.js",
            "http://traceur-compiler.googlecode.com/git/src/bootstrap.js"
        ],
        "label": "Traceur"
    },
    {
        "url": "http://remy.github.com/twitterlib/twitterlib.min.js",
        "label": "TwitterLib"
    },
    {
        "url": "http://documentcloud.github.com/underscore/underscore-min.js",
        "label": "underscore 1.3.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/zepto/0.7/zepto.min.js",
        "label": "Zepto 0.7"
    }
];

window.libraries = libraries; // expose a command line API

libraries.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");
for (var i = 0; i < libraries.userSpecified.length; i++) {
  libraries.push(libraries.userSpecified[i]);
}

libraries.add = function (lib) {
  // save to localStorage
  lib.group = 'Custom';
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  libraries.push(lib);
  $('#library').trigger('init');
};

libraries.clear = function () {
  libraries.userSpecified = [];
  localStorage.removeItem('libraries');
  var length = libraries.length;
  for (var i = 0; i < length; i++) {
    if (libraries[i].group === 'Custom') {
      libraries.splice(i, 1);
      length--;
    }
  }
  // force a refresh?
  $('#library').trigger('init');
};
<commit_msg>Updated mootools<commit_after>//= require "../chrome/storage"

var libraries = [
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
        "label": "jQuery latest",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-git.js",
        "label": "jQuery WIP (via git)",
        "group": "jQuery"
    },
    {
        "url": "http://code.jquery.com/jquery-1.7.2.min.js",
        "label": "jQuery 1.7.2",
        "group": "jQuery"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js",
        "label": "jQuery 1.6.4",
        "group": "jQuery"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css",
            "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
            "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"
        ],
        "label": "jQuery UI 1.8.13",
        "group": "jQuery UI"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/latest/jquery.mobile.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/latest/jquery.mobile.js"
        ],
        "label": "jQuery Mobile Latest",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.js"
        ],
        "label": "jQuery Mobile 1.1.0",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css",
            "http://code.jquery.com/jquery-1.6.4.min.js",
            "http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.1.min.js"
        ],
        "label": "jQuery Mobile 1.0.1",
        "group": "jQuery Mobile"
    },
    {
        "url": [
            "http://code.jquery.com/jquery.min.js",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap.css",
            "http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css",
            "http://twitter.github.com/bootstrap/assets/js/bootstrap.js"
        ],
        "label": "Bootstrap latest",
        "group": "Bootstrap"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
        "label": "Prototype latest",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js",
        "label": "Prototype 1.7.0.0",
        "group": "Prototype"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js",
        "label": "Prototype 1.6.1.0",
        "group": "Prototype"
    },
    {
        "url": [
            "http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js",
            "http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js"
        ],
        "label": "script.aculo.us 1.8.3",
        "group": "Prototype"
    },
    {
        "url": "http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js",
        "label": "YUI 3.5.1",
        "group": "YUI"
    },
    {
        "url": "http://yui.yahooapis.com/2.9.0/build/yuiloader/yuiloader-min.js",
        "label": "YUI 2.9.0",
        "group": "YUI"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js",
        "label": "Mootools 1.4.5",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js",
        "label": "Mootools 1.3.2",
        "group": "MooTools"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js",
        "label": "Dojo 1.6.0",
        "group": "Dojo"
    },
    {
        "url": "http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js",
        "label": "Dojo 1.4.1",
        "group": "Dojo"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.7.1.min.js",
            "http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q2 2012",
        "group": "Kendo UI"
    },
    {
        "url": [
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.common.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.default.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.dataviz.min.css",
            "http://cdn.kendostatic.com/2012.1.322/styles/kendo.mobile.all.min.css",
            "http://code.jquery.com/jquery-1.7.1.min.js",
            "http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"
        ],
        "label": "Kendo UI Q1 2012",
        "group": "Kendo UI"
    },
    {
        "url" : [
            "http://code.jquery.com/qunit/qunit-git.css",
            "http://code.jquery.com/qunit/qunit-git.js"
        ],
        "label": "QUnit",
        "group": "Testing"
    },
    {
        "url":"http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js",
        "label": "Angular 1.0.1"
    },
    {
        "url": [
            "http://documentcloud.github.com/underscore/underscore-min.js",
            "http://documentcloud.github.com/backbone/backbone-min.js"
        ],
        "label": "Backbone 0.9.2"
    },
    {
        "url": "http://jashkenas.github.com/coffee-script/extras/coffee-script.js",
        "label": "CoffeeScript"
    },
    {
        "url": "https://github.com/downloads/emberjs/ember.js/ember-0.9.8.1.min.js",
        "label": "Ember.js 0.9.8.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/es5-shim/1.2.4/es5-shim.min.js",
        "label": "ES5 shim 1.2.4"
    },
    {
        "url": [
            "http://extjs.cachefly.net/ext-3.1.0/resources/css/ext-all.css",
            "http://cdnjs.cloudflare.com/ajax/libs/ext-core/3.1.0/ext-core.js"
        ],
        "label": "ext-core 3.1.0"
    },
    {
        "url": "http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js",
        "label": "Knockout 2.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/less.js/1.1.3/less-1.1.3.min.js",
        "label": "Less 1.1.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.4.2/lodash.min.js",
        "label": "lodash 0.4.2"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.5.3/modernizr.min.js",
        "label": "Modernizr 2.5.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.6/prefixfree.min.js",
        "label": "Prefixfree 1.0.6"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.2.3/processing-api.min.js",
        "label": "Processing 1.2.3"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/raphael/2.0.0/raphael-min.js",
        "label": "Raphaël 2.0.0"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/sammy.js/0.6.3/sammy.min.js",
        "label": "Sammy 0.6.3"
    },
    {
        "url": [
            "http://cdn.sencha.io/touch/1.1.0/resources/css/sencha-touch.css",
            "http://cdn.sencha.io/touch/1.1.0/sencha-touch.js"
        ],
        "label": "Sencha Touch"
    },
    {
        "url": [
            "http://traceur-compiler.googlecode.com/git/src/traceur.js",
            "http://traceur-compiler.googlecode.com/git/src/bootstrap.js"
        ],
        "label": "Traceur"
    },
    {
        "url": "http://remy.github.com/twitterlib/twitterlib.min.js",
        "label": "TwitterLib"
    },
    {
        "url": "http://documentcloud.github.com/underscore/underscore-min.js",
        "label": "underscore 1.3.1"
    },
    {
        "url": "http://cdnjs.cloudflare.com/ajax/libs/zepto/0.7/zepto.min.js",
        "label": "Zepto 0.7"
    }
];

window.libraries = libraries; // expose a command line API

libraries.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");
for (var i = 0; i < libraries.userSpecified.length; i++) {
  libraries.push(libraries.userSpecified[i]);
}

libraries.add = function (lib) {
  // save to localStorage
  lib.group = 'Custom';
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  libraries.push(lib);
  $('#library').trigger('init');
};

libraries.clear = function () {
  libraries.userSpecified = [];
  localStorage.removeItem('libraries');
  var length = libraries.length;
  for (var i = 0; i < length; i++) {
    if (libraries[i].group === 'Custom') {
      libraries.splice(i, 1);
      length--;
    }
  }
  // force a refresh?
  $('#library').trigger('init');
};
<|endoftext|>


<commit_before>import React from 'react';
import classnames from 'classnames';
import { get } from 'lodash';
import Tab from './TabV2';
import { Icon } from '../Icon';
import { Badge } from '../Badge';

function Tabs({ embedded, children, onChange, active }) {
  const filterTabs = item => get(item, 'type') === Tab;

  function renderHeader(tab, index) {
    const tabName = get(tab, 'props.id');
    const onClick = () => {
      if (tabName !== active) {
        onChange(tabName);
      }
    };
    const className = classnames('ui-tab-header', {
      'ui-tab-header-active': tabName === active,
    });
    const icon = get(tab, 'props.icon');
    const title = get(tab, 'props.title');
    const badge = get(tab, 'props.badge');
    const image = get(tab, 'props.image');

    return (

        {icon && <Icon name={icon} />}
        {title}
        {badge && <Badge margin="1xl" theme="info">{badge}</Badge>}
        {image && ()}

    );
  }

  function renderHeaders() {
    return (

        {children.filter(filterTabs).map(renderHeader)}

    );
  }

  function renderTab(tab, index) {
    const tabName = get(tab, 'props.id');

    if (tabName !== active) { return null; }

    const builder = get(tab, 'props.builder');

    const buildTabContent = () => {
      if (builder) { return builder(); }

      return tab.props.children;
    };

    const newProps = { ...tab.props,
      key: index,
      children: buildTabContent(),
    };

    return <Tab {...newProps} />;
  }

  function renderTabs() {
    return (

        {children.filter(filterTabs).map(renderTab)}

    );
  }

  const className = classnames('ui-tabs', {
    'ui-tabs-embedded': embedded,
  });
  return (

      {renderHeaders()}
      {renderTabs()}

  );
}

Tabs.propTypes = {
  children: React.PropTypes.node,
  embedded: React.PropTypes.bool,

  // Name of the active tab (optional)
  active: React.PropTypes.string,

  // Called when the tab changes
  onChange: React.PropTypes.func,
};

Tabs.defaultProps = {
};

export default Tabs;
<commit_msg>Allow tabs component to have only one tab<commit_after>import React from 'react';
import classnames from 'classnames';
import { get } from 'lodash';
import Tab from './TabV2';
import { Icon } from '../Icon';
import { Badge } from '../Badge';

function Tabs({ embedded, children, onChange, active }) {
  const filterTabs = item => get(item, 'type') === Tab;

  function renderHeader(tab, index) {
    const tabName = get(tab, 'props.id');
    const onClick = () => {
      if (tabName !== active) {
        onChange(tabName);
      }
    };
    const className = classnames('ui-tab-header', {
      'ui-tab-header-active': tabName === active,
    });
    const icon = get(tab, 'props.icon');
    const title = get(tab, 'props.title');
    const badge = get(tab, 'props.badge');
    const image = get(tab, 'props.image');

    return (

        {icon && <Icon name={icon} />}
        {title}
        {badge && <Badge margin="1xl" theme="info">{badge}</Badge>}
        {image && ()}

    );
  }

  function renderHeaders() {
    return (

        {[].concat(children).filter(filterTabs).map(renderHeader)}

    );
  }

  function renderTab(tab, index) {
    const tabName = get(tab, 'props.id');

    if (tabName !== active) { return null; }

    const builder = get(tab, 'props.builder');

    const buildTabContent = () => {
      if (builder) { return builder(tabName); }

      return tab.props.children;
    };

    const newProps = { ...tab.props,
      key: index,
      children: buildTabContent(),
    };

    return <Tab {...newProps} />;
  }

  function renderTabs() {
    return (

        {[].concat(children).filter(filterTabs).map(renderTab)}

    );
  }

  const className = classnames('ui-tabs', {
    'ui-tabs-embedded': embedded,
  });
  return (

      {renderHeaders()}
      {renderTabs()}

  );
}

Tabs.propTypes = {
  children: React.PropTypes.node,
  embedded: React.PropTypes.bool,

  // Name of the active tab (optional)
  active: React.PropTypes.string,

  // Called when the tab changes
  onChange: React.PropTypes.func,
};

Tabs.defaultProps = {
};

export default Tabs;
<|endoftext|>


<commit_before>/*
 * grunt-contrib-qunit
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Nodejs libs.
  var path = require('path');
  var fs = require('fs');

  // External lib.
  var phantomjs = require('grunt-lib-phantomjs-istanbul').init(grunt);
  var istanbul = require('istanbul');
  var instrumenter = new istanbul.Instrumenter();
  var rimraf = require('rimraf');

  // Keep track of the last-started module, test and status.
  var currentModule, currentTest, status, generalOptions;
  // Keep track of the last-started test(s).
  var unfinished = {};
  // Get temp file path for covarage
  var tempFileCoverage = path.normalize(__dirname + '/../temp/coverage.tmp');
  // Get an asset file, local to the root of the project.
  var asset = path.join.bind(null, __dirname, '..');

  // Allow an error message to retain its color when split across multiple lines.
  var formatMessage = function(str) {
    return String(str).split('\n').map(function(s) { return s.magenta; }).join('\n');
  };

  // Keep track of failed assertions for pretty-printing.
  var failedAssertions = [];
  var logFailedAssertions = function() {
    var assertion;
    // Print each assertion error.
    while (assertion = failedAssertions.shift()) {
      grunt.verbose.or.error(assertion.testName);
      grunt.log.error('Message: ' + formatMessage(assertion.message));
      if (assertion.actual !== assertion.expected) {
        grunt.log.error('Actual: ' + formatMessage(assertion.actual));
        grunt.log.error('Expected: ' + formatMessage(assertion.expected));
      }
      if (assertion.source) {
        grunt.log.error(assertion.source.replace(/ {4}(at)/g, '  $1'));
      }
      grunt.log.writeln();
    }
  };

  // QUnit hooks.
  phantomjs.on('qunit.moduleStart', function(name) {
    unfinished[name] = true;
    currentModule = name;
  });

  phantomjs.on('qunit.moduleDone', function(name/*, failed, passed, total*/) {
    delete unfinished[name];
  });

  phantomjs.on('qunit.log', function(result, actual, expected, message, source) {
    if (!result) {
      failedAssertions.push({
        actual: actual, expected: expected, message: message, source: source,
        testName: currentTest
      });
    }
  });

  phantomjs.on('qunit.testStart', function(name) {
    currentTest = (currentModule ? currentModule + ' - ' : '') + name;
    grunt.verbose.write(currentTest + '...');
  });

  phantomjs.on('qunit.coverage', function(coverage) {
    if (coverage) {
      var Report = istanbul.Report;
      var Utils = istanbul.utils;
      var collector = new istanbul.Collector();
      var coverageOptions = generalOptions.coverage;

      // add coverage information to the collector
      collector.add(coverage);

      // store coverage data for cmd output
      status.coverage = Utils.summarizeCoverage(collector.getFinalCoverage());

      // check if a html report should be generated
      if (coverageOptions.htmlReport) {
        Report.create('html', {dir: coverageOptions.htmlReport}).writeReport(collector);
      }

      // check if a cobertura report should be generated
      if (coverageOptions.coberturaReport) {
        Report.create('cobertura', {dir: coverageOptions.coberturaReport}).writeReport(collector, true);
      }

      // check if a lcov report should be generated
      if (coverageOptions.lcovReport) {
        Report.create('lcov', {dir: coverageOptions.lcovReport}).writeReport(collector);
      }

      // delete the instrumented files
      rimraf.sync(generalOptions.transport.instrumentedFiles);
    }
  });

  phantomjs.on('qunit.testDone', function(name, failed/*, passed, total*/) {
    // Log errors if necessary, otherwise success.
    if (failed > 0) {
      // list assertions
      if (grunt.option('verbose')) {
        grunt.log.error();
        logFailedAssertions();
      } else {
        grunt.log.write('F'.red);
      }
    } else {
      grunt.verbose.ok().or.write('.');
    }
  });

  phantomjs.on('qunit.done', function(failed, passed, total, duration) {
    phantomjs.halt();
    status.failed += failed;
    status.passed += passed;
    status.total += total;
    status.duration += duration;
    // Print assertion errors here, if verbose mode is disabled.
    if (!grunt.option('verbose')) {
      if (failed > 0) {
        grunt.log.writeln();
        logFailedAssertions();
      } else {
        grunt.log.ok();
      }
    }
  });

  // Re-broadcast qunit events on grunt.event.
  phantomjs.on('qunit.*', function() {
    var args = [this.event].concat(grunt.util.toArray(arguments));
    grunt.event.emit.apply(grunt.event, args);
  });

  // Built-in error handlers.
  phantomjs.on('fail.load', function(url) {
    phantomjs.halt();
    grunt.verbose.write('Running PhantomJS...').or.write('...');
    grunt.log.error();
    grunt.warn('PhantomJS unable to load "' + url + '" URI.');
  });

  phantomjs.on('fail.timeout', function() {
    phantomjs.halt();
    grunt.log.writeln();
    grunt.warn('PhantomJS timed out, possibly due to a missing QUnit start() call.');
  });

  // Pass-through console.log statements.
  phantomjs.on('console', console.log.bind(console));

  grunt.registerMultiTask('qunit', 'Run QUnit unit tests in a headless PhantomJS instance.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      // Default PhantomJS timeout.
      timeout: 5000,
      // QUnit-PhantomJS bridge file to be injected.
      inject: asset('phantomjs/bridge.js'),
      // Explicit non-file URLs to test.
      urls: [],
      // Explicitly define all coverage options (as empty)
      coverage: {
        src: []
      }
    });

    // Combine any specified URLs with src files.
    var urls = options.urls.concat(this.filesSrc);

    // This task is asynchronous.
    var done = this.async();

    // Reset status.
    status = {failed: 0, passed: 0, total: 0, duration: 0, coverage: '-'};

    // expand files for coverage
    if (options.coverage && options.coverage.src && options.coverage.src.length) {
        options.coverage.include = grunt.file.expand(options.coverage.src);
        var instrumentedFiles = {};
    }

    grunt.util.async.forEachSeries(options.coverage.include, function (file, cb) {
      var filepath = fs.realpathSync(file);
      var fileStorage = filepath;

      // check if files will be delivered by a webserver
      if (options.urls && options.coverage && options.coverage.baseUrl) {
        fileStorage = path.relative(options.coverage.baseUrl, filepath);
      }

      // instrument the files that should be processed by istanbul
      if (options.coverage && options.coverage.instrumentedFiles) {
        instrumentedFiles[fileStorage] = instrumenter.instrumentSync(String(fs.readFileSync(filepath)), filepath);
      }

      cb();
    }, function (err, result) {
        // set transport options
        if (!options.transport) {
          options.transport = {};
        }

        // clear instrumented files folder & generate a new one
        if (options.coverage && options.coverage.instrumentedFiles) {
          if (!fs.existsSync(options.coverage.instrumentedFiles)) {
            grunt.file.mkdir(options.coverage.instrumentedFiles);
            options.transport.instrumentedFiles = options.coverage.instrumentedFiles;
          } else {
            options.transport.instrumentedFiles = fs.realpathSync(options.coverage.instrumentedFiles);
            rimraf.sync(options.transport.instrumentedFiles);
          }
        }

        // write instrumented file information to an temporary file
        // and transport the info to phantom
        if (options.coverage && options.coverage.instrumentedFiles) {
          grunt.file.write(tempFileCoverage, JSON.stringify(instrumentedFiles));
          options.transport.coverage = fs.realpathSync(tempFileCoverage);
        }

        // make options globally available
        generalOptions = options;

        // Process each filepath in-order.
        grunt.util.async.forEachSeries(urls, function(url, next) {
          var basename = path.basename(url);
          grunt.verbose.subhead('Testing ' + url).or.write('Testing ' + url);

          // Reset current module.
          currentModule = null;

          // Launch PhantomJS.
          grunt.event.emit('qunit.spawn', url);
          phantomjs.spawn(url, {
            // Additional PhantomJS options.
            options: options,
            // Do stuff when done.
            done: function(err) {
              if (err) {
                // If there was an error, abort the series.
                done();
              } else {
                // Otherwise, process next url.
                next();
              }
            },
          });
        },
        // All tests have been run.
        function() {
          // Log results.
          if (status.failed > 0) {
            grunt.warn(status.failed + '/' + status.total + ' assertions failed (' +
              status.duration + 'ms)');
          } else if (status.total === 0) {
            grunt.warn('0/0 assertions ran (' + status.duration + 'ms)');
          } else {
            grunt.verbose.writeln();
            grunt.log.ok(status.total + ' assertions passed (' + status.duration + 'ms)');

            // check if coverage was enable during the testrun
            if (status.coverage && status.coverage.lines) {
              grunt.log.ok('Coverage:');
              grunt.log.ok('-  Lines: ' + status.coverage.lines.pct + '%');
              grunt.log.ok('-  Statements: ' + status.coverage.statements.pct + '%');
              grunt.log.ok('-  Functions: ' + status.coverage.functions.pct + '%');
              grunt.log.ok('-  Branches: ' + status.coverage.branches.pct + '%');
            }
          }
          // All done!
          done();
        });
      });
    });

};
<commit_msg>Re-added syncing for htmlReport as reports were not being completed (ended at <body> tag).<commit_after>/*
 * grunt-contrib-qunit
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Nodejs libs.
  var path = require('path');
  var fs = require('fs');

  // External lib.
  var phantomjs = require('grunt-lib-phantomjs-istanbul').init(grunt);
  var istanbul = require('istanbul');
  var instrumenter = new istanbul.Instrumenter();
  var rimraf = require('rimraf');

  // Keep track of the last-started module, test and status.
  var currentModule, currentTest, status, generalOptions;
  // Keep track of the last-started test(s).
  var unfinished = {};
  // Get temp file path for covarage
  var tempFileCoverage = path.normalize(__dirname + '/../temp/coverage.tmp');
  // Get an asset file, local to the root of the project.
  var asset = path.join.bind(null, __dirname, '..');

  // Allow an error message to retain its color when split across multiple lines.
  var formatMessage = function(str) {
    return String(str).split('\n').map(function(s) { return s.magenta; }).join('\n');
  };

  // Keep track of failed assertions for pretty-printing.
  var failedAssertions = [];
  var logFailedAssertions = function() {
    var assertion;
    // Print each assertion error.
    while (assertion = failedAssertions.shift()) {
      grunt.verbose.or.error(assertion.testName);
      grunt.log.error('Message: ' + formatMessage(assertion.message));
      if (assertion.actual !== assertion.expected) {
        grunt.log.error('Actual: ' + formatMessage(assertion.actual));
        grunt.log.error('Expected: ' + formatMessage(assertion.expected));
      }
      if (assertion.source) {
        grunt.log.error(assertion.source.replace(/ {4}(at)/g, '  $1'));
      }
      grunt.log.writeln();
    }
  };

  // QUnit hooks.
  phantomjs.on('qunit.moduleStart', function(name) {
    unfinished[name] = true;
    currentModule = name;
  });

  phantomjs.on('qunit.moduleDone', function(name/*, failed, passed, total*/) {
    delete unfinished[name];
  });

  phantomjs.on('qunit.log', function(result, actual, expected, message, source) {
    if (!result) {
      failedAssertions.push({
        actual: actual, expected: expected, message: message, source: source,
        testName: currentTest
      });
    }
  });

  phantomjs.on('qunit.testStart', function(name) {
    currentTest = (currentModule ? currentModule + ' - ' : '') + name;
    grunt.verbose.write(currentTest + '...');
  });

  phantomjs.on('qunit.coverage', function(coverage) {
    if (coverage) {
      var Report = istanbul.Report;
      var Utils = istanbul.utils;
      var collector = new istanbul.Collector();
      var coverageOptions = generalOptions.coverage;

      // add coverage information to the collector
      collector.add(coverage);

      // store coverage data for cmd output
      status.coverage = Utils.summarizeCoverage(collector.getFinalCoverage());

      // check if a html report should be generated
      if (coverageOptions.htmlReport) {
        Report.create('html', {dir: coverageOptions.htmlReport}).writeReport(collector, true);
      }

      // check if a cobertura report should be generated
      if (coverageOptions.coberturaReport) {
        Report.create('cobertura', {dir: coverageOptions.coberturaReport}).writeReport(collector, true);
      }

      // check if a lcov report should be generated
      if (coverageOptions.lcovReport) {
        Report.create('lcov', {dir: coverageOptions.lcovReport}).writeReport(collector);
      }

      // delete the instrumented files
      rimraf.sync(generalOptions.transport.instrumentedFiles);
    }
  });

  phantomjs.on('qunit.testDone', function(name, failed/*, passed, total*/) {
    // Log errors if necessary, otherwise success.
    if (failed > 0) {
      // list assertions
      if (grunt.option('verbose')) {
        grunt.log.error();
        logFailedAssertions();
      } else {
        grunt.log.write('F'.red);
      }
    } else {
      grunt.verbose.ok().or.write('.');
    }
  });

  phantomjs.on('qunit.done', function(failed, passed, total, duration) {
    phantomjs.halt();
    status.failed += failed;
    status.passed += passed;
    status.total += total;
    status.duration += duration;
    // Print assertion errors here, if verbose mode is disabled.
    if (!grunt.option('verbose')) {
      if (failed > 0) {
        grunt.log.writeln();
        logFailedAssertions();
      } else {
        grunt.log.ok();
      }
    }
  });

  // Re-broadcast qunit events on grunt.event.
  phantomjs.on('qunit.*', function() {
    var args = [this.event].concat(grunt.util.toArray(arguments));
    grunt.event.emit.apply(grunt.event, args);
  });

  // Built-in error handlers.
  phantomjs.on('fail.load', function(url) {
    phantomjs.halt();
    grunt.verbose.write('Running PhantomJS...').or.write('...');
    grunt.log.error();
    grunt.warn('PhantomJS unable to load "' + url + '" URI.');
  });

  phantomjs.on('fail.timeout', function() {
    phantomjs.halt();
    grunt.log.writeln();
    grunt.warn('PhantomJS timed out, possibly due to a missing QUnit start() call.');
  });

  // Pass-through console.log statements.
  phantomjs.on('console', console.log.bind(console));

  grunt.registerMultiTask('qunit', 'Run QUnit unit tests in a headless PhantomJS instance.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      // Default PhantomJS timeout.
      timeout: 5000,
      // QUnit-PhantomJS bridge file to be injected.
      inject: asset('phantomjs/bridge.js'),
      // Explicit non-file URLs to test.
      urls: [],
      // Explicitly define all coverage options (as empty)
      coverage: {
        src: []
      }
    });

    // Combine any specified URLs with src files.
    var urls = options.urls.concat(this.filesSrc);

    // This task is asynchronous.
    var done = this.async();

    // Reset status.
    status = {failed: 0, passed: 0, total: 0, duration: 0, coverage: '-'};

    // expand files for coverage
    if (options.coverage && options.coverage.src && options.coverage.src.length) {
        options.coverage.include = grunt.file.expand(options.coverage.src);
        var instrumentedFiles = {};
    }

    grunt.util.async.forEachSeries(options.coverage.include, function (file, cb) {
      var filepath = fs.realpathSync(file);
      var fileStorage = filepath;

      // check if files will be delivered by a webserver
      if (options.urls && options.coverage && options.coverage.baseUrl) {
        fileStorage = path.relative(options.coverage.baseUrl, filepath);
      }

      // instrument the files that should be processed by istanbul
      if (options.coverage && options.coverage.instrumentedFiles) {
        instrumentedFiles[fileStorage] = instrumenter.instrumentSync(String(fs.readFileSync(filepath)), filepath);
      }

      cb();
    }, function (err, result) {
        // set transport options
        if (!options.transport) {
          options.transport = {};
        }

        // clear instrumented files folder & generate a new one
        if (options.coverage && options.coverage.instrumentedFiles) {
          if (!fs.existsSync(options.coverage.instrumentedFiles)) {
            grunt.file.mkdir(options.coverage.instrumentedFiles);
            options.transport.instrumentedFiles = options.coverage.instrumentedFiles;
          } else {
            options.transport.instrumentedFiles = fs.realpathSync(options.coverage.instrumentedFiles);
            rimraf.sync(options.transport.instrumentedFiles);
          }
        }

        // write instrumented file information to an temporary file
        // and transport the info to phantom
        if (options.coverage && options.coverage.instrumentedFiles) {
          grunt.file.write(tempFileCoverage, JSON.stringify(instrumentedFiles));
          options.transport.coverage = fs.realpathSync(tempFileCoverage);
        }

        // make options globally available
        generalOptions = options;

        // Process each filepath in-order.
        grunt.util.async.forEachSeries(urls, function(url, next) {
          var basename = path.basename(url);
          grunt.verbose.subhead('Testing ' + url).or.write('Testing ' + url);

          // Reset current module.
          currentModule = null;

          // Launch PhantomJS.
          grunt.event.emit('qunit.spawn', url);
          phantomjs.spawn(url, {
            // Additional PhantomJS options.
            options: options,
            // Do stuff when done.
            done: function(err) {
              if (err) {
                // If there was an error, abort the series.
                done();
              } else {
                // Otherwise, process next url.
                next();
              }
            },
          });
        },
        // All tests have been run.
        function() {
          // Log results.
          if (status.failed > 0) {
            grunt.warn(status.failed + '/' + status.total + ' assertions failed (' +
              status.duration + 'ms)');
          } else if (status.total === 0) {
            grunt.warn('0/0 assertions ran (' + status.duration + 'ms)');
          } else {
            grunt.verbose.writeln();
            grunt.log.ok(status.total + ' assertions passed (' + status.duration + 'ms)');

            // check if coverage was enable during the testrun
            if (status.coverage && status.coverage.lines) {
              grunt.log.ok('Coverage:');
              grunt.log.ok('-  Lines: ' + status.coverage.lines.pct + '%');
              grunt.log.ok('-  Statements: ' + status.coverage.statements.pct + '%');
              grunt.log.ok('-  Functions: ' + status.coverage.functions.pct + '%');
              grunt.log.ok('-  Branches: ' + status.coverage.branches.pct + '%');
            }
          }
          // All done!
          done();
        });
      });
    });

};
<|endoftext|>


<commit_before>import {
  createSimpleFunctional
} from '../../util/helpers'

import VTabs from './VTabs'
import VTabsItem from './VTabsItem'
import VTabsItems from './VTabsItemS'
import VTabsContent from './VTabsContent'
import VTabsBar from './VTabsBar'

VTabs.install = function install (Vue) {
  const VTabsSlider = createSimpleFunctional('tabs__slider', 'li')

  Vue.component(VTabs.name, VTabs)
  Vue.component(VTabsBar.name, VTabsBar)
  Vue.component(VTabsContent.name, VTabsContent)
  Vue.component(VTabsItem.name, VTabsItem)
  Vue.component(VTabsSlider.name, VTabsSlider)
  Vue.component(VTabsItems.name, VTabsItems)
}

export default VTabs
<commit_msg>fixed import<commit_after>import {
  createSimpleFunctional
} from '../../util/helpers'

import VTabs from './VTabs'
import VTabsItem from './VTabsItem'
import VTabsItems from './VTabsItems'
import VTabsContent from './VTabsContent'
import VTabsBar from './VTabsBar'

VTabs.install = function install (Vue) {
  const VTabsSlider = createSimpleFunctional('tabs__slider', 'li')

  Vue.component(VTabs.name, VTabs)
  Vue.component(VTabsBar.name, VTabsBar)
  Vue.component(VTabsContent.name, VTabsContent)
  Vue.component(VTabsItem.name, VTabsItem)
  Vue.component(VTabsSlider.name, VTabsSlider)
  Vue.component(VTabsItems.name, VTabsItems)
}

export default VTabs
<|endoftext|>


<commit_before>/*
 * grunt-react
 * https://github.com/ericclemmons/grunt-react
 *
 * Copyright (c) 2013 Eric Clemmons, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var path = require('path');
  var transform = require('react-tools').transform;

  grunt.registerMultiTask('react', 'Compile Facebook React JSX templates into JavaScript', function() {
    var done = this.async();

    var options = this.options();
    grunt.verbose.writeflags(options, 'Options');

    if (this.files.length < 1) {
      grunt.verbose.warn('Destination not written because no source files were provided.');
    }

    grunt.util.async.forEachSeries(this.files, function(f, nextFileObj) {
      var destFile = f.dest;

      var files = f.src.filter(function(filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      });

      if (files.length === 0) {
        if (f.src.length < 1) {
          grunt.log.warn('Destination not written because no source files were found.');
        }

        // No src files, go to next target. Warn would have been issued above.
        return nextFileObj();
      }

      var compiled = [];
      grunt.util.async.concatSeries(files, function(file, next) {
        grunt.log.writeln('[react] Compiling ' + file.cyan + ' --> ' + destFile.cyan);

        try {
          compiled.push(transform(grunt.file.read(file)));
          next();
        } catch (e) {
          var error = grunt.log.wordlist(['[react] ' + e], { color: 'red' });
          grunt.log.error(error);
          nextFileObj(error);
        }
      }, function () {
        grunt.file.write(destFile, compiled.join(grunt.util.normalizelf(grunt.util.linefeed)));
        grunt.log.writeln('[react] File ' + destFile.cyan + ' created.');
        nextFileObj();
      });

    }, done);
  });
};
<commit_msg>Throw a proper error when something goes wrong.<commit_after>/*
 * grunt-react
 * https://github.com/ericclemmons/grunt-react
 *
 * Copyright (c) 2013 Eric Clemmons, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var path = require('path');
  var transform = require('react-tools').transform;

  grunt.registerMultiTask('react', 'Compile Facebook React JSX templates into JavaScript', function() {
    var done = this.async();

    var options = this.options();
    grunt.verbose.writeflags(options, 'Options');

    if (this.files.length < 1) {
      grunt.verbose.warn('Destination not written because no source files were provided.');
    }

    grunt.util.async.forEachSeries(this.files, function(f, nextFileObj) {
      var destFile = f.dest;

      var files = f.src.filter(function(filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      });

      if (files.length === 0) {
        if (f.src.length < 1) {
          grunt.log.warn('Destination not written because no source files were found.');
        }

        // No src files, go to next target. Warn would have been issued above.
        return nextFileObj();
      }

      var compiled = [];
      grunt.util.async.concatSeries(files, function(file, next) {
        grunt.log.writeln('[react] Compiling ' + file.cyan + ' --> ' + destFile.cyan);

        try {
          compiled.push(transform(grunt.file.read(file)));
          next();
        } catch (e) {
          grunt.fail.warn(e);
        }
      }, function () {
        grunt.file.write(destFile, compiled.join(grunt.util.normalizelf(grunt.util.linefeed)));
        grunt.log.writeln('[react] File ' + destFile.cyan + ' created.');
        nextFileObj();
      });

    }, done);
  });
};
<|endoftext|>


<commit_before>/*
 * grunt-serve
 * https://github.com/lud2k/grunt-serve
 *
 * Copyright (c) 2014 Ludovic Cabre
 * Licensed under the MIT license.
 */

'use strict';

var	childProcess = require("child_process"),
	fs = require('fs'),
	dot = require('dot'),
	paths = require('path'),
	contentTypes = require('../data/content_types.js'),
	jwt = require('jsonwebtoken'),
	express = require('express'),
	app = express(),
	server;
// requires

// load all template files
var loadTemplate = function(name) {
		return dot.template(fs.readFileSync(paths.join(__dirname, '..', 'pages', name)))
	},
	indexTmpl = loadTemplate('index.html'),
	notFoundTmpl = loadTemplate('not_found.html'),
	directoryTmpl = loadTemplate('directory.html'),
	errorTmpl = loadTemplate('error.html'),
	successTmpl = loadTemplate('success.html'),
	gruntErrorTmpl = loadTemplate('grunt_error.html'),
	missingTmpl = loadTemplate('missing.html'),
	unauthTmpl = loadTemplate('unauthorized.html');

/**
 * Definition of the exported method that will be called by Grunt on initialization.
 */
module.exports = function(grunt) {

	grunt.registerTask('_serve_selftest', 'Test grunt serve', function(){
		grunt.log.write('task testing successful');
	});

	//Aufrufen mit /task/serve_selfupdate:<url>
	grunt.registerTask('_serve_selfupdate', 'Updates the Repo and start serve again', function() {
		var options = this.options({
			localrepo: './',
			linkrepo: 'defaultLink'
		})
		if(options.linkrepo == ''){
			grunt.log.write('no link');
		} else{
			/*grunt.log.write('ich will mal was tolles machen \n');
			git().pull(function(err, update) {
				grunt.log.write('ich habe gepullt (: \n')
				if(update){
					grunt.log.write('ich habe ein update gemacht (: \n');
					//beende serve
					//process.exit(1);
				}
			});*/
			grunt.log.write('link: '+ options.link);
			grunt.log.write('local: '+ options.localrepo);
		}
	})
	// register serve task
	grunt.registerTask('serve', 'Starts a http server that can be called to run tasks.', function() {
		// control when the task should end
	    var done = this.async();

		// get options
		var options = this.options({
			port: 9000,
			keypath: './public.pem',
			silently: false,
			serve: {
				path: process.cwd()
			}
		});

		app.get ('/', function(req, res) {
			try{
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'});
					} else{
						// forward request
						render(res, 200, indexTmpl, {
							host: req.headers.host,
							aliases: mapToArray(options.aliases, 'name'),
							files: filesInDirectory(grunt, options, '.'),
						}, {info: 'OK'});
					}
				});
			} catch (e) {
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'});
			}
		});

		app.get ('/task/:taskname', function(req, res) {
			try {
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'} );
					} else{
						var tasks = req.params.taskname.split(','),
						output = null;

						// run tasks
						executeTasks(req, res, grunt, options, tasks, output, null);
						return;
					}
				});
			} catch(e) {
				// show error
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'});
			}
		});

		server = app.listen(options.port);

		// handle SIGINT signal properly
		process.on('SIGINT', function() {
			// terminate task
		    done();
		});
    	// a few messages
		grunt.log.write('Server is running on port '+options.port+'...\n');
		grunt.log.write('Press CTRL+C at any time to terminate it.\n');
	});
	grunt.registerTask('showTasks', 'show tasks', function(){
		displayTasks(grunt);
	});
}

/**
 * Handles all requests to the server.
 * Each call with trigger a call to the following function.
 */

/*
function handleRequest(request, response, grunt, options) {

	// is this url contains virtual root? If so, remove it
	if (options.virtualRoot) {
		if (path.indexOf(options.virtualRoot) === 0) {
			path = path.substr(options.virtualRoot.length);
		}
	}

	// does this path match an alias?
	var aliasName = path.substr(1);
	var aliases = options.aliases;
	if (aliases && aliases[aliasName]) {
		// get alias configuration
		var tasks = aliases[aliasName].tasks,
			output = aliases[aliasName].output,
			contentType = aliases[aliasName].contentType;

		if (!tasks) throw "No tasks were defined for alias: "+aliasName;

		// run tasks
		executeTasks(request, response, grunt, options, tasks, output, contentType);
		return;
	}
}
*/

function displayTasks(grunt){
	var tasks = grunt.task._tasks;
	console.dir(tasks);
	for (var task in tasks) {
		console.dir(tasks.task);
	}
}

/**
 * Runs Grunt to execute the given tasks.
 */
function executeTasks(request, response, grunt, options, tasks, output, contentType) {
	// execute tasks
	childProcess.exec('grunt '+tasks.join(' '), function(error, stdout, stderr) {
		try {
			// should we print the stdout?
			if (!options.silently) {
				// print stdout
				console.log(stdout);

				// print stderr (if any)
				if (stderr) {
					console.log(stderr);
				}
			}

			// any error? write logs and return
			if (stderr || error) {
			    render(response, 500, gruntErrorTmpl, {
			    	tasks: tasks,
			    	stdout: formatStdout(stdout),
			    	stderr: formatStdout(stderr)
			    }, {info: 'Error'});
				return;
			}

		    // the the output stdout?
		    if (output == 'stdout' || !output) {
			    // write stdout
		    	render(response, 200, successTmpl, {
		    		output: formatStdout(stdout)
		    	}, {info: 'OK'});

		    } else {
		    	// requested output file exists?
				if (grunt.file.exists(output)) {
					// write file
		    		write(response, 200, grunt, output, contentType);
				} else {
					// show file not found
				    render(response, 500, missingTmpl, {
				    	output: output
				    } , {info: 'Error'});
				}
		    }
		} catch(e) {
			// show error
		    render(response, 500, errorTmpl, {
		    	error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
		    }, {info: 'Error'});
		}
	});
}

/**
 * Renders a json response.
 */
function render(response, code, template, data, info) {
	var json = JSON.stringify({
		statusCode : code,
		text: info
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var json = JSON.stringify({
		statusCode : code,
		templ : template,
		text: "test123"
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var html = template(data);
	if (!response.headersSent) {
	    response.writeHead(code, {"Content-Type": "text/html"});
	}
    response.end(html);
}
*/

/**
 * Writes a file's content to the output and ends the request.
 */
function write(response, code, grunt, file, contentType) {
	var data = fs.readFileSync(file);
	if (!response.headersSent) {
	    response.writeHead(200, headersForOutput(file, contentType));
	}
	response.end(data);
}

/**
 * Converts a map to an array adding the key to the value.
 */
function mapToArray(map, name) {
	var ret = [];
	for (var key in map) {
		map[key][name] = key;
		ret.push(map[key]);
	}
	return ret;
}

/**
 * Returns the list of files in the given directory.
 */
function filesInDirectory(grunt, options, path) {
	var ret = [],
		fullPath = paths.join(options.serve.path, path),
		files = fs.readdirSync(fullPath);

	// for each file
	for (var i=0; i<files.length; i++) {
		var file = files[i],
			stats = fs.statSync(paths.join(fullPath, file)),
			isDir = stats.isDirectory();

		// skip ., .. and hidden files
		if (file.charAt(0) == '.') continue;

		ret.push({
			path: path ? path + '/' + file : file,
			name: file,
			isDir: isDir
		});
	}

	return ret;
}

/**
 * Returns the headers that fits the best the output.
 * Will also add headers to prevent caching.
 */
function headersForOutput(path, contentType) {
	// disable caching
	var ret = {
		'Cache-Control': 'no-cache, no-store, must-revalidate',
		'Pragma': 'no-cache',
		'Expires': '0'
	}

	// try to auto detect the content type
	if (!contentType) {
		contentType = contentTypes(path);
		if (contentType) {
			ret['Content-Type'] = contentType;
		}
	}

	return ret;
}

/**
 * Converts Grunt's stdout into html.
 * (keeping the colors the same)
 */
function formatStdout(stdout) {
	var regex = /\x1B\[(\d+)m/g,
		opened = false,
		colors = {
			'0': '#000000',
			'30': '#000000',
			'31': '#CC0000',
			'32': '#00CC00',
			'33': '#CCCC00',
			'34': '#00CC00',
			'35': '#CC00CC',
			'36': '#00CCCC',
			'37': '#999999'
		},
		match;

	// replace all colors markers by html
	while ((match = regex.exec(stdout))) {
		var code = match[1]+'',
			start = stdout.substr(0, match.index),
			end = stdout.substr(match.index+3+code.length);

		if (code) {
			var colorEnd = opened ? '' : '',
				colorStart = '';
			stdout = start + colorEnd + colorStart + end;

		} else {
			stdout = start + end;
		}

		opened = true;
	}

	// replace all line return by the html equivalent
	return stdout.replace(/\n+/g, '
');
}
<commit_msg>change showTasks<commit_after>/*
 * grunt-serve
 * https://github.com/lud2k/grunt-serve
 *
 * Copyright (c) 2014 Ludovic Cabre
 * Licensed under the MIT license.
 */

'use strict';

var	childProcess = require("child_process"),
	fs = require('fs'),
	dot = require('dot'),
	paths = require('path'),
	contentTypes = require('../data/content_types.js'),
	jwt = require('jsonwebtoken'),
	express = require('express'),
	app = express(),
	server;
// requires

// load all template files
var loadTemplate = function(name) {
		return dot.template(fs.readFileSync(paths.join(__dirname, '..', 'pages', name)))
	},
	indexTmpl = loadTemplate('index.html'),
	notFoundTmpl = loadTemplate('not_found.html'),
	directoryTmpl = loadTemplate('directory.html'),
	errorTmpl = loadTemplate('error.html'),
	successTmpl = loadTemplate('success.html'),
	gruntErrorTmpl = loadTemplate('grunt_error.html'),
	missingTmpl = loadTemplate('missing.html'),
	unauthTmpl = loadTemplate('unauthorized.html');

/**
 * Definition of the exported method that will be called by Grunt on initialization.
 */
module.exports = function(grunt) {

	grunt.registerTask('_serve_selftest', 'Test grunt serve', function(){
		grunt.log.write('task testing successful');
	});

	//Aufrufen mit /task/serve_selfupdate:<url>
	grunt.registerTask('_serve_selfupdate', 'Updates the Repo and start serve again', function() {
		var options = this.options({
			localrepo: './',
			linkrepo: 'defaultLink'
		})
		if(options.linkrepo == ''){
			grunt.log.write('no link');
		} else{
			/*grunt.log.write('ich will mal was tolles machen \n');
			git().pull(function(err, update) {
				grunt.log.write('ich habe gepullt (: \n')
				if(update){
					grunt.log.write('ich habe ein update gemacht (: \n');
					//beende serve
					//process.exit(1);
				}
			});*/
			grunt.log.write('link: '+ options.link);
			grunt.log.write('local: '+ options.localrepo);
		}
	})
	// register serve task
	grunt.registerTask('serve', 'Starts a http server that can be called to run tasks.', function() {
		// control when the task should end
	    var done = this.async();

		// get options
		var options = this.options({
			port: 9000,
			keypath: './public.pem',
			silently: false,
			serve: {
				path: process.cwd()
			}
		});

		app.get ('/', function(req, res) {
			try{
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'});
					} else{
						// forward request
						render(res, 200, indexTmpl, {
							host: req.headers.host,
							aliases: mapToArray(options.aliases, 'name'),
							files: filesInDirectory(grunt, options, '.'),
						}, {info: 'OK'});
					}
				});
			} catch (e) {
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'});
			}
		});

		app.get ('/task/:taskname', function(req, res) {
			try {
				var cert = fs.readFileSync(options.keypath);
				var token = req.headers.webtoken;
				jwt.verify(token,cert,{algorithms: ['RS256']}, function(err, payload){
					if(err){
						err = {
							name: 'JsonWebTokenError',
							message: 'invalid signature'
						}
						render(res, 401, unauthTmpl, null, {info: 'unauthorized'} );
					} else{
						var tasks = req.params.taskname.split(','),
						output = null;

						// run tasks
						executeTasks(req, res, grunt, options, tasks, output, null);
						return;
					}
				});
			} catch(e) {
				// show error
				render(res, 500, errorTmpl, {
					error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
				}, {info: 'Error'});
			}
		});

		server = app.listen(options.port);

		// handle SIGINT signal properly
		process.on('SIGINT', function() {
			// terminate task
		    done();
		});
    	// a few messages
		grunt.log.write('Server is running on port '+options.port+'...\n');
		grunt.log.write('Press CTRL+C at any time to terminate it.\n');
	});
	grunt.registerTask('showTasks', 'show tasks', function(){
		displayTasks(grunt);
	});
}

/**
 * Handles all requests to the server.
 * Each call with trigger a call to the following function.
 */

/*
function handleRequest(request, response, grunt, options) {

	// is this url contains virtual root? If so, remove it
	if (options.virtualRoot) {
		if (path.indexOf(options.virtualRoot) === 0) {
			path = path.substr(options.virtualRoot.length);
		}
	}

	// does this path match an alias?
	var aliasName = path.substr(1);
	var aliases = options.aliases;
	if (aliases && aliases[aliasName]) {
		// get alias configuration
		var tasks = aliases[aliasName].tasks,
			output = aliases[aliasName].output,
			contentType = aliases[aliasName].contentType;

		if (!tasks) throw "No tasks were defined for alias: "+aliasName;

		// run tasks
		executeTasks(request, response, grunt, options, tasks, output, contentType);
		return;
	}
}
*/

function displayTasks(grunt){
	var tasks = grunt.task._tasks;
	console.dir(tasks);
	for (var task in tasks) {
		console.dir(tasks.task);
		console.dir(task.options);
	}
}

/**
 * Runs Grunt to execute the given tasks.
 */
function executeTasks(request, response, grunt, options, tasks, output, contentType) {
	// execute tasks
	childProcess.exec('grunt '+tasks.join(' '), function(error, stdout, stderr) {
		try {
			// should we print the stdout?
			if (!options.silently) {
				// print stdout
				console.log(stdout);

				// print stderr (if any)
				if (stderr) {
					console.log(stderr);
				}
			}

			// any error? write logs and return
			if (stderr || error) {
			    render(response, 500, gruntErrorTmpl, {
			    	tasks: tasks,
			    	stdout: formatStdout(stdout),
			    	stderr: formatStdout(stderr)
			    }, {info: 'Error'});
				return;
			}

		    // the the output stdout?
		    if (output == 'stdout' || !output) {
			    // write stdout
		    	render(response, 200, successTmpl, {
		    		output: formatStdout(stdout)
		    	}, {info: 'OK'});

		    } else {
		    	// requested output file exists?
				if (grunt.file.exists(output)) {
					// write file
		    		write(response, 200, grunt, output, contentType);
				} else {
					// show file not found
				    render(response, 500, missingTmpl, {
				    	output: output
				    } , {info: 'Error'});
				}
		    }
		} catch(e) {
			// show error
		    render(response, 500, errorTmpl, {
		    	error: 'Unexpected JavaScript exception "'+e+'"
'+(e && e.stack ? e.stack.replace(/\n+/g, '
') : '')
		    }, {info: 'Error'});
		}
	});
}

/**
 * Renders a json response.
 */
function render(response, code, template, data, info) {
	var json = JSON.stringify({
		statusCode : code,
		text: info
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var json = JSON.stringify({
		statusCode : code,
		templ : template,
		text: "test123"
	})
	if (!response.headersSent) {
		response.writeHead(code, {"Content-Type": "application/json"});
	}
    response.end(json);
}

/**
 * Renders a html page and ends the request.
 */

/*
function render(response, code, template, data) {
	var html = template(data);
	if (!response.headersSent) {
	    response.writeHead(code, {"Content-Type": "text/html"});
	}
    response.end(html);
}
*/

/**
 * Writes a file's content to the output and ends the request.
 */
function write(response, code, grunt, file, contentType) {
	var data = fs.readFileSync(file);
	if (!response.headersSent) {
	    response.writeHead(200, headersForOutput(file, contentType));
	}
	response.end(data);
}

/**
 * Converts a map to an array adding the key to the value.
 */
function mapToArray(map, name) {
	var ret = [];
	for (var key in map) {
		map[key][name] = key;
		ret.push(map[key]);
	}
	return ret;
}

/**
 * Returns the list of files in the given directory.
 */
function filesInDirectory(grunt, options, path) {
	var ret = [],
		fullPath = paths.join(options.serve.path, path),
		files = fs.readdirSync(fullPath);

	// for each file
	for (var i=0; i<files.length; i++) {
		var file = files[i],
			stats = fs.statSync(paths.join(fullPath, file)),
			isDir = stats.isDirectory();

		// skip ., .. and hidden files
		if (file.charAt(0) == '.') continue;

		ret.push({
			path: path ? path + '/' + file : file,
			name: file,
			isDir: isDir
		});
	}

	return ret;
}

/**
 * Returns the headers that fits the best the output.
 * Will also add headers to prevent caching.
 */
function headersForOutput(path, contentType) {
	// disable caching
	var ret = {
		'Cache-Control': 'no-cache, no-store, must-revalidate',
		'Pragma': 'no-cache',
		'Expires': '0'
	}

	// try to auto detect the content type
	if (!contentType) {
		contentType = contentTypes(path);
		if (contentType) {
			ret['Content-Type'] = contentType;
		}
	}

	return ret;
}

/**
 * Converts Grunt's stdout into html.
 * (keeping the colors the same)
 */
function formatStdout(stdout) {
	var regex = /\x1B\[(\d+)m/g,
		opened = false,
		colors = {
			'0': '#000000',
			'30': '#000000',
			'31': '#CC0000',
			'32': '#00CC00',
			'33': '#CCCC00',
			'34': '#00CC00',
			'35': '#CC00CC',
			'36': '#00CCCC',
			'37': '#999999'
		},
		match;

	// replace all colors markers by html
	while ((match = regex.exec(stdout))) {
		var code = match[1]+'',
			start = stdout.substr(0, match.index),
			end = stdout.substr(match.index+3+code.length);

		if (code) {
			var colorEnd = opened ? '' : '',
				colorStart = '';
			stdout = start + colorEnd + colorStart + end;

		} else {
			stdout = start + end;
		}

		opened = true;
	}

	// replace all line return by the html equivalent
	return stdout.replace(/\n+/g, '
');
}
<|endoftext|>


<commit_before>import express from 'express';
import bodyParser from 'body-parser';
import env from 'dotenv';
import webpack from 'webpack';
import { createServer } from 'http';
import webpackMiddleware from 'webpack-dev-middleware';
import routes from './routes/index';
import webpackConfig from '../webpack.config';
import SocketController from './socket/socketController';

env.config();
const app = express();
const server = createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

// Middlewares used
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, x-access-token');
  next();
});

app.use(webpackMiddleware(webpack(webpackConfig)));
app.use(express.static('dist'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api/v1/', routes);

app.get('*', (req, res) => {
  res.sendFile(`${process.cwd()}/dist/index.html`);
});
server.listen(port, () => {
  console.log(`Listening on port ${port} in ${app.get('env')}`);
});
SocketController.init(io);
export default server;
<commit_msg>serve only static files<commit_after>import express from 'express';
import bodyParser from 'body-parser';
import env from 'dotenv';
import webpack from 'webpack';
import { createServer } from 'http';
import webpackMiddleware from 'webpack-dev-middleware';
import routes from './routes/index';
import webpackConfig from '../webpack.config';
import SocketController from './socket/socketController';

env.config();
const app = express();
const server = createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

// Middlewares used
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, x-access-token');
  next();
});

app.use(express.static('dist'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api/v1/', routes);

app.get('*', (req, res) => {
  res.sendFile(`${process.cwd()}/dist/index.html`);
});
server.listen(port, () => {
  console.log(`Listening on port ${port} in ${app.get('env')}`);
});
SocketController.init(io);
export default server;
<|endoftext|>


<commit_before>'use strict'
import React from 'react'
import lang from 'i18n/lang'

let FileSaveAs = React.createClass({
  onChange: function (e) {
    let newName = e.target.value + '.spj'
    if (newName !== this.props.deck._fn && Object.keys(localStorage).indexOf(newName) >= 0) {
      this.refs.errorMsg.innerHTML = lang.duplicatedFileNameErr
    }
    else if (newName.length === 4) {
      this.refs.errorMsg.innerHTML = lang.emptyFileNameErr
    }
    else {
      this.refs.errorMsg.innerHTML = ''
    }
  },
  onOk: function () {
    this.props.onNewDeck(this.refs.fname.value + '.spj', this.props.deck)
  },
  render: function () {
    return

        X

Save As ...

        <input type="text" name="fname" onChange={this.onChange}
               defaultValue={this.props.deck._fn.replace(/\.spj$/,'')} ref="fname"></input>.spj

        {lang.btnOk}

        {lang.btnCancel}

  }
})
module.exports = FileSaveAs
<commit_msg>added todo<commit_after>'use strict'
import React from 'react'
import lang from 'i18n/lang'

let FileSaveAs = React.createClass({
  onChange: function (e) {
    let newName = e.target.value + '.spj'
    if (newName !== this.props.deck._fn && Object.keys(localStorage).indexOf(newName) >= 0) {
      this.refs.errorMsg.innerHTML = lang.duplicatedFileNameErr
    }
    else if (newName.length === 4) {
      this.refs.errorMsg.innerHTML = lang.emptyFileNameErr
    }
    else {
      this.refs.errorMsg.innerHTML = ''
    }
  },
  onOk: function () {
    // TODO: delete duplicated file if exists
    this.props.onNewDeck(this.refs.fname.value + '.spj', this.props.deck)
  },
  render: function () {
    return

        X

Save As ...

        <input type="text" name="fname" onChange={this.onChange}
               defaultValue={this.props.deck._fn.replace(/\.spj$/,'')} ref="fname"></input>.spj

        {lang.btnOk}

        {lang.btnCancel}

  }
})
module.exports = FileSaveAs
<|endoftext|>


<commit_before><commit_msg>Removed EBBI, NBI indexes from frontend.<commit_after><|endoftext|>


<commit_before>import homeReducer from '../app/Resources/js/reducers/homeReducer'
import Constants from '../app/Resources/js/constants/home'
import { getYmdStr } from '../app/Resources/js/utils/util'

const initialState = {
    fetching: false,
    timelineJson: {},
    username: '',
    currentDate: getYmdStr(new Date())
}

describe('homeReducer', () => {
    it('undefined Action', () => {
        expect(homeReducer(initialState, {})).toEqual(
            initialState
        )
    })
    it('AJAX_FETCH_START', () => {
        initialState.fetching = true
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.AJAX_FETCH_START
        })).toEqual(
            expectState
        )
    })
    it('FETCH_SINGLE_DATE', () => {
        initialState.fetching = false
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.FETCH_SINGLE_DATE,
            timelineJson: {},
            currentDate: initialState.currentDate
        })).toEqual(
            expectState
        )
    })
    it('DONE_IMPORT', () => {
        initialState.isShowImportModal = false
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.DONE_IMPORT,
            currentDate: initialState.currentDate
        })).toEqual(
            expectState
        )
    })
})
<commit_msg>:green_apple:<commit_after>import homeReducer from '../app/Resources/js/reducers/homeReducer'
import Constants from '../app/Resources/js/constants/home'
import { getYmdStr } from '../app/Resources/js/utils/util'

const initialState = {
    fetching: false,
    timelineJson: {},
    username: '',
    currentDate: getYmdStr(new Date())
}

describe('homeReducer', () => {
    it('undefined Action', () => {
        expect(homeReducer(initialState, {})).toEqual(
            initialState
        )
    })
    it('AJAX_FETCH_START', () => {
        initialState.fetching = true
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.AJAX_FETCH_START
        })).toEqual(
            expectState
        )
    })
    it('FETCH_SINGLE_DATE', () => {
        initialState.fetching = false
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.FETCH_SINGLE_DATE,
            timelineJson: {},
            currentDate: initialState.currentDate
        })).toEqual(
            expectState
        )
    })
    it('DONE_IMPORT', () => {
        initialState.isShowImportModal = false
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.DONE_IMPORT,
            currentDate: initialState.currentDate
        })).toEqual(
            expectState
        )
    })
    it('SET_CURRENT_DATE', () => {
        initialState.currentDate = '2020-12-20'
        const expectState = initialState

        expect(homeReducer(initialState, {
            type: Constants.SET_CURRENT_DATE,
            currentDate: '2020-12-20'
        })).toEqual(
            expectState
        )
    })
})
<|endoftext|>