<commit_before>// fileserver
var bodyParser = require('body-parser');
var fileDriver = require('./fsDriver.js');
var url = require('url');
var mime = require('mime');
var path = require('path');
var mw = require('dat-middleware');
var flow = require('middleware-flow');
var morgan = require('morgan');
var error = require('debug')('rest-fs:fileserver');

var fileserver = function(app) {
  if (!app) {
    throw new Error('express app required');
  }

  app.set('etag', 'strong');
  app.use(require('express-domain-middleware'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(morgan('combined', {
    skip: function () { return process.env.LOG !== 'true'; }
  }));
  app.get(/^\/.+\/$/, getDir);
  app.get(/^\/.+[^\/]$/, getFile);
  app.post("/*", postFileOrDir);
  app.put("/*", putFileOrDir);
  app.delete(/^\/.+\/$/, delDir);
  app.delete(/^\/.+[^\/]$/, delFile);
  app.use(function (err, req, res, next)  {
    error('uncaught error', err.stack);
    var outErr = {
      message: err.message,
      stack: err.stack
    };
    res.status(500).send(outErr);
  });
  return app;
};

/* GET
  /path/to/dir/
  list contents of directory

  *optional*
  ?recursive = list recursively default false

  return: list of files/dirs
  res.body = [
    {
      "fullFilePath"
    }, ...
  ]
*/
var getDir = function (req, res, next) {
  if (req.query.stat) {
    return statFile(req, res, next);
  }

  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isRecursive = req.query.recursive || "false";

  var handList = function (err, files) {
    if (err && err.code === 'ENOTDIR') {
      // this this is a file, redirect to file path
      var originalUrl = url.parse(req.originalUrl);
      originalUrl.pathname = originalUrl.pathname.substr(0, originalUrl.pathname.length - 1);
      var target = url.format(originalUrl);
      res.statusCode = 303;
      res.setHeader('Location', target);
      return res.end('Redirecting to ' + target);
    }
    if (files) {
      for (var i = files.length - 1; i >= 0; i--) {
        files[i] = formatOutData(req, files[i]);
      }
    }
    sendCode(200, req, res, next, files)(err);
  };

  if (isRecursive === "true") {
    return fileDriver.listAll(dirPath, handList);
  } else {
    return fileDriver.list(dirPath, handList);
  }
};

/* GET
  /path/to/file
  return contents of file
  if dir, redirect to dir path

  *optional*
  ?encoding = default utf8

  return: data of file
  res.body = {"content of specified file"}
*/
var getFile = function (req, res, next) {
  if (req.query.stat) {
    return statFile(req, res, next);
  }

  var filePath = decodeURI(url.parse(req.url).pathname);
  var encoding = req.query.encoding || 'utf8';
  fileDriver.readFile(filePath, encoding, function(err, data) {
    if (err && err.code === 'EISDIR') {
      // this this is a dir, redirect to dir path
      var originalUrl = url.parse(req.originalUrl);
      originalUrl.pathname += '/';
      var target = url.format(originalUrl);
      res.statusCode = 303;
      res.setHeader('Location', target);
      return res.end('Redirecting to ' + target);
    }

    res.set('content-type', mime.lookup(filePath));
    sendCode(200, req, res, next, data)(err);
  });
};

/* POST
  /path/to/file/or/dir
  creates or overwrites file
  creates dir if it does not exisit.
  renames or moves file if newPath exists
  *optional*
  body.newPath = if exist, move/rename file to this location.
  body.clobber = if true will overwrite dest files (default false)
  body.mkdirp = if true will create path to new location (default false)

  body.mode = permissons of file (defaults: file 438(0666) dir 511(0777))
  body.encoding = default utf8

  returns: modified resource
  res.body = {
    "fullFilePath" or dir
  }
*/
var postFileOrDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isDir = dirPath.substr(-1) == '/';
  var options = {};
  var isJson = false;
  if (typeof req.headers['content-type'] === 'string') {
    isJson = ~req.headers['content-type'].indexOf('application/json') === -1 ? true : false;
  }
  // move/rename if newPath exists
  if (req.body.newPath) {
    options.clobber = req.body.clobber || false;
    options.mkdirp = req.body.mkdirp || false;
    return fileDriver.move(dirPath, req.body.newPath, options,
      sendCode(200, req, res, next, formatOutData(req, req.body.newPath)));
  }

  if (isDir) {
    var mode = req.body.mode || 511;
    return fileDriver.mkdir(dirPath, mode,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }

  if (!isJson) {
    // default is to not clobber
    options.encoding = req.query.encoding  || 'utf8';
    options.mode = req.query.mode || 438;
    options.flags =  req.query.clobber === 'true' ? 'w' : 'wx';

    return fileDriver.writeFileStream(dirPath, req, options,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }

  options.encoding = req.body.encoding  || 'utf8';
  options.mode = req.body.mode || 438;
  var data = req.body.content || '';
  fileDriver.writeFile(dirPath, data, options,
    sendCode(201, req, res, next, formatOutData(req, dirPath)));
};

/* PUT
  /path/to/file/or/dir
  make file or dir

  *optional*
  body.mode = permissons of file (438 default 0666 octal)
  body.encoding = default utf8

  returns: modified resource
  res.body = {
    "fullFilePath"
  }
*/
var putFileOrDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isDir = dirPath.substr(-1) == '/';
  var options = {};

  if (isDir) {
    var mode = req.body.mode || 511;
    fileDriver.mkdir(dirPath, mode,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  } else {
    options.encoding = req.body.encoding  || 'utf8';
    options.mode = req.body.mode  || 438;
    var data = req.body.content || '';
    fileDriver.writeFile(dirPath, data, options,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }
};

/* DEL
  /path/to/dir/
  deletes dir
  *optional*
  body.clobber = will remove non-empty dir (defaut: false)

  return:
  res.body = {}
*/
var delDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var clobber = req.body.clobber  || false;
  fileDriver.rmdir(dirPath, clobber, sendCode(200, req, res, next, {}));
};

/* DEL
  /path/to/file
  deletes file

  return:
  res.body = {}
*/
var delFile = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  fileDriver.unlink(dirPath, sendCode(200, req, res, next, {}));
};

/* GET
  /path/to/dir/or/file
  Returns stats for a file

  return: stats for the file as determined by node
  res.body = {
    dev: 16777220,
    mode: 16877,
    nlink: 31,
    uid: 501,
    gid: 20,
    rdev: 0,
    blksize: 4096,
    ino: 604862,
    size: 1054,
    blocks: 0,
    atime: Thu Mar 05 2015 11:38:47 GMT-0800 (PST),
    mtime: Thu Mar 05 2015 10:52:41 GMT-0800 (PST),
    ctime: Thu Mar 05 2015 10:52:41 GMT-0800 (PST),
    birthtime: Mon Mar 02 2015 10:55:37 GMT-0800 (PST)
  }
*/
var statFile = function (req, res, next) {
  var filePath = decodeURI(url.parse(req.url).pathname);
  fileDriver.stat(filePath, function(err, stats) {
    if (err) { return responseError(req, res, next, err); }
    res.status(200).json(stats);
  });
}

// Helpers

// formats out data based on client spec.
var formatOutData = function (req, filepath) {
  var out = filepath;
  if (typeof req.modifyOut === 'function') {
    out = req.modifyOut(out);
  }
  return out;
};

var responseError = function(req, res, next, err) {
  error('ERROR', req.url, err);
  code = 500;
  out = {
    errno: err.errno,
    code: err.code,
    path: err.path,
    message: err.message,
    stack: err.stack
  };

  if (err.code === 'ENOENT') {
    code = 404;
  } if (err.code === 'EPERM') {
    code = 403;
  } if (err.code === 'ENOTDIR' ||
        err.code === 'EISDIR') {
    code = 400;
  } if (err.code === 'ENOTEMPTY' ||
        err.code === 'EEXIST' ||
        err.code === 'EINVAL') {
    code = 409;
  }

  res.status(code).send(out);
}

var sendCode = function(code, req, res, next, out) {
  return function (err) {
    if (err) { return responseError(req, res, next, err); }
    res.status(code).send(out);
  };
};

module.exports = fileserver;
<commit_msg>Reverted sendCode, no more tears.<commit_after>// fileserver
var bodyParser = require('body-parser');
var fileDriver = require('./fsDriver.js');
var url = require('url');
var mime = require('mime');
var path = require('path');
var mw = require('dat-middleware');
var flow = require('middleware-flow');
var morgan = require('morgan');
var error = require('debug')('rest-fs:fileserver');

var fileserver = function(app) {
  if (!app) {
    throw new Error('express app required');
  }

  app.set('etag', 'strong');
  app.use(require('express-domain-middleware'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(morgan('combined', {
    skip: function () { return process.env.LOG !== 'true'; }
  }));
  app.get(/^\/.+\/$/, getDir);
  app.get(/^\/.+[^\/]$/, getFile);
  app.post("/*", postFileOrDir);
  app.put("/*", putFileOrDir);
  app.delete(/^\/.+\/$/, delDir);
  app.delete(/^\/.+[^\/]$/, delFile);
  app.use(function (err, req, res, next)  {
    error('uncaught error', err.stack);
    var outErr = {
      message: err.message,
      stack: err.stack
    };
    res.status(500).send(outErr);
  });
  return app;
};

/* GET
  /path/to/dir/
  list contents of directory

  *optional*
  ?recursive = list recursively default false

  return: list of files/dirs
  res.body = [
    {
      "fullFilePath"
    }, ...
  ]
*/
var getDir = function (req, res, next) {
  if (req.query.stat) {
    return statFile(req, res, next);
  }

  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isRecursive = req.query.recursive || "false";

  var handList = function (err, files) {
    if (err && err.code === 'ENOTDIR') {
      // this this is a file, redirect to file path
      var originalUrl = url.parse(req.originalUrl);
      originalUrl.pathname = originalUrl.pathname.substr(0, originalUrl.pathname.length - 1);
      var target = url.format(originalUrl);
      res.statusCode = 303;
      res.setHeader('Location', target);
      return res.end('Redirecting to ' + target);
    }
    if (files) {
      for (var i = files.length - 1; i >= 0; i--) {
        files[i] = formatOutData(req, files[i]);
      }
    }
    sendCode(200, req, res, next, files)(err);
  };

  if (isRecursive === "true") {
    return fileDriver.listAll(dirPath, handList);
  } else {
    return fileDriver.list(dirPath, handList);
  }
};

/* GET
  /path/to/file
  return contents of file
  if dir, redirect to dir path

  *optional*
  ?encoding = default utf8

  return: data of file
  res.body = {"content of specified file"}
*/
var getFile = function (req, res, next) {
  if (req.query.stat) {
    return statFile(req, res, next);
  }

  var filePath = decodeURI(url.parse(req.url).pathname);
  var encoding = req.query.encoding || 'utf8';
  fileDriver.readFile(filePath, encoding, function(err, data) {
    if (err && err.code === 'EISDIR') {
      // this this is a dir, redirect to dir path
      var originalUrl = url.parse(req.originalUrl);
      originalUrl.pathname += '/';
      var target = url.format(originalUrl);
      res.statusCode = 303;
      res.setHeader('Location', target);
      return res.end('Redirecting to ' + target);
    }

    res.set('content-type', mime.lookup(filePath));
    sendCode(200, req, res, next, data)(err);
  });
};

/* POST
  /path/to/file/or/dir
  creates or overwrites file
  creates dir if it does not exisit.
  renames or moves file if newPath exists
  *optional*
  body.newPath = if exist, move/rename file to this location.
  body.clobber = if true will overwrite dest files (default false)
  body.mkdirp = if true will create path to new location (default false)

  body.mode = permissons of file (defaults: file 438(0666) dir 511(0777))
  body.encoding = default utf8

  returns: modified resource
  res.body = {
    "fullFilePath" or dir
  }
*/
var postFileOrDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isDir = dirPath.substr(-1) == '/';
  var options = {};
  var isJson = false;
  if (typeof req.headers['content-type'] === 'string') {
    isJson = ~req.headers['content-type'].indexOf('application/json') === -1 ? true : false;
  }
  // move/rename if newPath exists
  if (req.body.newPath) {
    options.clobber = req.body.clobber || false;
    options.mkdirp = req.body.mkdirp || false;
    return fileDriver.move(dirPath, req.body.newPath, options,
      sendCode(200, req, res, next, formatOutData(req, req.body.newPath)));
  }

  if (isDir) {
    var mode = req.body.mode || 511;
    return fileDriver.mkdir(dirPath, mode,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }

  if (!isJson) {
    // default is to not clobber
    options.encoding = req.query.encoding  || 'utf8';
    options.mode = req.query.mode || 438;
    options.flags =  req.query.clobber === 'true' ? 'w' : 'wx';

    return fileDriver.writeFileStream(dirPath, req, options,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }

  options.encoding = req.body.encoding  || 'utf8';
  options.mode = req.body.mode || 438;
  var data = req.body.content || '';
  fileDriver.writeFile(dirPath, data, options,
    sendCode(201, req, res, next, formatOutData(req, dirPath)));
};

/* PUT
  /path/to/file/or/dir
  make file or dir

  *optional*
  body.mode = permissons of file (438 default 0666 octal)
  body.encoding = default utf8

  returns: modified resource
  res.body = {
    "fullFilePath"
  }
*/
var putFileOrDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var isDir = dirPath.substr(-1) == '/';
  var options = {};

  if (isDir) {
    var mode = req.body.mode || 511;
    fileDriver.mkdir(dirPath, mode,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  } else {
    options.encoding = req.body.encoding  || 'utf8';
    options.mode = req.body.mode  || 438;
    var data = req.body.content || '';
    fileDriver.writeFile(dirPath, data, options,
      sendCode(201, req, res, next, formatOutData(req, dirPath)));
  }
};

/* DEL
  /path/to/dir/
  deletes dir
  *optional*
  body.clobber = will remove non-empty dir (defaut: false)

  return:
  res.body = {}
*/
var delDir = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  var clobber = req.body.clobber  || false;
  fileDriver.rmdir(dirPath, clobber, sendCode(200, req, res, next, {}));
};

/* DEL
  /path/to/file
  deletes file

  return:
  res.body = {}
*/
var delFile = function (req, res, next) {
  var dirPath =  decodeURI(url.parse(req.url).pathname);
  fileDriver.unlink(dirPath, sendCode(200, req, res, next, {}));
};

/* GET
  /path/to/dir/or/file
  Returns stats for a file

  return: stats for the file as determined by node
  res.body = {
    dev: 16777220,
    mode: 16877,
    nlink: 31,
    uid: 501,
    gid: 20,
    rdev: 0,
    blksize: 4096,
    ino: 604862,
    size: 1054,
    blocks: 0,
    atime: Thu Mar 05 2015 11:38:47 GMT-0800 (PST),
    mtime: Thu Mar 05 2015 10:52:41 GMT-0800 (PST),
    ctime: Thu Mar 05 2015 10:52:41 GMT-0800 (PST),
    birthtime: Mon Mar 02 2015 10:55:37 GMT-0800 (PST)
  }
*/
var statFile = function (req, res, next) {
  var filePath = decodeURI(url.parse(req.url).pathname);
  fileDriver.stat(filePath, function(err, stats) {
    sendCode(200, req, res, next, stats)(err);
  });
}

// Helpers

// formats out data based on client spec.
var formatOutData = function (req, filepath) {
  var out = filepath;
  if (typeof req.modifyOut === 'function') {
    out = req.modifyOut(out);
  }
  return out;
};

var sendCode = function(code, req, res, next, out) {
  return function (err) {
    if (err) {
      error('ERROR', req.url, err);
      code = 500;
      out = {
        errno: err.errno,
        code: err.code,
        path: err.path,
        message: err.message,
        stack: err.stack
      };

      if (err.code === 'ENOENT') {
        code = 404;
      } if (err.code === 'EPERM') {
        code = 403;
      } if (err.code === 'ENOTDIR' ||
            err.code === 'EISDIR') {
        code = 400;
      } if (err.code === 'ENOTEMPTY' ||
            err.code === 'EEXIST' ||
            err.code === 'EINVAL') {
        code = 409;
      }
    }
    res.status(code).send(out);
  };
};

module.exports = fileserver;
<|endoftext|>


<commit_before>(function(){

    // The Tipue-powered code that returns search results to
    // "search.html".
    $(function() {
      $('#tipue_search_input').tipuesearch();
    });

    var loadSearchBox = document.getElementById("searchbox"),
      frag = document.createDocumentFragment(),
      form = document.createElement("form"),
      searchTextBox = document.createElement("input"),
      searchButton = document.createElement("input");

    // set attributes for form
    form.action = "search.html";
    form.setAttribute("role", "search");

    // set attributes for Search text box
    searchTextBox.type = "text";
    searchTextBox.name = "q";
    searchTextBox.id = "tipue_search_input";
    searchTextBox.placeholder = "Search...";

    // set attributes for Submit button
    searchButton.type = "submit";
    searchButton.setAttribute("class", "btnSearch");
    searchButton.value = "Search";

    // Arrange elements
    form.appendChild(searchTextBox);
    form.appendChild(searchButton);

    // Load arranged elements into document fragment
    frag.appendChild(form);

    // Load document fragment into #searchbox, which is already on the page
    loadSearchBox.appendChild(frag);

})();<commit_msg>update jekyll search sample JS code<commit_after>(function(){

  $(function() {
    $('#tipue_search_input').tipuesearch();
  });

  // Variables that are global to this RequireJS module only
  var loadMenu,
    isCssDisabled,
    testcss,
    currstyle;

  loadMenu = function() {

    var loadSearchBox = document.getElementById("searchbox"),
      frag = document.createDocumentFragment(),
      form = document.createElement("form"),
      searchTextBox = document.createElement("input"),
      searchButton = document.createElement("input");

    form.action = "search.html";
    form.setAttribute("role", "search");

    searchTextBox.type = "text";
    searchTextBox.name = "q";
    searchTextBox.id = "tipue_search_input";
    searchTextBox.placeholder = "Search...";

    searchButton.type = "submit";
    searchButton.value = "Search";

    form.appendChild(searchTextBox);
    form.appendChild(searchButton);

    frag.appendChild(form);

    loadSearchBox.appendChild(frag);

  }

  // Start checking if CSS is disabled
  isCssDisabled = false;

  testcss = document.createElement('div');

  testcss.style.position = 'absolute';

  document.getElementsByTagName('body')[0].appendChild(testcss);

  if (testcss.currentStyle) {
    currstyle = testcss.currentStyle['position'];
  }

  else if (window.getComputedStyle) {
    currstyle = document.defaultView.getComputedStyle(testcss, null).getPropertyValue('position');
  }

  isCssDisabled = (currstyle === 'static') ? true : false;

  document.getElementsByTagName('body')[0].removeChild(testcss);

  if (isCssDisabled === false) {
    loadMenu();
  } else {
    return false;
  }

})();<|endoftext|>


<commit_before>var isError = require('util').isError;
var parse = function(body) {
	try {
		return JSON.parse(body || '{}') || {};
	} catch (err) {
		return {};
	}
};

var fn = function(request, response, next) {
	response.json = response.json.bind(response);

	if (request.body !== undefined || (request.method === 'GET' || request.method === 'HEAD')) {
		next();
		return;
	}

	request.body = '';
	request.setEncoding('utf-8');
	request.on('data', function(data) {
		request.body += data;
	});
	request.on('end', function() {
		next();
	});
};

fn.request = {};
fn.request.__defineGetter__('json', function() {
	return this._json || (this._json = parse(this.body));
});

fn.response = {};
fn.response.json = function(status, doc) {
	if (typeof status === 'number' && /^[^23]/.test(status) && (!doc || typeof doc === 'string')) {
		doc = {status:status, message:(doc || 'whoops')};
	}
	if (isError(status)) {
		var statusCode = status.status || status.statusCode || 500;

		this.json(statusCode, {status:statusCode, message:status.message});
		return;
	}
	if (doc) {
		this.statusCode = status;
	} else {
		doc = status;
	}

	doc = doc === undefined ? null : doc;
	doc = JSON.stringify(doc);

	this.setHeader('Content-Type', 'application/json; charset=utf-8');
	this.setHeader('Content-Length', Buffer.byteLength(doc));
	this.end(doc);
};

module.exports = fn;<commit_msg>json middleware using body parser<commit_after>var isError = require('util').isError;
var body = require('./body');

var fn = body('json', function(data) {
	try {
		return JSON.parse(data || '{}') || {};
	} catch (err) {
		return {};
	}
});

fn.response = {};
fn.response.json = function(status, doc) {
	if (typeof status === 'number' && status >= 400 && (!doc || typeof doc === 'string')) {
		doc = {status:status, message:(doc || 'whoops')};
	}
	if (isError(status)) {
		var statusCode = status.status || status.statusCode || 500;

		this.json(statusCode, {status:statusCode, message:status.message});
		return;
	}
	if (doc) {
		this.statusCode = status;
	} else {
		doc = status;
	}

	doc = doc === undefined ? null : doc;
	doc = JSON.stringify(doc);

	this.setHeader('Content-Type', 'application/json; charset=utf-8');
	this.setHeader('Content-Length', Buffer.byteLength(doc));
	this.end(doc);
};

module.exports = fn;<|endoftext|>


<commit_before>/**
 * RuntimeClient.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/runtime/RuntimeClient', [
	'moxie/core/utils/Env',
	'moxie/core/Exceptions',
	'moxie/core/utils/Basic',
	'moxie/runtime/Runtime'
], function(Env, x, Basic, Runtime) {
	/**
	Set of methods and properties, required by a component to acquire ability to connect to a runtime

	@class moxie/runtime/RuntimeClient
	*/
	return function RuntimeClient() {
		var runtime;

		Basic.extend(this, {
			/**
			Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
			Increments number of clients connected to the specified runtime.

			@private
			@method connectRuntime
			@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
			*/
			connectRuntime: function(options) {
				var comp = this, ruid;

				function initialize(items) {
					var type, constructor;

					// if we ran out of runtimes
					if (!items.length) {
						comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
						runtime = null;
						return;
					}

					type = items.shift().toLowerCase();
					constructor = Runtime.getConstructor(type);
					if (!constructor) {
						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Constructor for '%s' runtime is not available.", type);
						}
						initialize(items);
						return;
					}

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("Trying runtime: %s", type);
						Env.log(options);
					}

					// try initializing the runtime
					runtime = new constructor(options);

					runtime.bind('Init', function() {
						// mark runtime as initialized
						runtime.initialized = true;

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' initialized", runtime.type);
						}

						// jailbreak ...
						setTimeout(function() {
							runtime.clients++;
							// this will be triggered on component
							comp.trigger('RuntimeInit', runtime);
						}, 1);
					});

					runtime.bind('Error', function() {
						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' failed to initialize", runtime.type);
						}

						runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
						initialize(items);
					});

					runtime.bind('Exception', function(e, err) {
						var message = err.name + "(#" + err.code + ")" + (err.message ? ", from: " + err.message : '');

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' has thrown an exception: %s", this.type, message);
						}
						comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.EXCEPTION_ERR, message));
					});

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("\tselected mode: %s", runtime.mode);
					}

					// check if runtime managed to pick-up operational mode
					if (!runtime.mode) {
						runtime.trigger('Error');
						return;
					}

					runtime.init();
				}

				// check if a particular runtime was requested
				if (Basic.typeOf(options) === 'string') {
					ruid = options;
				} else if (Basic.typeOf(options.ruid) === 'string') {
					ruid = options.ruid;
				}

				if (ruid) {
					runtime = Runtime.getRuntime(ruid);
					if (runtime) {
						runtime.clients++;
						return runtime;
					} else {
						// there should be a runtime and there's none - weird case
						throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
					}
				}

				// initialize a fresh one, that fits runtime list and required features best
				initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
			},

			/**
			Disconnects from the runtime. Decrements number of clients connected to the specified runtime.

			@private
			@method disconnectRuntime
			*/
			disconnectRuntime: function() {
				if (runtime && --runtime.clients <= 0) {
					runtime.destroy();
				}

				// once the component is disconnected, it shouldn't have access to the runtime
				runtime = null;
			},

			/**
			Returns the runtime to which the client is currently connected.

			@method getRuntime
			@return {Runtime} Runtime or null if client is not connected
			*/
			getRuntime: function() {
				if (runtime && runtime.uid) {
					return runtime;
				}
				return runtime = null; // make sure we do not leave zombies rambling around
			},

			/**
			Handy shortcut to safely invoke runtime extension methods.

			@private
			@method exec
			@return {Mixed} Whatever runtime extension method returns
			*/
			exec: function() {
				return runtime ? runtime.exec.apply(this, arguments) : null;
			},

			/**
			Test runtime client for specific capability

			@method can
			@param {String} cap
			@return {Bool}
			*/
			can: function(cap) {
				return runtime ? runtime.can(cap) : false;
			}

		});
	};

});<commit_msg>RuntimeClient: Assign runtime id on the client, after it is connected.<commit_after>/**
 * RuntimeClient.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

define('moxie/runtime/RuntimeClient', [
	'moxie/core/utils/Env',
	'moxie/core/Exceptions',
	'moxie/core/utils/Basic',
	'moxie/runtime/Runtime'
], function(Env, x, Basic, Runtime) {
	/**
	Set of methods and properties, required by a component to acquire ability to connect to a runtime

	@class moxie/runtime/RuntimeClient
	*/
	return function RuntimeClient() {
		var runtime;

		Basic.extend(this, {
			/**
			Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
			Increments number of clients connected to the specified runtime.

			@private
			@method connectRuntime
			@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
			*/
			connectRuntime: function(options) {
				var comp = this, ruid;

				function initialize(items) {
					var type, constructor;

					// if we ran out of runtimes
					if (!items.length) {
						comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
						runtime = null;
						return;
					}

					type = items.shift().toLowerCase();
					constructor = Runtime.getConstructor(type);
					if (!constructor) {
						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Constructor for '%s' runtime is not available.", type);
						}
						initialize(items);
						return;
					}

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("Trying runtime: %s", type);
						Env.log(options);
					}

					// try initializing the runtime
					runtime = new constructor(options);

					runtime.bind('Init', function() {
						// mark runtime as initialized
						runtime.initialized = true;

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' initialized", runtime.type);
						}

						// jailbreak ...
						setTimeout(function() {
							runtime.clients++;
							comp.ruid = runtime.uid;
							// this will be triggered on component
							comp.trigger('RuntimeInit', runtime);
						}, 1);
					});

					runtime.bind('Error', function() {
						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' failed to initialize", runtime.type);
						}

						runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
						initialize(items);
					});

					runtime.bind('Exception', function(e, err) {
						var message = err.name + "(#" + err.code + ")" + (err.message ? ", from: " + err.message : '');

						if (MXI_DEBUG && Env.debug.runtime) {
							Env.log("Runtime '%s' has thrown an exception: %s", this.type, message);
						}
						comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.EXCEPTION_ERR, message));
					});

					if (MXI_DEBUG && Env.debug.runtime) {
						Env.log("\tselected mode: %s", runtime.mode);
					}

					// check if runtime managed to pick-up operational mode
					if (!runtime.mode) {
						runtime.trigger('Error');
						return;
					}

					runtime.init();
				}

				// check if a particular runtime was requested
				if (Basic.typeOf(options) === 'string') {
					ruid = options;
				} else if (Basic.typeOf(options.ruid) === 'string') {
					ruid = options.ruid;
				}

				if (ruid) {
					runtime = Runtime.getRuntime(ruid);
					if (runtime) {
						comp.ruid = ruid;
						runtime.clients++;
						return runtime;
					} else {
						// there should be a runtime and there's none - weird case
						throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
					}
				}

				// initialize a fresh one, that fits runtime list and required features best
				initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
			},

			/**
			Disconnects from the runtime. Decrements number of clients connected to the specified runtime.

			@private
			@method disconnectRuntime
			*/
			disconnectRuntime: function() {
				if (runtime && --runtime.clients <= 0) {
					runtime.destroy();
				}

				// once the component is disconnected, it shouldn't have access to the runtime
				runtime = null;
			},

			/**
			Returns the runtime to which the client is currently connected.

			@method getRuntime
			@return {Runtime} Runtime or null if client is not connected
			*/
			getRuntime: function() {
				if (runtime && runtime.uid) {
					return runtime;
				}
				return runtime = null; // make sure we do not leave zombies rambling around
			},

			/**
			Handy shortcut to safely invoke runtime extension methods.

			@private
			@method exec
			@return {Mixed} Whatever runtime extension method returns
			*/
			exec: function() {
				return runtime ? runtime.exec.apply(this, arguments) : null;
			},

			/**
			Test runtime client for specific capability

			@method can
			@param {String} cap
			@return {Bool}
			*/
			can: function(cap) {
				return runtime ? runtime.can(cap) : false;
			}

		});
	};

});<|endoftext|>


<commit_before>// PLUGIN: Mustache

(function (Popcorn) {

  /**
   * Mustache Popcorn Plug-in
   *
   * Adds the ability to render JSON using templates via the Mustache templating library.
   *
   * @param {Object} options
   *
   * Required parameters: start, end, template, data, and target.
   * Optional parameter: static.
   *
   *   start: the time in seconds when the mustache template should be rendered
   *          in the target div.
   *
   *   end: the time in seconds when the rendered mustache template should be
   *        removed from the target div.
   *
   *   target: a String -- the target div's id.
   *
   *   template: the mustache template for the plugin to use when rendering.  This can be
   *             a String containing the template, or a Function that returns the template's
   *             String.
   *
   *   data: the data to be rendered using the mustache template.  This can be a JSON String,
   *         a JavaScript Object literal, or a Function returning a String or Literal.
   *
   *   dynamic: an optional argument indicating that the template and json data are dynamic
   *            and need to be loaded dynamically on every use.  Defaults to True.
   *
   * Example:
     var p = Popcorn('#video')

        // Example using template and JSON strings.
        .mustache({
          start: 5, // seconds
          end:  15,  // seconds
          target: 'mustache',
          template: '
{{header}}
'                         +
                    '{{#bug}}'                                    +
                    '{{/bug}}'                                    +
                    ''                                            +
                    '{{#items}}'                                  +
                    '  {{#first}}'                                +
                    '
{{name}}
'      +
                    '  {{/first}}'                                +
                    '  {{#link}}'                                 +
                    '
{{name}}
' +
                    '  {{/link}}'                                 +
                    '{{/items}}'                                  +
                    ''                                            +
                    '{{#empty}}'                                  +
                    '
The list is empty.
'                 +
                    '{{/empty}}'                                  ,

          data:     '{'                                                        +
                    '  "header": "Colors", '                                   +
                    '  "items": [ '                                            +
                    '      {"name": "red", "first": true, "url": "#Red"}, '    +
                    '      {"name": "green", "link": true, "url": "#Green"}, ' +
                    '      {"name": "blue", "link": true, "url": "#Blue"} '    +
                    '  ],'                                                     +
                    '  'empty': false'                                         +
                    '}',
          dynamic: false // The json is not going to change, load it early.
        } )

        // Example showing Functions instead of Strings.
        .mustache({
          start: 20,  // seconds
          end:   25,  // seconds
          target: 'mustache',
          template: function(instance, options) {
                      var template = // load your template file here...
                      return template;
                    },
          data:     function(instance, options) {
                      var json = // load your json here...
                      return json;
                    }
        } );
  *
  */

  Popcorn.plugin( 'mustache' , function( options ) {

    var getData, data, getTemplate, template, loaded = false;

    Popcorn.getScript('https://github.com/janl/mustache.js/raw/master/mustache.js', function() {
      loaded = true;
    });

    var shouldReload = !!options.dynamic,
        typeOfTemplate = typeof options.template,
        typeOfData = typeof options.data;

    if ( typeOfTemplate === 'function' ) {
      if ( !shouldReload ) {
        template = options.template( options );
      } else {
        getTemplate = options.template;
      }
    } else if ( typeOfTemplate === 'string' ) {
      template = options.template;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.template must be a String or a Function.' );
    }

    if ( typeOfData === 'function' ) {
      if ( !shouldReload ) {
        data = options.data(options);
      } else {
        getData = options.data;
      }
    } else if ( typeOfData === 'string' ) {
      data = JSON.parse( options.data );
    } else if ( typeOfData === 'object' ) {
      data = options.data;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.data must be a String, Object, or Function.' );
    }

    return {
      start: function( event, options ) {

        var interval = function() {

          if( !loaded ) {
            setTimeout( function() {
              interval();
            }, 10 );
          } else {

            // if dynamic, freshen json data on every call to start, just in case.
            if ( getData ) {
              data = getData( options );
            }

            if ( getTemplate ) {
              template = getTemplate( options );
            }

            var html = Mustache.to_html( template,
                                         data
                                       ).replace( /^\s*/mg, '' );
            document.getElementById( options.target ).innerHTML = html;
          }
        }

        interval();

      },

      end: function( event, options ) {
        document.getElementById( options.target ).innerHTML = '';
      },
      _teardown: function( options ) {
        getData = data = getTemplate = template = null;
      }
    };
  },
  {
    about: {
      name: 'Popcorn Mustache Plugin',
      version: '0.1',
      author: 'David Humphrey (@humphd)',
      website: 'http://vocamus.net/dave'
    },
    options: {
      start: {elem:'input', type:'text', label:'In'},
      end: {elem:'input', type:'text', label:'Out'},
      target: 'mustache-container',
      template: {elem:'input', type:'text', label:'Template'},
      data: {elem:'input', type:'text', label:'Data'},
      /* TODO: how to show a checkbox/boolean? */
      dynamic: {elem:'input', type:'text', label:'Dynamic'}
    }
  });
})( Popcorn );
<commit_msg>Added a semi-colon to fix a linting issue<commit_after>// PLUGIN: Mustache

(function (Popcorn) {

  /**
   * Mustache Popcorn Plug-in
   *
   * Adds the ability to render JSON using templates via the Mustache templating library.
   *
   * @param {Object} options
   *
   * Required parameters: start, end, template, data, and target.
   * Optional parameter: static.
   *
   *   start: the time in seconds when the mustache template should be rendered
   *          in the target div.
   *
   *   end: the time in seconds when the rendered mustache template should be
   *        removed from the target div.
   *
   *   target: a String -- the target div's id.
   *
   *   template: the mustache template for the plugin to use when rendering.  This can be
   *             a String containing the template, or a Function that returns the template's
   *             String.
   *
   *   data: the data to be rendered using the mustache template.  This can be a JSON String,
   *         a JavaScript Object literal, or a Function returning a String or Literal.
   *
   *   dynamic: an optional argument indicating that the template and json data are dynamic
   *            and need to be loaded dynamically on every use.  Defaults to True.
   *
   * Example:
     var p = Popcorn('#video')

        // Example using template and JSON strings.
        .mustache({
          start: 5, // seconds
          end:  15,  // seconds
          target: 'mustache',
          template: '
{{header}}
'                         +
                    '{{#bug}}'                                    +
                    '{{/bug}}'                                    +
                    ''                                            +
                    '{{#items}}'                                  +
                    '  {{#first}}'                                +
                    '
{{name}}
'      +
                    '  {{/first}}'                                +
                    '  {{#link}}'                                 +
                    '
{{name}}
' +
                    '  {{/link}}'                                 +
                    '{{/items}}'                                  +
                    ''                                            +
                    '{{#empty}}'                                  +
                    '
The list is empty.
'                 +
                    '{{/empty}}'                                  ,

          data:     '{'                                                        +
                    '  "header": "Colors", '                                   +
                    '  "items": [ '                                            +
                    '      {"name": "red", "first": true, "url": "#Red"}, '    +
                    '      {"name": "green", "link": true, "url": "#Green"}, ' +
                    '      {"name": "blue", "link": true, "url": "#Blue"} '    +
                    '  ],'                                                     +
                    '  'empty': false'                                         +
                    '}',
          dynamic: false // The json is not going to change, load it early.
        } )

        // Example showing Functions instead of Strings.
        .mustache({
          start: 20,  // seconds
          end:   25,  // seconds
          target: 'mustache',
          template: function(instance, options) {
                      var template = // load your template file here...
                      return template;
                    },
          data:     function(instance, options) {
                      var json = // load your json here...
                      return json;
                    }
        } );
  *
  */

  Popcorn.plugin( 'mustache' , function( options ) {

    var getData, data, getTemplate, template, loaded = false;

    Popcorn.getScript('https://github.com/janl/mustache.js/raw/master/mustache.js', function() {
      loaded = true;
    });

    var shouldReload = !!options.dynamic,
        typeOfTemplate = typeof options.template,
        typeOfData = typeof options.data;

    if ( typeOfTemplate === 'function' ) {
      if ( !shouldReload ) {
        template = options.template( options );
      } else {
        getTemplate = options.template;
      }
    } else if ( typeOfTemplate === 'string' ) {
      template = options.template;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.template must be a String or a Function.' );
    }

    if ( typeOfData === 'function' ) {
      if ( !shouldReload ) {
        data = options.data(options);
      } else {
        getData = options.data;
      }
    } else if ( typeOfData === 'string' ) {
      data = JSON.parse( options.data );
    } else if ( typeOfData === 'object' ) {
      data = options.data;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.data must be a String, Object, or Function.' );
    }

    return {
      start: function( event, options ) {

        var interval = function() {

          if( !loaded ) {
            setTimeout( function() {
              interval();
            }, 10 );
          } else {

            // if dynamic, freshen json data on every call to start, just in case.
            if ( getData ) {
              data = getData( options );
            }

            if ( getTemplate ) {
              template = getTemplate( options );
            }

            var html = Mustache.to_html( template,
                                         data
                                       ).replace( /^\s*/mg, '' );
            document.getElementById( options.target ).innerHTML = html;
          }
        };

        interval();

      },

      end: function( event, options ) {
        document.getElementById( options.target ).innerHTML = '';
      },
      _teardown: function( options ) {
        getData = data = getTemplate = template = null;
      }
    };
  },
  {
    about: {
      name: 'Popcorn Mustache Plugin',
      version: '0.1',
      author: 'David Humphrey (@humphd)',
      website: 'http://vocamus.net/dave'
    },
    options: {
      start: {elem:'input', type:'text', label:'In'},
      end: {elem:'input', type:'text', label:'Out'},
      target: 'mustache-container',
      template: {elem:'input', type:'text', label:'Template'},
      data: {elem:'input', type:'text', label:'Data'},
      /* TODO: how to show a checkbox/boolean? */
      dynamic: {elem:'input', type:'text', label:'Dynamic'}
    }
  });
})( Popcorn );
<|endoftext|>


<commit_before>{
	"translatorID":"e4660e05-a935-43ec-8eec-df0347362e4c",
	"translatorType":4,
	"label":"ERIC",
	"creator":"Ramesh Srigiriraju",
	"target":"^http://(?:www\\.)?eric\\.ed\\.gov/",
	"minVersion":"1.0.0b4.r1",
	"maxVersion":"",
	"priority":100,
	"inRepository":true,
	"lastUpdated":"2008-12-15 05:30:00"
}

function detectWeb(doc, url)	{
	var namespace=doc.documentElement.namespaceURI;
	var nsResolver=namespace?function(prefix)	{
		return (prefix=="x")?namespace:null;
	}:null;
	var searchpath='//form[@name="searchResultsForm"][@id="searchResultsForm"]';
	if(doc.evaluate(searchpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
		return "multiple";
	//var singpath='//tr/td[@class="primaryHeader"][contains(text(), "Record Details")]';
	var singpath='contains(//div[@id="titleBarBlue"]/text(), "Record Details")';
	if(doc.evaluate(singpath, doc, nsResolver, XPathResult.ANY_TYPE, null).booleanValue)	{
		var typepath='//tr[td/span/strong/text()="Pub Types:"]/td[2]/text()';
		var typestr=doc.evaluate(typepath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
		var typereg=new RegExp("([^;/\-]+)");
		var typearr=typereg.exec(typestr);
		if(typearr[1]=="Journal Articles")
			return "journalArticle";
		if(typearr[1]=="Information Analyses")
			return "journalArticle";
		if(typearr[1]="Machine")
			return "computerProgram";
		if(typearr[1]="Computer Programs")
			return "computerProgram";
		if(typearr[1]="Dissertations")
			return "thesis";
		if(typearr[1]="Reports")
			return "report";
		if(typearr[1]="Non")
			return "audioRecording";
		if(typearr[1]="Legal")
			return "statute";
		else
			return "book";
	}
}

function doWeb(doc, url)	{
	var namespace=doc.documentElement.namespaceURI;
	var nsResolver=namespace?function(prefix)	{
		return (prefix=="x")?namespace:null;
	}:null;
	var searchpath='//form[@name="searchResultsForm"][@id="searchResultsForm"]';
	if(doc.evaluate(searchpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())	{
		var string="http://eric.ed.gov/ERICWebPortal/custom/portlets/clipboard/performExport.jsp";
		var idpath='//a[img]/@id';
		var ids=doc.evaluate(idpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		var items=new Array();
		var titlpath='//tr[1]/td[1]/p/a';
		var titlerows=doc.evaluate(titlpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		var id;
		while(id=ids.iterateNext())
			items[id.nodeValue]=Zotero.Utilities.cleanTags(Zotero.Utilities.cleanString(titlerows.iterateNext().textContent));
		items=Zotero.selectItems(items);
		var string="http://eric.ed.gov/ERICWebPortal/custom/portlets/clipboard/performExport.jsp?";
		for(var ids in items)
			string+="accno="+ids+"&";
		string+="texttype=endnote&citationtype=brief&Download.x=86&Download.y=14";
		Zotero.Utilities.HTTP.doGet(string, function(text)	{
			var trans=Zotero.loadTranslator("import");
			trans.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
			trans.setString(text);
			trans.setHandler("itemDone", function(obj, newItem)	{
				var linkpath='//tbody[tr/td/a/@id="'+newItem.itemID+'"]/tr/td/p/a[@class="action"]';
				var link=doc.evaluate(linkpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
				if(link)
					newItem.attachments.push({url:link.href, title:newItem.title, mimeType:"application/pdf"});
				newItem.complete();
			});
			trans.translate();
			Zotero.done();
		});
		Zotero.wait();
	}
	var singpath='contains(//div[@id="titleBarBlue"]/text(), "Record Details")';
	if(doc.evaluate(singpath, doc, nsResolver, XPathResult.ANY_TYPE, null).booleanValue)	{
		var idpath='//input[@type="hidden"][@name="accno"]/@value';
		var idpath2='//meta[@name="eric #"]/@content';
		var id = url.match(/accno=([^&]+)/)[1];
		var string="http://eric.ed.gov/ERICWebPortal/custom/portlets/clipboard/performExport.jsp?accno=";
		string+= id+"&texttype=endnote&citationtype=brief&Download.x=86&Download.y=14";
		Zotero.Utilities.HTTP.doGet(string, function(text)	{
			var trans=Zotero.loadTranslator("import");
			trans.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
			trans.setString(text);
			trans.setHandler("itemDone", function(obj, newItem)	{
				var linkpath='//tr/td/p[img/@alt="PDF"]/a';
				var link=doc.evaluate(linkpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
				if(link)
					newItem.attachments.push({url:link.href, title:newItem.title, mimeType:"application/pdf"});
				newItem.complete();
			});
			trans.translate();
			Zotero.done();
		});
		Zotero.wait();
	}
}<commit_msg>Fixed ERIC translator<commit_after>{
        "translatorID":"e4660e05-a935-43ec-8eec-df0347362e4c",
        "label":"ERIC",
        "creator":"Ramesh Srigiriraju, Avram Lyon",
        "target":"^http://(?:www\\.)?eric\\.ed\\.gov/",
        "minVersion":"1.0.0b4.r1",
        "maxVersion":"",
        "priority":100,
        "inRepository":"1",
        "translatorType":4,
        "lastUpdated":"2010-08-24 07:23:41"
}

function detectWeb(doc, url)	{
	var namespace=doc.documentElement.namespaceURI;
	var nsResolver=namespace?function(prefix)	{
		return (prefix=="x")?namespace:null;
	}:null;
	// Search results
	var searchpath='//div[@id="searchFaceted"]//td[@class="resultHeader"]';
	if(doc.evaluate(searchpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
		return "multiple";
	// Clipboard
	if(url.match(/ERICWebPortal\/search\/clipboard\.jsp/))
		return "multiple";
	// folder
	if(url.match(/ERICWebPortal\/MyERIC\/clipboard\/viewFolder\.jsp\?folderIndex/))
		return "multiple";
	// Individual record
	var singpath='//div[@id="titleBarBlue"]';
	var res = doc.evaluate(singpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
	if(res && res.textContent.indexOf("Record Details") !== -1)	{
		var typepath='//tr[td/span/a/strong/text()="Pub Types:"]/td[2]/text()';
		var typestr=doc.evaluate(typepath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
		var typereg=new RegExp("([^;/\-]+)");
		var typearr=typereg.exec(typestr);
		if(typearr[1]=="Journal Articles")
			return "journalArticle";
		if(typearr[1]=="Information Analyses")
			return "journalArticle";
		if(typearr[1]="Machine")
			return "computerProgram";
		if(typearr[1]="Computer Programs")
			return "computerProgram";
		if(typearr[1]="Dissertations")
			return "thesis";
		if(typearr[1]="Reports")
			return "report";
		if(typearr[1]="Non")
			return "audioRecording";
		if(typearr[1]="Legal")
			return "statute";
		else
			return "book";
	}
}

function doWeb(doc, url)	{
	var namespace=doc.documentElement.namespaceURI;
	var nsResolver=namespace?function(prefix)	{
		return (prefix=="x")?namespace:null;
	}:null;
	if(detectWeb(doc, url) == "multiple")	{
		var string="http://eric.ed.gov/ERICWebPortal/custom/portlets/clipboard/performExport.jsp";
		var items=new Array();
		if(url.match(/ERICWebPortal\/search\/clipboard\.jsp/)
			|| url.match(/ERICWebPortal\/MyERIC\/clipboard\/viewFolder\.jsp\?folderIndex/)) {
			// We have a clipboard or folder page; structure is the same
			var rowpath='//table[@class="tblDataTable"]/tbody/tr[td]';
			var rows = doc.evaluate(rowpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var row, id, title;
			while(row = rows.iterateNext()) {
				title = doc.evaluate('./td[2]/a', row, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
				id = doc.evaluate('./td[6]', row, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
				Zotero.debug(title + id);
				items[id] = Zotero.Utilities.cleanTags(Zotero.Utilities.cleanString(title));
			}
		} else {
			// We have normal search results
			var idpath='//a[img[@width="64"]]';
			var ids=doc.evaluate(idpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var titlpath='//table[@class="tblSearchResult"]//td[@class="resultHeader"][1]/p/a';
			var titlerows=doc.evaluate(titlpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var id;
			while(id=ids.iterateNext())
				items[id.id]=Zotero.Utilities.cleanTags(Zotero.Utilities.cleanString(titlerows.iterateNext().textContent));
		}
		items=Zotero.selectItems(items);
		if (!items) return false;
		var string="http://eric.ed.gov/ERICWebPortal/MyERIC/clipboard/performExport.jsp?";
		for(var ids in items)
			string+="accno="+ids+"&";
		string+="texttype=endnote&citationtype=brief&Download.x=86&Download.y=14";
		Zotero.debug(string);
		Zotero.Utilities.HTTP.doGet(string, function(text)	{
			var trans=Zotero.loadTranslator("import");
			trans.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
			trans.setString(text);
			trans.setHandler("itemDone", function(obj, newItem)	{
				var linkpath='//tbody[tr/td/a/@id="'+newItem.itemID+'"]/tr/td/p/a[@class="action"]';
				var link=doc.evaluate(linkpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
				if(link)
					newItem.attachments.push({url:link.href, title:newItem.title, mimeType:"application/pdf"});
				newItem.complete();
			});
			trans.translate();
			Zotero.done();
		});
		Zotero.wait();
	}
	var type = detectWeb(doc, url);
	if(type && type != "multiple")	{
		var idpath='//tr[/td[1]/span/a/strong/contains("ERIC #")]/td[2]';
		var idpath2='//meta[@name="eric #"]/@content';
		var id = url.match(/accno=([^&]+)/)[1];
		var string="http://eric.ed.gov/ERICWebPortal/MyERIC/clipboard/performExport.jsp?";
		string+= "accno="+ id+"&texttype=endnote&citationtype=brief&Download.x=86&Download.y=14";
		Zotero.debug(string);
		Zotero.Utilities.HTTP.doGet(string, function(text)	{
			var trans=Zotero.loadTranslator("import");
			trans.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
			trans.setString(text);
			trans.setHandler("itemDone", function(obj, newItem)	{
				var linkpath='//tr/td/p[img/@alt="PDF"]/a';
				var link=doc.evaluate(linkpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
				if(link)
					newItem.attachments.push({url:link.href, title:newItem.title, mimeType:"application/pdf"});
				newItem.complete();
			});
			trans.translate();
			Zotero.done();
		});
		Zotero.wait();
	}
}
<|endoftext|>


<commit_before>$(function() {
  var celloGame = new CelloGame();
  var violinGame = new ViolinGame();
  var trumpetGame = new TrumpetGame();

  $("#configBtn").click(function() {
    configureCelloGame();
    configureViolinGame();
    configureTrumpetGame();
  });

  $("#resetBtn").click(function() {
    $.post("/reset");
  });

  $("#armBtn").click(function() {
      $.post("/arm");
  });

  $("#startBtn").click(function() {
    $.ajax({url: "/start",
            method: "POST",
            data: JSON.stringify({duration: parseInt($("#durationTxt").val())}),
            contentType: "application/json"
          });
  });

  function configureViolinGame() {
    violinGame.resetGame().then(function (answer) {
      sendConfig("violin-chip", answer);
    });
  }

  function configureTrumpetGame() {
    var trumpetGameAnswer = trumpetGame.resetGame();
    sendConfig("trumpet-edison", trumpetGameAnswer);
  }

  function configureCelloGame(){
    var celloGameAnswer = resetCelloGame();
    sendConfig("cello-chip", { answer: celloGameAnswer });
  }

  function resetCelloGame(){
    celloGame.resetGame();
    var celloGameAnswer = celloGame.answer;
    var celloGameQuestion = celloGame.question;
    var celloGameQuestionSet = celloGame.questionSet;

    $('#answer', '#celloGame').text(celloGameAnswer);
    $('#questionSet', '#celloGame').text(celloGameQuestionSet);

    for(var i=0; i < celloGameQuestion.length; i++) {
        $('p', '#celloGame #button' + (i + 1)).text(celloGameQuestion[celloGameAnswer[i]]);
        $('img', '#celloGame #button' + (i + 1)).attr('src', getImagePathForButton(celloGameQuestion[celloGameAnswer[i]], celloGameQuestionSet));
    }

    return celloGameAnswer;
  }

  function sendConfig(deviceName, data) {
    $.ajax({
      type: 'POST',
      url: '/configure',
      data: JSON.stringify({
        "deviceName": deviceName,
        "data": data
      }),
      contentType: "application/json",
      dataType: 'json'
    });
  }

  function getImagePathForButton(button, questionSet) {
    var imageFolder = "assets/cellogame/";
    return imageFolder + questionSet + "_"  + button + ".jpg";
  }
});
<commit_msg>Fix config for cello<commit_after>$(function() {
  var celloGame = new CelloGame();
  var violinGame = new ViolinGame();
  var trumpetGame = new TrumpetGame();

  $("#configBtn").click(function() {
    configureCelloGame();
    configureViolinGame();
    configureTrumpetGame();
  });

  $("#resetBtn").click(function() {
    $.post("/reset");
  });

  $("#armBtn").click(function() {
      $.post("/arm");
  });

  $("#startBtn").click(function() {
    $.ajax({url: "/start",
            method: "POST",
            data: JSON.stringify({duration: parseInt($("#durationTxt").val())}),
            contentType: "application/json"
          });
  });

  function configureViolinGame() {
    violinGame.resetGame().then(function (answer) {
      sendConfig("violin-chip", answer);
    });
  }

  function configureTrumpetGame() {
    var trumpetGameAnswer = trumpetGame.resetGame();
    sendConfig("trumpet-edison", trumpetGameAnswer);
  }

  function configureCelloGame(){
    var celloGameAnswer = resetCelloGame();
    var answer = celloGameAnswer.sort().map(function (val) {
      return celloGameAnswer.indexOf(val);
    });
    sendConfig("cello-chip", { answer: answer });
  }

  function resetCelloGame(){
    celloGame.resetGame();
    var celloGameAnswer = celloGame.answer;
    var celloGameQuestion = celloGame.question;
    var celloGameQuestionSet = celloGame.questionSet;

    $('#answer', '#celloGame').text(celloGameAnswer);
    $('#questionSet', '#celloGame').text(celloGameQuestionSet);

    for(var i=0; i < celloGameQuestion.length; i++) {
        $('p', '#celloGame #button' + (i + 1)).text(celloGameQuestion[celloGameAnswer[i]]);
        $('img', '#celloGame #button' + (i + 1)).attr('src', getImagePathForButton(celloGameQuestion[celloGameAnswer[i]], celloGameQuestionSet));
    }

    return celloGameAnswer;
  }

  function sendConfig(deviceName, data) {
    $.ajax({
      type: 'POST',
      url: '/configure',
      data: JSON.stringify({
        "deviceName": deviceName,
        "data": data
      }),
      contentType: "application/json",
      dataType: 'json'
    });
  }

  function getImagePathForButton(button, questionSet) {
    var imageFolder = "assets/cellogame/";
    return imageFolder + questionSet + "_"  + button + ".jpg";
  }
});
<|endoftext|>


<commit_before>import get from 'lodash/get'
import React from 'react'
const el = React.createElement
import { observer } from 'mobservable-react'
import { observable, map} from 'mobservable'
import Command from '../reactiveCollection/Command'

import Button from 'react-bootstrap/lib/Button'
import Input from 'react-bootstrap/lib/Input'

export var fieldEditor = function(collections, collectionId, itemId, $patch, options) {
  var model = collections[collectionId].model
  var path = options.path
  var type = options.type || 'text'
  var onChange = newVal => $patch.set(path, newVal)

  return observer(function() {
    var itemValue = model.get(itemId).value
    var partEditing = $patch.has(path)
    var value = partEditing ? $patch.get(path) : get(itemValue, path)

    if (typeof type === 'function') return el(type, {value, onChange})
    return el(Input, {
      type: type,
      // bsStyle: partEditing ? "success" : null,
      value: value,
      onChange: ev => onChange(ev.target.value),
    })
  })
}

export var labeledPart = function(collections, collectionId, itemId, $patch, options) {
  var label = options.label
  var innerView = options.view
  var cmp = typeof innerView === 'function' ?
    innerView(collections, collectionId, itemId, $patch, options) :
    fieldEditor(collections, collectionId, itemId, $patch, options)

  return function () {
    return el(Input, {label: label, help: options.help},
      el(cmp)
    )
  }
}

export default function (parts) {
  return function (collections, collectionId, itemId) {
    var model = collections[collectionId].model
    var $patch = map()
    var save = new Command(() => {
      return model.patch(itemId, $patch.toJs()).then(() => $patch.clear())
    })
    var cmps = parts.map(part => {
      if (typeof part === 'function') return part(collections, collectionId, itemId, $patch)
      if (typeof part === 'string') part = {path: part, label: part, type: 'text'}
      if (Array.isArray(part)) part = {path: part[0], label: part[1], type: 'text'}
      return labeledPart(collections, collectionId, itemId, $patch, part)
    })

    return observer(function () {
      var editing = $patch.keys().length > 0
      return el('div', null,
        el('form', null, cmps.map((cmp, i) => el(cmp, {key: i}))),
        editing && save.status() === 'idle' ? el(Button, {
          onClick: save.trigger,
          // disabled: !editing || save.status() !== 'idle',
        }, 'enregistrer') : null,
        editing && save.status() === 'idle' ? el(Button, {
          // disabled: !editing || save.status() !== 'idle',
          onClick: () => $patch.clear(),
        }, "Annuler") : null,
        save.status() === 'idle' ? null : el('span', null, save.status('fr'))
      )
    })
  }
}<commit_msg>improve itemFieldForm for using number values when type is 'number'<commit_after>import get from 'lodash/get'
import React from 'react'
const el = React.createElement
import { observer } from 'mobservable-react'
import { observable, map} from 'mobservable'
import Command from '../reactiveCollection/Command'

import Button from 'react-bootstrap/lib/Button'
import Input from 'react-bootstrap/lib/Input'

export var fieldEditor = function(collections, collectionId, itemId, $patch, options) {
  var model = collections[collectionId].model
  var path = options.path
  var type = options.type || 'text'
  var onChange = newVal => $patch.set(path, newVal)

  return observer(function() {
    var itemValue = model.get(itemId).value
    var partEditing = $patch.has(path)
    var value = partEditing ? $patch.get(path) : get(itemValue, path)

    if (typeof type === 'function') return el(type, {value, onChange})
    return el(Input, {
      type: type,
      // bsStyle: partEditing ? "success" : null,
      value: value,
      onChange: ev => onChange(type === 'number' ? ev.target.valueAsNumber : ev.target.value),
    })
  })
}

export var labeledPart = function(collections, collectionId, itemId, $patch, options) {
  var label = options.label
  var innerView = options.view
  var cmp = typeof innerView === 'function' ?
    innerView(collections, collectionId, itemId, $patch, options) :
    fieldEditor(collections, collectionId, itemId, $patch, options)

  return function () {
    return el(Input, {label: label, help: options.help},
      el(cmp)
    )
  }
}

export default function (parts) {
  return function (collections, collectionId, itemId) {
    var model = collections[collectionId].model
    var $patch = map()
    var save = new Command(() => {
      return model.patch(itemId, $patch.toJs()).then(() => $patch.clear())
    })
    var cmps = parts.map(part => {
      if (typeof part === 'function') return part(collections, collectionId, itemId, $patch)
      if (typeof part === 'string') part = {path: part, label: part, type: 'text'}
      if (Array.isArray(part)) part = {path: part[0], label: part[1], type: 'text'}
      return labeledPart(collections, collectionId, itemId, $patch, part)
    })

    return observer(function () {
      var editing = $patch.keys().length > 0
      return el('div', null,
        el('form', null, cmps.map((cmp, i) => el(cmp, {key: i}))),
        editing && save.status() === 'idle' ? el(Button, {
          onClick: save.trigger,
          // disabled: !editing || save.status() !== 'idle',
        }, 'enregistrer') : null,
        editing && save.status() === 'idle' ? el(Button, {
          // disabled: !editing || save.status() !== 'idle',
          onClick: () => $patch.clear(),
        }, "Annuler") : null,
        save.status() === 'idle' ? null : el('span', null, save.status('fr'))
      )
    })
  }
}<|endoftext|>