<commit_before>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); }/*,
        containment: "window"*/
    });

    // for(var squareId in relations) {
    //     var windId = "#" + relations[squareId].windId;
    //     $(windId).resizable({
    //         resize: function(event) {
    //             relations[squareId].dims.prevHeight = $(this).height();
    //             relations[squareId].dims.prevWidth = $(this).width();
    //         },
    //         minHeight: relations[squareId].dims.initHeight,
    //         minWidth: relations[squareId].dims.initWidth
    //     })
    // }

    $(".square").click(function() {
        $(this).css("background-color", "rgba(255, 255, 255, 0.7)");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).hasClass("exit")) {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background-color", "transparent");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open closed window
        $(windId).addClass("opened");
        $(windId).addClass("active");

        if(windId === "#pic_window") {
            $("#image_slider").css({"width": "5460px"});
        }

        // randomize position only when opened the first time
        if($(windId).hasClass("new")) {
            css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
            css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
            $(windId).removeClass("new");
        }
        $(windId).css(css);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<commit_msg>added slight delay to opening windows for flare<commit_after>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); }/*,
        containment: "window"*/
    });

    // for(var squareId in relations) {
    //     var windId = "#" + relations[squareId].windId;
    //     $(windId).resizable({
    //         resize: function(event) {
    //             relations[squareId].dims.prevHeight = $(this).height();
    //             relations[squareId].dims.prevWidth = $(this).width();
    //         },
    //         minHeight: relations[squareId].dims.initHeight,
    //         minWidth: relations[squareId].dims.initWidth
    //     })
    // }

    $(".square").click(function() {
        $(this).css("background-color", "rgba(255, 255, 255, 0.7)");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).hasClass("exit")) {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background-color", "transparent");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open new window (with delay for flare)
        $("*").css("cursor", "progress");
        var rand = Math.floor(Math.random() * 600);
        setTimeout(function() {
            $(windId).addClass("opened");
            $(windId).addClass("active");

            if(windId === "#pic_window") {
                $("#image_slider").css({"width": "5460px"});
            }

            // randomize position only when opened the first time
            if($(windId).hasClass("new")) {
                css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
                css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
                $(windId).removeClass("new");
            }

            $(windId).css(css);
            $("*").css("cursor", "default");
        }, rand);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<|endoftext|>


<commit_before>/* global require */

var $ = require('jquery'),
  Pryv = require('pryv');

var masterToken,
  lang,
  returnURL,
  referer,
  console,
  serviceInfoUrlArea,
  permissionsArea,
  clientDataArea,
  oauthState,
  submitButton,
  toggleDev,
  permissionsViewInactive,
  apiEndpointArea,
  tokenArea,
  domainArea,
  requestingAppId,
  pryvServiceInfoUrl;

var defaultPermissions = [{
  streamId: 'diary',
  defaultName: 'Journal',
  level: 'read'
}];

/**
 * Initialize access page
 */
window.onload = function () {
  // Load ressources
  masterToken = $('#masterToken');
  lang = $('#languageCode');
  referer = $('#referer');
  returnURL = $('#returnURL');
  console = $('#console');
  serviceInfoUrlArea = $('#serviceInfoUrlArea');
  permissionsArea = $('#permissionsArea');
  clientDataArea = $('#clientDataArea');
  oauthState = $('#oauthState');
  submitButton = $('#submitButton');
  toggleDev = $('#toggleDev');
  permissionsViewInactive = $('#permissionsViewInactive');
  apiEndpointArea = $('#apiEndpointArea');
  tokenArea = $('#tokenArea');
  domainArea = $('#domainArea');
  requestingAppId = $('#requestingAppId');

  permissionsAreaState(false);
  pryvServiceInfoUrl = Pryv.Browser.serviceInfoFromUrl() || 'https://reg.pryv.me/service/info';
  serviceInfoUrlArea.val(pryvServiceInfoUrl);
  masterToken.prop('checked', false);
  permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  masterToken.click(masterTokenManagement);
  submitButton.click(requestAccess);

  // Toggle dev options
  toggleDevOptions();
  toggleDev.click(toggleDevOptions);

};

/**
 * Change view and permissions to fit a master token app access
 */
function masterTokenManagement() {
  var masterTokenPermissions = [{
    streamId: '*',
    level: 'manage'
  }];

  if (masterToken.is(':checked')) {
    try {
      defaultPermissions = JSON.parse(permissionsArea.val());
      permissionsArea.val(JSON.stringify(masterTokenPermissions, null, '  '));
      permissionsAreaState(true);
      permissionsViewInactive.css({ 'display': 'unset' });
    } catch (err) {
      logToConsole(err);
    }
  } else {
    permissionsViewInactive.css({ 'display': 'none' });
    permissionsAreaState(false);
    permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  }
}

/**
 * Disable/activate inputs for permissions area
 * @param state {Boolean}: activation state
 */
function permissionsAreaState(state) {
  permissionsArea.prop('disabled', state);
}

/**
 * Prints to console a message/error
 * @param text {String}: the message to print
 */
function logToConsole(text) {
  console.append(text + '\n');
  if (console.length) {
    console.scrollTop(console[0].scrollHeight - console.height());
  }
}

/**
 * Process the form and request access
 */
function requestAccess() {

  var settings = {};
  var authRequest = {
    requestingAppId: false,
    referer: null,
    languageCode: false,
    permissionsArea: false,
    returnURL: false,
    callbacks: {}
  };
  authRequest.requestingAppId = requestingAppId.val();

  if (authRequest.requestingAppId.length < 6) {
    return alert('RequestingAppId is invalid!');
  }

  // Dev and advanced settings
  authRequest.languageCode = lang.val();
  if (authRequest.languageCode === 'default') { delete authRequest.languageCode; }

  authRequest.returnURL = returnURL.val();
  authRequest.oauthState = oauthState.val();
  authRequest.referer = referer.val() || null;

  try {
    authRequest.requestedPermissions = JSON.parse(permissionsArea.val());

    // Add clientData if any
    var clientData = clientDataArea.val();
    if (clientData.length > 0) {
      authRequest.clientData = JSON.parse(clientData);
    }

    settings.spanButtonID = 'pryvButton';

    settings.onStateChange = function (state) {
      logToConsole('##pryvAuthStateChange \t ' + JSON.stringify(state));
      if (state.id === Pryv.Browser.AuthStates.AUTHORIZED) {
        apiEndpointArea.text(state.apiEndpoint);
        logToConsole('# Auth succeeded for user ' + state.apiEndpoint);
      }
      if (state.id === Pryv.Browser.AuthStates.LOGOUT) {
        logToConsole('# Logout');
      }
    };

    settings.authRequest = authRequest;

    Pryv.Browser.setupAuth(settings, serviceInfoUrlArea.val());
  } catch (e) {
    logToConsole('Error in Access params: ' + e);
  }
}

/**
 * Hide/show advanced dev. options panel and reset to default values
 */
function toggleDevOptions() {
  returnURL.val('auto#');
  lang.val('default');
  lang.parent().parent().toggle();
  referer.parent().parent().toggle();
  returnURL.parent().parent().toggle();
  oauthState.parent().parent().hide();
}<commit_msg>Removed trailing callbacks property<commit_after>/* global require */

var $ = require('jquery'),
  Pryv = require('pryv');

var masterToken,
  lang,
  returnURL,
  referer,
  console,
  serviceInfoUrlArea,
  permissionsArea,
  clientDataArea,
  oauthState,
  submitButton,
  toggleDev,
  permissionsViewInactive,
  apiEndpointArea,
  tokenArea,
  domainArea,
  requestingAppId,
  pryvServiceInfoUrl;

var defaultPermissions = [{
  streamId: 'diary',
  defaultName: 'Journal',
  level: 'read'
}];

/**
 * Initialize access page
 */
window.onload = function () {
  // Load ressources
  masterToken = $('#masterToken');
  lang = $('#languageCode');
  referer = $('#referer');
  returnURL = $('#returnURL');
  console = $('#console');
  serviceInfoUrlArea = $('#serviceInfoUrlArea');
  permissionsArea = $('#permissionsArea');
  clientDataArea = $('#clientDataArea');
  oauthState = $('#oauthState');
  submitButton = $('#submitButton');
  toggleDev = $('#toggleDev');
  permissionsViewInactive = $('#permissionsViewInactive');
  apiEndpointArea = $('#apiEndpointArea');
  tokenArea = $('#tokenArea');
  domainArea = $('#domainArea');
  requestingAppId = $('#requestingAppId');

  permissionsAreaState(false);
  pryvServiceInfoUrl = Pryv.Browser.serviceInfoFromUrl() || 'https://reg.pryv.me/service/info';
  serviceInfoUrlArea.val(pryvServiceInfoUrl);
  masterToken.prop('checked', false);
  permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  masterToken.click(masterTokenManagement);
  submitButton.click(requestAccess);

  // Toggle dev options
  toggleDevOptions();
  toggleDev.click(toggleDevOptions);

};

/**
 * Change view and permissions to fit a master token app access
 */
function masterTokenManagement() {
  var masterTokenPermissions = [{
    streamId: '*',
    level: 'manage'
  }];

  if (masterToken.is(':checked')) {
    try {
      defaultPermissions = JSON.parse(permissionsArea.val());
      permissionsArea.val(JSON.stringify(masterTokenPermissions, null, '  '));
      permissionsAreaState(true);
      permissionsViewInactive.css({ 'display': 'unset' });
    } catch (err) {
      logToConsole(err);
    }
  } else {
    permissionsViewInactive.css({ 'display': 'none' });
    permissionsAreaState(false);
    permissionsArea.val(JSON.stringify(defaultPermissions, null, '  '));
  }
}

/**
 * Disable/activate inputs for permissions area
 * @param state {Boolean}: activation state
 */
function permissionsAreaState(state) {
  permissionsArea.prop('disabled', state);
}

/**
 * Prints to console a message/error
 * @param text {String}: the message to print
 */
function logToConsole(text) {
  console.append(text + '\n');
  if (console.length) {
    console.scrollTop(console[0].scrollHeight - console.height());
  }
}

/**
 * Process the form and request access
 */
function requestAccess() {

  var settings = {};
  var authRequest = {
    requestingAppId: false,
    referer: null,
    languageCode: false,
    permissionsArea: false,
    returnURL: false
  };
  authRequest.requestingAppId = requestingAppId.val();

  if (authRequest.requestingAppId.length < 6) {
    return alert('RequestingAppId is invalid!');
  }

  // Dev and advanced settings
  authRequest.languageCode = lang.val();
  if (authRequest.languageCode === 'default') { delete authRequest.languageCode; }

  authRequest.returnURL = returnURL.val();
  authRequest.oauthState = oauthState.val();
  authRequest.referer = referer.val() || null;

  try {
    authRequest.requestedPermissions = JSON.parse(permissionsArea.val());

    // Add clientData if any
    var clientData = clientDataArea.val();
    if (clientData.length > 0) {
      authRequest.clientData = JSON.parse(clientData);
    }

    settings.spanButtonID = 'pryvButton';

    settings.onStateChange = function (state) {
      logToConsole('##pryvAuthStateChange \t ' + JSON.stringify(state));
      if (state.id === Pryv.Browser.AuthStates.AUTHORIZED) {
        apiEndpointArea.text(state.apiEndpoint);
        logToConsole('# Auth succeeded for user ' + state.apiEndpoint);
      }
      if (state.id === Pryv.Browser.AuthStates.LOGOUT) {
        logToConsole('# Logout');
      }
    };

    settings.authRequest = authRequest;

    Pryv.Browser.setupAuth(settings, serviceInfoUrlArea.val());
  } catch (e) {
    logToConsole('Error in Access params: ' + e);
  }
}

/**
 * Hide/show advanced dev. options panel and reset to default values
 */
function toggleDevOptions() {
  returnURL.val('auto#');
  lang.val('default');
  lang.parent().parent().toggle();
  referer.parent().parent().toggle();
  returnURL.parent().parent().toggle();
  oauthState.parent().parent().hide();
}<|endoftext|>


<commit_before>// Promise might be already declared if Node.js/io.js is new enough. `const`
// theoretically wouldn't work in those cases.
var Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs')),
	path = require('path'),
	_ = require('underscore');

// Express
const express = require('express'),
	app = express();

var lilypond = require('./lib/lilypond');

// Serve static files from ./htdocs
app.use(express.static(__dirname + '/htdocs'));
app.use('/css/', express.static(__dirname + '/node_modules/normalize.css'));
app.use('/js/', express.static(__dirname + '/node_modules/requirejs'));
app.use('/js/CodeMirror/', express.static(__dirname + '/node_modules/codemirror'));
// We don't need the extended features right now.
app.use(require('body-parser').urlencoded({extended: false}));

// Use underscore.js for templating.
const cache = {};
app.engine('html', function (path, options, callback) {
	if (cache[path]) {
		return Promise.resolve(options)
			.then(cache[path])
			.nodeify(callback);
	}

	fs.readFileAsync(path, 'utf8')
		.then(function (str) {
			cache[path] = _.template(str);
			return cache[path](options);
		}).nodeify(callback);
});
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

// Default score
const defaultScore = fs.readFileSync(__dirname + '/default.ly', 'utf8');

// DB
const scores = require('./lib/db');

const MAX_ATTEMPTS = 5;
function getNewId(attempt) {
	attempt = attempt || 0;
	const id = Math.random().toString(36).substring(2, 8);

	return scores.get(id, 1).then(function () {
		if (++attempt >= MAX_ATTEMPTS) {
			return Promise.reject(new Error('Too many attempts for new ID'));
		}
		return getNewId(attempt);
	}, function () {
		return id;
	})
}

app.post('/save', function(req, res) {
	const code = req.body.code,
		version = req.body.version || 'stable';
	var id;

	new Promise(function(fulfill, reject) {
		if (req.body.id) return fulfill(req.body.id);
		getNewId().then(fulfill, reject);
	}).then(function(_id) {
		id = _id;
	}).then(function() {
		return scores.save(id, code, version);
	}).then(function (info) {
		res.send(info);
	}).catch(function (err) {
		res.status(500).send('Internal server error: ' +
			(err.text || err.message || '')
		);
		console.error(err.err || err);
	}).catch(console.error);
});

var mkdirp = Promise.promisify(require('mkdirp'));
app.post('/prepare_preview', function(req, res) {
	const code = req.body.code;
	var id,
		tempDir,
		tempSrc,
		response = {};

	new Promise(function(fulfill, reject) {
		if (req.body.id) return fulfill(req.body.id);
		getNewId().then(fulfill, reject);
	}).then(function(_id) {
		id = _id;
		tempDir = __dirname + '/render/' + _id;
		tempSrc = tempDir + '/score.ly';
		response.id = _id;
	}).then(function() {
		return mkdirp(tempDir)
		.then(function() {
			return fs.writeFileAsync(tempSrc, code);
		}).catch(function (err) {
			return Promise.reject({ text: 'Cannot write file', err: err});
		});
	}).then(function() {
		return lilypond.compile(tempDir, 'score.ly', req.body.version)
		.then(function (ret) {
			response.output = ret;
			return fs.accessAsync(
				__dirname + '/render/' + id + '/rendered' + '.png',
				fs.R_OK
			).then(function () {
				response.pages = 1;
				return fs.renameAsync(
					__dirname + '/render/' + id + '/rendered' + '.png',
					__dirname + '/render/' + id + '/rendered' + '-page1' + '.png'
				).catch(function (err) {
					return Promise.reject({ text: 'file rename failed', err: err });
				});
			}, function () {
				return countPages(id, 1).then(function (pages) {
					response.pages = pages;
				});
			})
		}, function (err) {
			response.error = err;
			response.pages = 0;
		});
	}).then(function () {
		// res.send.bind(res, response) doesn't work because Express.js supports
		// a two-argument form of res.send.
		res.send(response);
	}).catch(function (err) {
		res.status(500).send('Internal server error: ' +
			(err.text || err.message || '')
		);
		console.error(err.err || err);
	}).catch(console.error);
});

app.get('/preview', function(req, res) {
	const id = req.query.id,
		page = req.query.page || 1;

	res.sendFile(__dirname + '/render/' + id + '/rendered' + '-page' + page + '.png');
});

app.get('/downloadPDF', function(req, res) {
	const id = req.query.id;

	res.download(__dirname + '/render/' + id + '/rendered' + '.pdf', 'score.pdf');
});

app.get('/downloadMidi', function(req, res) {
	const id = req.query.id;

	res.download(__dirname + '/render/' + id + '/rendered' + '.midi', 'score.midi');
});

var versions;
function handleMain(req, res, next) {
	const id = req.params.id,
		revision = req.params.revision || 1;

	if (!id) {
		return res.render('index.html', {
			score: JSON.stringify({
				id: '',
				revision: '0',
				code: defaultScore,
			}),
			versions: versions,
		});
	}

	scores.get(id, revision)
		.then(function (score) {
			score.id = id;
			score.revision = revision;
			res.render('index.html', {
				score: JSON.stringify(score), versions: versions});
		}).catch(function(err) {
			if (err.notFound) {
				return res.status(404).send('Score not found');
			}
			res.status(500).send('Internal server error');
			console.error(err);
		}).catch(console.error);
}
lilypond.versions().then(function(_versions) {
	versions = _versions;
	app.get('/:id?/:revision?', handleMain);
});

app.get('/raw/:id/:revision?', function(req, res, next) {
	const id = req.params.id,
		revision = req.params.revision || 1;

	res.set('Content-Type', 'text/plain');
	scores.get(id, revision)
		.then(function (score) {
			res.send(score.code);
		}).catch(function(err) {
			if (err.notFound) {
				return res.status(404).send('Score not found');
			}
			res.status(500).send('Internal server error');
			console.error(err);
		}).catch(console.error);
});

const port = process.env.LISTEN_PORT || 3001;
app.listen(port);
console.log('Listening on port ' + port + '.');

function countPages(id) {
	const re = new RegExp(id + '-page.*\.png');
	return fs.readdirAsync(__dirname + '/render').then(function (files) {
		return files.filter(function (f) {
			return re.test(f);
		}).length;
	});
}
<commit_msg>Remove pointless string concat<commit_after>// Promise might be already declared if Node.js/io.js is new enough. `const`
// theoretically wouldn't work in those cases.
var Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs')),
	path = require('path'),
	_ = require('underscore');

// Express
const express = require('express'),
	app = express();

var lilypond = require('./lib/lilypond');

// Serve static files from ./htdocs
app.use(express.static(__dirname + '/htdocs'));
app.use('/css/', express.static(__dirname + '/node_modules/normalize.css'));
app.use('/js/', express.static(__dirname + '/node_modules/requirejs'));
app.use('/js/CodeMirror/', express.static(__dirname + '/node_modules/codemirror'));
// We don't need the extended features right now.
app.use(require('body-parser').urlencoded({extended: false}));

// Use underscore.js for templating.
const cache = {};
app.engine('html', function (path, options, callback) {
	if (cache[path]) {
		return Promise.resolve(options)
			.then(cache[path])
			.nodeify(callback);
	}

	fs.readFileAsync(path, 'utf8')
		.then(function (str) {
			cache[path] = _.template(str);
			return cache[path](options);
		}).nodeify(callback);
});
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

// Default score
const defaultScore = fs.readFileSync(__dirname + '/default.ly', 'utf8');

// DB
const scores = require('./lib/db');

const MAX_ATTEMPTS = 5;
function getNewId(attempt) {
	attempt = attempt || 0;
	const id = Math.random().toString(36).substring(2, 8);

	return scores.get(id, 1).then(function () {
		if (++attempt >= MAX_ATTEMPTS) {
			return Promise.reject(new Error('Too many attempts for new ID'));
		}
		return getNewId(attempt);
	}, function () {
		return id;
	})
}

app.post('/save', function(req, res) {
	const code = req.body.code,
		version = req.body.version || 'stable';
	var id;

	new Promise(function(fulfill, reject) {
		if (req.body.id) return fulfill(req.body.id);
		getNewId().then(fulfill, reject);
	}).then(function(_id) {
		id = _id;
	}).then(function() {
		return scores.save(id, code, version);
	}).then(function (info) {
		res.send(info);
	}).catch(function (err) {
		res.status(500).send('Internal server error: ' +
			(err.text || err.message || '')
		);
		console.error(err.err || err);
	}).catch(console.error);
});

var mkdirp = Promise.promisify(require('mkdirp'));
app.post('/prepare_preview', function(req, res) {
	const code = req.body.code;
	var id,
		tempDir,
		tempSrc,
		response = {};

	new Promise(function(fulfill, reject) {
		if (req.body.id) return fulfill(req.body.id);
		getNewId().then(fulfill, reject);
	}).then(function(_id) {
		id = _id;
		tempDir = __dirname + '/render/' + _id;
		tempSrc = tempDir + '/score.ly';
		response.id = _id;
	}).then(function() {
		return mkdirp(tempDir)
		.then(function() {
			return fs.writeFileAsync(tempSrc, code);
		}).catch(function (err) {
			return Promise.reject({ text: 'Cannot write file', err: err});
		});
	}).then(function() {
		return lilypond.compile(tempDir, 'score.ly', req.body.version)
		.then(function (ret) {
			response.output = ret;
			return fs.accessAsync(
				__dirname + '/render/' + id + '/rendered.png',
				fs.R_OK
			).then(function () {
				response.pages = 1;
				return fs.renameAsync(
					__dirname + '/render/' + id + '/rendered.png',
					__dirname + '/render/' + id + '/rendered-page1' + '.png'
				).catch(function (err) {
					return Promise.reject({ text: 'file rename failed', err: err });
				});
			}, function () {
				return countPages(id, 1).then(function (pages) {
					response.pages = pages;
				});
			})
		}, function (err) {
			response.error = err;
			response.pages = 0;
		});
	}).then(function () {
		// res.send.bind(res, response) doesn't work because Express.js supports
		// a two-argument form of res.send.
		res.send(response);
	}).catch(function (err) {
		res.status(500).send('Internal server error: ' +
			(err.text || err.message || '')
		);
		console.error(err.err || err);
	}).catch(console.error);
});

app.get('/preview', function(req, res) {
	const id = req.query.id,
		page = req.query.page || 1;

	res.sendFile(__dirname + '/render/' + id + '/rendered' + '-page' + page + '.png');
});

app.get('/downloadPDF', function(req, res) {
	const id = req.query.id;

	res.download(__dirname + '/render/' + id + '/rendered' + '.pdf', 'score.pdf');
});

app.get('/downloadMidi', function(req, res) {
	const id = req.query.id;

	res.download(__dirname + '/render/' + id + '/rendered' + '.midi', 'score.midi');
});

var versions;
function handleMain(req, res, next) {
	const id = req.params.id,
		revision = req.params.revision || 1;

	if (!id) {
		return res.render('index.html', {
			score: JSON.stringify({
				id: '',
				revision: '0',
				code: defaultScore,
			}),
			versions: versions,
		});
	}

	scores.get(id, revision)
		.then(function (score) {
			score.id = id;
			score.revision = revision;
			res.render('index.html', {
				score: JSON.stringify(score), versions: versions});
		}).catch(function(err) {
			if (err.notFound) {
				return res.status(404).send('Score not found');
			}
			res.status(500).send('Internal server error');
			console.error(err);
		}).catch(console.error);
}
lilypond.versions().then(function(_versions) {
	versions = _versions;
	app.get('/:id?/:revision?', handleMain);
});

app.get('/raw/:id/:revision?', function(req, res, next) {
	const id = req.params.id,
		revision = req.params.revision || 1;

	res.set('Content-Type', 'text/plain');
	scores.get(id, revision)
		.then(function (score) {
			res.send(score.code);
		}).catch(function(err) {
			if (err.notFound) {
				return res.status(404).send('Score not found');
			}
			res.status(500).send('Internal server error');
			console.error(err);
		}).catch(console.error);
});

const port = process.env.LISTEN_PORT || 3001;
app.listen(port);
console.log('Listening on port ' + port + '.');

function countPages(id) {
	const re = new RegExp(id + '-page.*\.png');
	return fs.readdirAsync(__dirname + '/render').then(function (files) {
		return files.filter(function (f) {
			return re.test(f);
		}).length;
	});
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  i<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if<|endoftext|>


<commit_before>/*
 * cmdrjs
 * Version 1.0.0-alpha
 * Copyright 2014 Shaftware.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Project: https://github.com/shaftware/cmdrjs
 */

; (function (define) {
    define(['jquery'], function ($) {

        var version = '1.0.0-alpha',
            commands = {},
            activated = false,
            template = '

<textarea class="prompt" spellcheck="false" />

',
            container,
            input,
            prompt,
            output,
            outputLine,
            queue = [],
            history = [],
            historyIndex = -1,
            config = {
                autoOpen: false,
                openKey: 96,
                closeKey: 27,
                echo: true
            };

        var cmdr = {
            activate: activate,
            deactivate: deactivate,
            reactivate: reactivate,
            open: open,
            close: close,
            read: read,
            readLine: readLine,
            write: write,
            writeLine: writeLine,
            clear: clear,
            execute: execute,
            setup: setup,
            commands: commands,
            config: config,
            version: version
        };

        cmdr.setup('CLS', function () {
            this.clear();
        });

        cmdr.setup('EXIT', function () {
            this.close();
        });

        cmdr.setup('ECHO', function (arg) {
            var toggle = arg.toUpperCase();
            if (toggle === 'ON') {
                this.config.echo = true;
            } else if (toggle === 'OFF') {
                this.config.echo = false;
            } else {
                this.writeLine(arg);
            }
        }, { parse: false });

        return cmdr;

        function activate() {
            if (activated) return;

            container = $(template).appendTo('body');
            input = $('.input', container);
            prompt = $('.prompt', container);
            output = $('.output', container);

            $(document).on('keypress.cmdr', function (event) {
                if (!isOpen() && !$(event.target).is('input, textarea, select') && checkKey(event, config.openKey)) {
                    event.preventDefault();
                    open();
                } else if (isOpen() && checkKey(event, config.closeKey)) {
                    close();
                }
            });

            prompt.on('keydown', function (event) {
                switch (event.keyCode) {
                    case 13:
                        var command = prompt.val();
                        if (command) {
                            historyAdd(command);
                            execute(command);
                        }
                        return false;
                    case 38:
                        historyBack();
                        return false;
                    case 40:
                        historyForward();
                        return false;
                    case 9:
                        return false;
                }
                return true;
            });

            container.on('click', function (event) {
                if (!$(event.target).is('.input *, .output *')) {
                    prompt.focus();
                }
            });

            activated = true;

            if (config.autoOpen) {
                open();
            }
        }

        function deactivate() {
            if (!activated) return;

            container.remove();
            container = null;
            input = null;
            prompt = null;
            output = null;

            $(document).off('keypress.cmdr');

            activated = false;
        }

        function reactivate() {
            if (activated) {
                deactivate();
            }
            activate();
        }

        function isOpen() {
            return container.is(':visible');
        }

        function open() {
            if (!activated) return;

            container.show();
            prompt.focus();
        }

        function close() {
            if (!activated) return;

            container.hide();
            prompt.blur();
        }

        function read(capture) {
            // allow only to run while command is running
            // return deferred
            // resolve on keypress
            // prevent char if capture is true
        }

        function readLine() {
            // allow only to run while command is running
            // return deferred
            // resolve on submit
        }

        function write(value, cssClass) {
            if (!activated) return;

            value = '' + value;

            var outputValue = $('').addClass(cssClass).text(value);
            if (!outputLine) {
                outputLine = $('
').appendTo(output);
            }
            outputLine.append(outputValue);
        }

        function writeLine(value, cssClass) {
            if (!activated) return;

            write(value, cssClass);
            outputLine = null;
        }

        function clear() {
            if (!activated) return;

            output.html('');
        }

        function execute(command) {
            if (!activated) return;

            if (typeof command !== 'string') {
                throw 'Invalid command';
            }

            command = command.trim();

            if (config.echo) {
                writeLine('> ' + command);
            }

            var parsed = parseCommand(command);
            var definition = commands[parsed.name.toUpperCase()];
            if (!definition) {
                writeLine('Invalid command', 'error');
                return;
            }

            prompt.prop('disabled', true).val('').hide();

            var args = parsed.args;
            if (!definition.parse) {
                args = [parsed.arg];
            }

            var result = definition.callback.apply(cmdr, args);

            $.when(result).done(function () {
                prompt.prop('disabled', false).show();
                input.css('visibility', 'visible');
            });
        }

        function setup(name, callback, settings) {
            var definition = resolveDefinition(name, callback, settings);
            commands[definition.name] = definition;
        }

        function historyAdd(command) {
            history.unshift(command);
            historyIndex = -1;
        }

        function historyBack() {
            if (history.length > historyIndex + 1) {
                historyIndex++;
                prompt.val(history[historyIndex]);
            }
        }

        function historyForward() {
            if (historyIndex > 0) {
                historyIndex--;
                prompt.val(history[historyIndex]);
            }
        }

        function parseCommand(command) {
            var exp = /[^\s"]+|"([^"]*)"/gi,
                name = null,
                arg = null,
                args = [];

            do {
                var match = exp.exec(command);
                if (match != null) {
                    var value = match[1] ? match[1] : match[0];
                    if (match.index === 0) {
                        name = value;
                        arg = command.substr(value.length + (match[1] ? 3 : 1));
                    } else {
                        args.push(value);
                    }
                }
            } while (match != null);

            return {
                name: name,
                arg: arg,
                args: args
            };
        }

        function resolveDefinition(name, callback, settings) {
            if (typeof name !== 'string') {
                settings = callback;
                callback = name;
                name = null;
            }
            if (typeof callback !== 'function') {
                settings = callback;
                callback = null;
            }

            var definition = {
                name: name,
                callback: callback,
                parse: true
            };

            $.extend(definition, settings);

            if (typeof definition.name !== 'string' ||
                typeof definition.callback !== 'function') {
                throw 'Invalid command definition';
            }

            definition.name = definition.name.toUpperCase();

            return definition;
        }

        function checkKey(event, key) {
            return (event.which || event.keyCode) === key;
        }
    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    } else {
        window['cmdr'] = factory(window['jQuery']);
    }
}));
<commit_msg>readline method<commit_after>/*
 * cmdrjs
 * Version 1.0.0-alpha
 * Copyright 2014 Shaftware.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Project: https://github.com/shaftware/cmdrjs
 */

; (function (define) {
    define(['jquery'], function ($) {

        var version = '1.0.0-alpha',
            commands = {},
            activated = false,
            template = '

<textarea class="prompt" spellcheck="false" />

',
            container,
            input,
            prompt,
            output,
            outputLine,
            current,
            queue = [],
            history = [],
            historyIndex = -1,
            config = {
                autoOpen: false,
                openKey: 96,
                closeKey: 27,
                echo: true
            };

        var cmdr = {
            activate: activate,
            deactivate: deactivate,
            reactivate: reactivate,
            open: open,
            close: close,
            read: read,
            readLine: readLine,
            write: write,
            writeLine: writeLine,
            clear: clear,
            execute: execute,
            setup: setup,
            commands: commands,
            config: config,
            version: version
        };

        cmdr.setup('CLS', function () {
            this.clear();
        });

        cmdr.setup('EXIT', function () {
            this.close();
        });

        cmdr.setup('ECHO', function (arg) {
            var toggle = arg.toUpperCase();
            if (toggle === 'ON') {
                this.config.echo = true;
            } else if (toggle === 'OFF') {
                this.config.echo = false;
            } else {
                this.writeLine(arg);
            }
        }, { parse: false });

        return cmdr;

        function activate() {
            if (activated) return;

            container = $(template).appendTo('body');
            input = $('.input', container);
            prompt = $('.prompt', container);
            output = $('.output', container);

            $(document).on('keypress.cmdr', function (event) {
                if (!isOpen() && !$(event.target).is('input, textarea, select') && checkKey(event, config.openKey)) {
                    event.preventDefault();
                    open();
                } else if (isOpen() && checkKey(event, config.closeKey)) {
                    close();
                }
            });

            prompt.on('keydown', function (event) {
                switch (event.keyCode) {
                    case 13:
                        var command = prompt.val();
                        if (command) {
                            historyAdd(command);
                            execute(command);
                        }
                        return false;
                    case 38:
                        historyBack();
                        return false;
                    case 40:
                        historyForward();
                        return false;
                    case 9:
                        return false;
                }
                return true;
            });

            container.on('click', function (event) {
                if (!$(event.target).is('.input *, .output *')) {
                    prompt.focus();
                }
            });

            activated = true;

            if (config.autoOpen) {
                open();
            }
        }

        function deactivate() {
            if (!activated) return;

            container.remove();
            container = null;
            input = null;
            prompt = null;
            output = null;

            $(document).off('keypress.cmdr');

            activated = false;
        }

        function reactivate() {
            if (activated) {
                deactivate();
            }
            activate();
        }

        function isOpen() {
            return container.is(':visible');
        }

        function open() {
            if (!activated) return;

            container.show();
            prompt.focus();
        }

        function close() {
            if (!activated) return;

            container.hide();
            prompt.blur();
        }

        function read(capture) {
            // allow only to run while command is running
            // return deferred
            // resolve on keypress
            // prevent char if capture is true
        }

        function readLine() {
            if (!activated) return null;
            if (!current) return null;

            activatePrompt();

            current.readLine = $.Deferred().done(function() {
                deactivatePrompt();
            });

            return current.readLine.promise();
        }

        function write(value, cssClass) {
            if (!activated) return;

            value = '' + value;

            var outputValue = $('').addClass(cssClass).text(value);
            if (!outputLine) {
                outputLine = $('
').appendTo(output);
            }
            outputLine.append(outputValue);
        }

        function writeLine(value, cssClass) {
            if (!activated) return;

            write(value, cssClass);
            outputLine = null;
        }

        function clear() {
            if (!activated) return;

            output.html('');
        }

        function execute(command) {
            if (!activated) return;
            if (current) return;

            if (typeof command !== 'string') {
                throw 'Invalid command';
            }

            command = command.trim();

            if (config.echo) {
                writeLine('> ' + command);
            }

            var parsed = parseCommand(command);
            var definition = commands[parsed.name.toUpperCase()];
            if (!definition) {
                writeLine('Invalid command', 'error');
                return;
            }

            current = {
                command: command,
                definition: definition
            };

            deactivatePrompt();

            var args = parsed.args;
            if (!definition.parse) {
                args = [parsed.arg];
            }

            var result = definition.callback.apply(cmdr, args);

            $.when(result).done(function () {
                current = null;
                if (queue.length > 0) {
                    execute(queue.shift());
                }
                activatePrompt();
            });
        }

        function setup(name, callback, settings) {
            var definition = resolveDefinition(name, callback, settings);
            commands[definition.name] = definition;
        }

        function activatePrompt() {
            prompt.prop('disabled', false).show();
        }

        function deactivatePrompt() {
            prompt.prop('disabled', true).val('').hide();
        }

        function historyAdd(command) {
            history.unshift(command);
            historyIndex = -1;
        }

        function historyBack() {
            if (history.length > historyIndex + 1) {
                historyIndex++;
                prompt.val(history[historyIndex]);
            }
        }

        function historyForward() {
            if (historyIndex > 0) {
                historyIndex--;
                prompt.val(history[historyIndex]);
            }
        }

        function parseCommand(command) {
            var exp = /[^\s"]+|"([^"]*)"/gi,
                name = null,
                arg = null,
                args = [];

            do {
                var match = exp.exec(command);
                if (match != null) {
                    var value = match[1] ? match[1] : match[0];
                    if (match.index === 0) {
                        name = value;
                        arg = command.substr(value.length + (match[1] ? 3 : 1));
                    } else {
                        args.push(value);
                    }
                }
            } while (match != null);

            return {
                name: name,
                arg: arg,
                args: args
            };
        }

        function resolveDefinition(name, callback, settings) {
            if (typeof name !== 'string') {
                settings = callback;
                callback = name;
                name = null;
            }
            if (typeof callback !== 'function') {
                settings = callback;
                callback = null;
            }

            var definition = {
                name: name,
                callback: callback,
                parse: true
            };

            $.extend(definition, settings);

            if (typeof definition.name !== 'string' ||
                typeof definition.callback !== 'function') {
                throw 'Invalid command definition';
            }

            definition.name = definition.name.toUpperCase();

            return definition;
        }

        function checkKey(event, key) {
            return (event.which || event.keyCode) === key;
        }
    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    } else {
        window['cmdr'] = factory(window['jQuery']);
    }
}));
<|endoftext|>


<commit_before>/*global before,describe,it */
var assert = require('chai').assert;

var commons = require('../lib/compress-commons');
var ZipArchiveEntry = commons.ZipArchiveEntry;
var GeneralPurposeBit = require('../lib/archivers/zip/general-purpose-bit');
var UnixStat = require('../lib/archivers/zip/unix-stat');

var entry;
// Jan 03 2013 14:26:38 GMT
var testDate = new Date(Date.UTC(2013, 0, 3, 14, 26, 38, 0));

describe('ZipArchiveEntry', function() {

  beforeEach(function() {
    entry = new ZipArchiveEntry('file.txt');
  });

  // Getters
  describe('#getCentralDirectoryExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getComment', function() {
    it('should return the comment', function() {
      entry.setComment('file comment');
      assert.equal(entry.getComment(), 'file comment');
    });
  });

  describe('#getCompressedSize', function() {
    it('should return the compressed size', function() {
      entry.csize = 10;
      assert.equal(entry.getCompressedSize(), 10);
    });
  });

  describe('#getCrc', function() {
    it('should return the CRC32', function() {
      entry.crc = 585446183;
      assert.equal(entry.getCrc(), 585446183);
    });
  });

  describe('#getExternalAttributes', function() {
    it('should return the external attributes', function() {
      entry.exattr = 2180972576;
      assert.equal(entry.getExternalAttributes(), 2180972576);
    });
  });

  describe('#getExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getGeneralPurposeBit', function() {
    it('should return the general purpose bit flag', function() {
      var gpb = new GeneralPurposeBit();
      gpb.useDataDescriptor(true);
      entry.gpb = gpb;
      assert.equal(entry.getGeneralPurposeBit(), gpb);
    });
  });

  describe('#getInternalAttributes', function() {
    it('should return the internal attributes', function() {
      entry.inattr = 2180972576;
      assert.equal(entry.getInternalAttributes(), 2180972576);
    });
  });

  describe('#getLastModifiedDate', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getLocalFileDataExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getMethod', function() {
    it('should return the compression method', function() {
      entry.method = 0;
      assert.equal(entry.getMethod(), 0);
    });
  });

  describe('#getName', function() {
    it('should return the name', function() {
      entry.name = 'file.txt';
      assert.equal(entry.getName(), 'file.txt');
    });
  });

  describe('#getPlatform', function() {
    it('should return the platform', function() {
      entry.platform = 3;
      assert.equal(entry.getPlatform(), 3);
    });
  });

  describe('#getSize', function() {
    it('should return the size', function() {
      entry.size = 25;
      assert.equal(entry.getSize(), 25);
    });
  });

  describe('#getTime', function() {
    it('should return a Date object', function() {
      entry.time = 1109607251;
      assert.typeOf(entry.getTime(), 'Date');
    });
  });

  describe('#getTimeDos', function() {
    it('should return a number', function() {
      entry.time = 1109607251;
      assert.typeOf(entry.getTimeDos(), 'number');
    });
  });

  describe('#getUnixMode', function() {
    it('should return the unix filemode', function() {
      entry.mode = 0777;
      entry.exattr = 2180972576;
      entry.platform = 3;
      assert.equal(entry.getUnixMode(), 0100777);
    });

    it('should set proper external attributes for an unix directory', function () {
      entry = new ZipArchiveEntry('directory/');
      entry.setUnixMode(0777);

      assert.ok(entry.getPlatform(), 3);
      assert.ok(entry.isDirectory());

      var exattr = entry.getExternalAttributes() >> 16;
      assert.equal(exattr & 040000, 040000);
    });
  });

  describe('#getVersionNeededToExtract', function() {
    it.skip('should be tested', function() {

    });
  });

  // Setters
  describe('#setComment', function() {
    it('should set internal variable', function() {
      entry.setComment('file comment');
      assert.propertyVal(entry, 'comment', 'file comment');
    });

    it('should set utf8 bit when receiving strings byte count != string length', function() {
      entry.setComment('ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäçèéêëìíîïñòóôõöùúûüýÿ');
      assert.ok(entry.getGeneralPurposeBit().usesUTF8ForNames());
    });
  });

  describe('#setCompressedSize', function() {
    it('should set internal variable', function() {
      entry.setCompressedSize(10);
      assert.propertyVal(entry, 'csize', 10);
    });
  });

  describe('#setCrc', function() {
    it('should set internal variable', function() {
      entry.setCrc(585446183);
      assert.propertyVal(entry, 'crc', 585446183);
    });
  });

  describe('#setExternalAttributes', function() {
    it('should set internal variable', function() {
      entry.setExternalAttributes(2180972576);
      assert.propertyVal(entry, 'exattr', 2180972576);
    });
  });

  describe('#setExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#setGeneralPurposeBit', function() {
    it('should set internal variable', function() {
      var gpb = new GeneralPurposeBit();
      gpb.useDataDescriptor(true);
      entry.setGeneralPurposeBit(gpb);
      assert.propertyVal(entry, 'gpb', gpb);
    });
  });

  describe('#setInternalAttributes', function() {
    it('should set internal variable', function() {
      entry.setInternalAttributes(2180972576);
      assert.propertyVal(entry, 'inattr', 2180972576);
    });
  });

  describe('#setMethod', function() {
    it('should set internal variable', function() {
      entry.setMethod(8);
      assert.propertyVal(entry, 'method', 8);
    });
  });

  describe('#setName', function() {
    it('should set internal variable', function() {
      entry.setName('file.txt');
      assert.propertyVal(entry, 'name', 'file.txt');
    });

    it('should allow ./ at the beginning of path', function() {
      entry.setName('./file.txt');
      assert.propertyVal(entry, 'name', './file.txt');
    });

    it('should clean windows style paths', function() {
      entry.setName('\\windows\\file.txt');
      assert.propertyVal(entry, 'name', 'windows/file.txt');

      entry.setName('c:\\this\\path\\file.txt');
      assert.propertyVal(entry, 'name', 'this/path/file.txt');

      entry.setName('\\\\server\\share\\');
      assert.propertyVal(entry, 'name', 'server/share/');
    });

    it('should set utf8 bit when receiving strings byte count != string length', function() {
      entry.setName('ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäçèéêëìíîïñòóôõöùúûüýÿ.txt');
      assert.ok(entry.getGeneralPurposeBit().usesUTF8ForNames());
    });
  });

  describe('#setPlatform', function() {
    it('should set internal variable', function() {
      entry.setPlatform(3);
      assert.propertyVal(entry, 'platform', 3);
    });
  });

  describe('#setSize', function() {
    it('should set internal variable', function() {
      entry.setSize(15);
      assert.propertyVal(entry, 'size', 15);
    });
  });

  describe('#setTime', function() {
    it('should set internal variable', function() {
      entry.setTime(testDate);
      assert.propertyVal(entry, 'time', 1109619539);
    });
  });

  describe('#setUnixMode', function() {
    it('should set internal variables', function() {
      entry.setUnixMode(0777);
      assert.propertyVal(entry, 'exattr', 2180972576);
      assert.propertyVal(entry, 'mode', 0777);
      assert.equal(entry.getUnixMode(), 0100777);

    });

    it('should also preserve filetype information', function() {
      entry.setUnixMode(0120755);
      assert.propertyVal(entry, 'exattr', 2716663840);
      assert.propertyVal(entry, 'mode', 0755);
      assert.equal(entry.getUnixMode(), 0120755);
    });
  });

  describe('#setVersionNeededToExtract', function() {
    it.skip('should be tested', function() {

    });
  });

  // Others
  describe('#isDirectory', function() {
    it('should return a boolean based on name of entry', function() {
      assert.notOk(entry.isDirectory());
      entry.setName('some/directory/');
      assert.ok(entry.isDirectory());
    });
  });

  describe('#isUnixSymlink', function() {
      it('should work ...', function() {
        entry.setUnixMode(UnixStat.LINK_FLAG);
        assert.ok(entry.isUnixSymlink());
        entry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DIR_FLAG);
        assert.notOk(entry.isUnixSymlink());
      });
  });
});
<commit_msg>add test for isUnixSymlink<commit_after>/*global before,describe,it */
var assert = require('chai').assert;

var commons = require('../lib/compress-commons');
var ZipArchiveEntry = commons.ZipArchiveEntry;
var GeneralPurposeBit = require('../lib/archivers/zip/general-purpose-bit');
var UnixStat = require('../lib/archivers/zip/unix-stat');

var entry;
// Jan 03 2013 14:26:38 GMT
var testDate = new Date(Date.UTC(2013, 0, 3, 14, 26, 38, 0));

describe('ZipArchiveEntry', function() {

  beforeEach(function() {
    entry = new ZipArchiveEntry('file.txt');
  });

  // Getters
  describe('#getCentralDirectoryExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getComment', function() {
    it('should return the comment', function() {
      entry.setComment('file comment');
      assert.equal(entry.getComment(), 'file comment');
    });
  });

  describe('#getCompressedSize', function() {
    it('should return the compressed size', function() {
      entry.csize = 10;
      assert.equal(entry.getCompressedSize(), 10);
    });
  });

  describe('#getCrc', function() {
    it('should return the CRC32', function() {
      entry.crc = 585446183;
      assert.equal(entry.getCrc(), 585446183);
    });
  });

  describe('#getExternalAttributes', function() {
    it('should return the external attributes', function() {
      entry.exattr = 2180972576;
      assert.equal(entry.getExternalAttributes(), 2180972576);
    });
  });

  describe('#getExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getGeneralPurposeBit', function() {
    it('should return the general purpose bit flag', function() {
      var gpb = new GeneralPurposeBit();
      gpb.useDataDescriptor(true);
      entry.gpb = gpb;
      assert.equal(entry.getGeneralPurposeBit(), gpb);
    });
  });

  describe('#getInternalAttributes', function() {
    it('should return the internal attributes', function() {
      entry.inattr = 2180972576;
      assert.equal(entry.getInternalAttributes(), 2180972576);
    });
  });

  describe('#getLastModifiedDate', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getLocalFileDataExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#getMethod', function() {
    it('should return the compression method', function() {
      entry.method = 0;
      assert.equal(entry.getMethod(), 0);
    });
  });

  describe('#getName', function() {
    it('should return the name', function() {
      entry.name = 'file.txt';
      assert.equal(entry.getName(), 'file.txt');
    });
  });

  describe('#getPlatform', function() {
    it('should return the platform', function() {
      entry.platform = 3;
      assert.equal(entry.getPlatform(), 3);
    });
  });

  describe('#getSize', function() {
    it('should return the size', function() {
      entry.size = 25;
      assert.equal(entry.getSize(), 25);
    });
  });

  describe('#getTime', function() {
    it('should return a Date object', function() {
      entry.time = 1109607251;
      assert.typeOf(entry.getTime(), 'Date');
    });
  });

  describe('#getTimeDos', function() {
    it('should return a number', function() {
      entry.time = 1109607251;
      assert.typeOf(entry.getTimeDos(), 'number');
    });
  });

  describe('#getUnixMode', function() {
    it('should return the unix filemode', function() {
      entry.mode = 0777;
      entry.exattr = 2180972576;
      entry.platform = 3;
      assert.equal(entry.getUnixMode(), 0100777);
    });

    it('should set proper external attributes for an unix directory', function () {
      entry = new ZipArchiveEntry('directory/');
      entry.setUnixMode(0777);

      assert.ok(entry.getPlatform(), 3);
      assert.ok(entry.isDirectory());

      var exattr = entry.getExternalAttributes() >> 16;
      assert.equal(exattr & 040000, 040000);
    });
  });

  describe('#getVersionNeededToExtract', function() {
    it.skip('should be tested', function() {

    });
  });

  // Setters
  describe('#setComment', function() {
    it('should set internal variable', function() {
      entry.setComment('file comment');
      assert.propertyVal(entry, 'comment', 'file comment');
    });

    it('should set utf8 bit when receiving strings byte count != string length', function() {
      entry.setComment('ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäçèéêëìíîïñòóôõöùúûüýÿ');
      assert.ok(entry.getGeneralPurposeBit().usesUTF8ForNames());
    });
  });

  describe('#setCompressedSize', function() {
    it('should set internal variable', function() {
      entry.setCompressedSize(10);
      assert.propertyVal(entry, 'csize', 10);
    });
  });

  describe('#setCrc', function() {
    it('should set internal variable', function() {
      entry.setCrc(585446183);
      assert.propertyVal(entry, 'crc', 585446183);
    });
  });

  describe('#setExternalAttributes', function() {
    it('should set internal variable', function() {
      entry.setExternalAttributes(2180972576);
      assert.propertyVal(entry, 'exattr', 2180972576);
    });
  });

  describe('#setExtra', function() {
    it.skip('should be tested', function() {

    });
  });

  describe('#setGeneralPurposeBit', function() {
    it('should set internal variable', function() {
      var gpb = new GeneralPurposeBit();
      gpb.useDataDescriptor(true);
      entry.setGeneralPurposeBit(gpb);
      assert.propertyVal(entry, 'gpb', gpb);
    });
  });

  describe('#setInternalAttributes', function() {
    it('should set internal variable', function() {
      entry.setInternalAttributes(2180972576);
      assert.propertyVal(entry, 'inattr', 2180972576);
    });
  });

  describe('#setMethod', function() {
    it('should set internal variable', function() {
      entry.setMethod(8);
      assert.propertyVal(entry, 'method', 8);
    });
  });

  describe('#setName', function() {
    it('should set internal variable', function() {
      entry.setName('file.txt');
      assert.propertyVal(entry, 'name', 'file.txt');
    });

    it('should allow ./ at the beginning of path', function() {
      entry.setName('./file.txt');
      assert.propertyVal(entry, 'name', './file.txt');
    });

    it('should clean windows style paths', function() {
      entry.setName('\\windows\\file.txt');
      assert.propertyVal(entry, 'name', 'windows/file.txt');

      entry.setName('c:\\this\\path\\file.txt');
      assert.propertyVal(entry, 'name', 'this/path/file.txt');

      entry.setName('\\\\server\\share\\');
      assert.propertyVal(entry, 'name', 'server/share/');
    });

    it('should set utf8 bit when receiving strings byte count != string length', function() {
      entry.setName('ÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäçèéêëìíîïñòóôõöùúûüýÿ.txt');
      assert.ok(entry.getGeneralPurposeBit().usesUTF8ForNames());
    });
  });

  describe('#setPlatform', function() {
    it('should set internal variable', function() {
      entry.setPlatform(3);
      assert.propertyVal(entry, 'platform', 3);
    });
  });

  describe('#setSize', function() {
    it('should set internal variable', function() {
      entry.setSize(15);
      assert.propertyVal(entry, 'size', 15);
    });
  });

  describe('#setTime', function() {
    it('should set internal variable', function() {
      entry.setTime(testDate);
      assert.propertyVal(entry, 'time', 1109619539);
    });
  });

  describe('#setUnixMode', function() {
    it('should set internal variables', function() {
      entry.setUnixMode(0777);
      assert.propertyVal(entry, 'exattr', 2180972576);
      assert.propertyVal(entry, 'mode', 0777);
      assert.equal(entry.getUnixMode(), 0100777);

    });

    it('should also preserve filetype information', function() {
      entry.setUnixMode(0120755);
      assert.propertyVal(entry, 'exattr', 2716663840);
      assert.propertyVal(entry, 'mode', 0755);
      assert.equal(entry.getUnixMode(), 0120755);
    });
  });

  describe('#setVersionNeededToExtract', function() {
    it.skip('should be tested', function() {

    });
  });

  // Others
  describe('#isDirectory', function() {
    it('should return a boolean based on name of entry', function() {
      assert.notOk(entry.isDirectory());
      entry.setName('some/directory/');
      assert.ok(entry.isDirectory());
    });
  });

  describe('#isUnixSymlink', function() {
      it('should verify symlinks can be set', function() {
        entry.setUnixMode(UnixStat.LINK_FLAG);
        assert.ok(entry.isUnixSymlink());
        entry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DIR_FLAG);
        assert.notOk(entry.isUnixSymlink());
      });
  });
});
<|endoftext|>


<commit_before>/**
 *
 */

function Keyboard(){

	var me=this;
	me.rb=require('robotjs');

};
Keyboard.prototype.longKeyPress=function(key, cb, time){
	var me=this;
	var i=setInterval(function(){

		me.rb.keyToggle(key, true);

	},250);

	setTimeout(function(){

		clearInterval(i);
		me.rb.keyToggle(key, false);
		if((typeof cb)=='function')cb();
	},time);

	return me;
}

Keyboard.prototype.keyTapArray=function(keys, cb, delay){
	var me=this;
	var i=setInterval(function(){

		me.rb.keyTap(keys.shift());
		if(keys.length==0){
			clearInterval(i);
			if((typeof cb)=='function')cb();
		}

	},delay);

	return me;
}

//made this to test long key press with only two keyToggles
Keyboard.prototype.longKeyPressSimple=function(key, cb, time){
	var me=this;

	me.rb.keyToggle(key, true);

	setTimeout(function(){

		me.rb.keyToggle(key, false);
		if((typeof cb)=='function')cb();
	},time);
}

module.exports=new Keyboard();<commit_msg>log tap and toggles<commit_after>/**
 *
 */

function Keyboard(){

	var me=this;
	me.rb=require('robotjs');

};
Keyboard.prototype.longKeyPress=function(key, cb, time){
	var me=this;
	var c=0;
	var i=setInterval(function(){

		me.rb.keyToggle(key, true);
		c++;
		if(c%4==0){
			//don't want to blast the console.
			console.log('pulse: '+key+' down');
		}
	},250);

	setTimeout(function(){

		clearInterval(i);
		me.rb.keyToggle(key, false);
		console.log('send: '+key+' up');
		if((typeof cb)=='function')cb();
	},time);

	return me;
}

Keyboard.prototype.keyTapArray=function(keys, cb, delay){
	var me=this;
	var i=setInterval(function(){

		var key=keys.shift();
		me.rb.keyTap(key);
		console.log('tap: '+key);
		if(keys.length==0){
			clearInterval(i);
			if((typeof cb)=='function')cb();
		}

	},delay);

	return me;
}

//made this to test long key press with only two keyToggles
Keyboard.prototype.longKeyPressSimple=function(key, cb, time){
	var me=this;

	me.rb.keyToggle(key, true);

	setTimeout(function(){

		me.rb.keyToggle(key, false);
		if((typeof cb)=='function')cb();
	},time);
}

module.exports=new Keyboard();<|endoftext|>


<commit_before>$(document).ready(function () {

	$(".editable").each(function (e) {

		var $el = $(this);
		var elType = $el.prop('nodeName').toLowerCase();
		var elClass = $el.attr("class");
		var elID = $el.attr("id");

		$el.qtip({
			content: $("#solutions").html(), // Use a pre-formatted element for the content
			position: {
				target: 'mouse', // Position it where the click was...
				adjust: { mouse: false } // ...but don't follow the mouse
			},
			hide: 'unfocus',
			show: 'mousedown', // Can't use click event for this, sorry!
			events: {
				show: function(event, api) {

					event.stopPropagation();

					$(this).find(".element-selected").text("<"+elType+" id='"+elID+"' class='"+elClass+"'/>");

					/*
					 * event.originalEvent contains the event that caused the callback to be fired.
					 * event.originalEvent.button tells us which button was clicked e.g. 1= left, 2 = right;
					 */
					if(event.originalEvent.button !== 2) {

						// IE might throw an error calling preventDefault(), so use a try/catch block.
						try { event.preventDefault(); } catch(e) {}
					}
				}
			},
			style: {
				classes: 'qtip-blue qtip-shadow'
			}
		});

		// Little snippet that stops the regular right-click menu from appearing
		$el.bind('contextmenu', function(){ return false; });
		$el.parent().bind('contextmenu', function(){ return false; });
	});
});<commit_msg>refactoring how the home page right click functions<commit_after>$(document).ready(function () {

	$(".editable").each(function (e) {

		var $el = $(this);
		var elType = $el.prop('nodeName').toLowerCase();
		var elClass = $el.attr("class");
		var elID = $el.attr("id");

		$el.qtip({
			content: $("#solutions").html(), // Use a pre-formatted element for the content
			position: {
				target: 'mouse', // Position it where the click was...
				adjust: { mouse: false } // ...but don't follow the mouse
			},
			hide: 'unfocus mousedown',
			show: 'mouseup', // Can't use click event for this, sorry!
			events: {
				show: function(event, api) {

					event.stopPropagation();

					$(this).find(".element-selected").text("<"+elType+" id='"+elID+"' class='"+elClass+"'/>");

					/*
					 * event.originalEvent contains the event that caused the callback to be fired.
					 * event.originalEvent.button tells us which button was clicked e.g. 1= left, 2 = right;
					 */
					if(event.originalEvent.button !== 2) {

						// IE might throw an error calling preventDefault(), so use a try/catch block.
						try { event.preventDefault(); } catch(e) {}
					}
				}
			},
			style: {
				classes: 'qtip-blue qtip-shadow'
			}
		});

		// Little snippet that stops the regular right-click menu from appearing
		$el.bind('contextmenu', function(){ return false; });
		$el.parent().bind('contextmenu', function(){ return false; });
	});
});<|endoftext|>


<commit_before>const PersistentCollection = require("djs-collection-persistent");
const util = require('util');

exports.run = (client, message, args) => {
    const guildSettings = client.guildSettings;

    const guilds = client.guilds.map((value, key) => `${value} (${key})`).join("\n");

    if(args[0]) {
        if(args[0].toLowerCase() === 'guilds') {
            // guildList = "";
            // guildIDs.forEach(g => {
            //     guildList += client.guilds[g] + " (" +g + ")\n";
            // });
            //
            message.channel.send(`Guilds: \`\`\`${guilds}\`\`\``);
            // message.channel.send(`Guilds: \`\`\`${util.inspect(guildIDs)}\`\`\``);
        } else if(args[0].toLowerCase() === 'roles') {
            message.channel.send(`Roles: \`\`\`${util.inspect(message.member.roles)}\`\`\``);
        }

        // message.channel.send(`Settings: \`\`\`${util.inspect(guildSettings.keyArray())}\`\`\``);

        // guilds = client.guilds.keyArray();
        // guilds.forEach(guild => {
        //     message.channel.send(`Config for guild ${guild} is \n\`\`\`${util.inspect(guildSettings.get(guild))}\`\`\``);
        // });
    }
};

exports.conf = {
    enabled: true,
    guildOnly: false,
    aliases: [],
    permLevel: 4,
    type: 'owner'
};

exports.help = {
    name: 'list',
    description: 'List stats about the bot.',
    usage: 'list [guilds]'
};

<commit_msg>Removed one of the test commmands from the repo because it shouldn't be needed<commit_after><|endoftext|>


<commit_before>function submit_onload() {
    assignments_get(update_asn_list)
}

function update_asn_list(data, status) {
    var assignments = data.assignments
    console.log("assignments = " + assignments)
    $.each(assignments, function(key, value) {
        var uuid = value
        assignment_get(update_asn_list_item, uuid)
    });
}

function update_asn_list_item(data, status) {

    console.log["data = " + data]
    keys = Object.keys(data)
    console.log["keys = " + keys]
    uuid = keys[0]
    console.log["uuid = " + uuid]
    var assignment = data[uuid]
    $("select#assignment")
        .append($("<option>", { value : uuid})
                .text(assignment.name));

}

$("button#logout").click(function() {
    logout()
});
<commit_msg>Fixed log statments<commit_after>function submit_onload() {
    assignments_get(update_asn_list)
}

function update_asn_list(data, status) {
    var assignments = data.assignments
    console.log("assignments = " + assignments)
    $.each(assignments, function(key, value) {
        var uuid = value
        assignment_get(update_asn_list_item, uuid)
    });
}

function update_asn_list_item(data, status) {

    console.log("data = " + data)
    keys = Object.keys(data)
    console.log("keys = " + keys)
    uuid = keys[0]
    console.log("uuid = " + uuid)
    var assignment = data[uuid]
    $("select#assignment")
        .append($("<option>", { value : uuid})
                .text(assignment.name));

}

$("button#logout").click(function() {
    logout()
});
<|endoftext|>


<commit_before>/* @flow */

import replHistory from '../replHistory';

const readline = require('readline');
const fs = require('fs');

jest.mock('readline');

readline.createInterface = jest.fn(() => ({
  _addHistory: jest.fn(() => 'qux'),
  history: [],
}));

jest.mock('fs');

fs.stat = jest.fn((path: string, cb: Function) => {
  cb(null, { size: 10 });
});

const streamWrite = jest.fn();

fs.createWriteStream = jest.fn(() => ({
  write: streamWrite,
}));

fs.createReadStream = jest.fn((path: string, opts: Object) => ({
  on: jest.fn((type: string, cb: Function) => {
    switch (type) {
      case 'data':
        return path === 'nonExistent' ? cb('') : cb('foo\nbar\n');
      case 'end':
        return cb();

      default: return undefined;
    }
  }),
}));

describe('replHistory', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('creates a readline interface and saves history when terminal is true', () => {
    replHistory({ terminal: true });

    expect(readline.createInterface).toHaveBeenCalled();
    expect(fs.createWriteStream).toHaveBeenCalled();
  });
  it('doesn\'t save history when terminal is false', () => {
    replHistory({});

    expect(fs.createWriteStream).not.toHaveBeenCalled();
  });

  it('loads REPL history from file if existent path and historySize passed', () => {
    const rl = replHistory({
      historySize: 10,
      path: '~/.history',
      terminal: true,
    });

    expect(rl.history.length).toBeGreaterThan(0);
  });

  describe('doesn\'t load REPL history from file', () => {
    it('if path isn\'t passed in options', () => {
      const rl = replHistory({
        terminal: true,
        historySize: 10,
      });

      expect(fs.stat).not.toHaveBeenCalled();
      expect(rl.history).toEqual([]);
    });

    it('if path doesn\'t exist', () => {
      const rl = replHistory({
        terminal: true,
        historySize: 10,
        path: 'nonExistent',
      });

      expect(rl.history).toEqual(['']);
    });

    it('if historySize not passed in options', () => {
      const rl = replHistory({
        terminal: true,
        path: 'foo',
      });

      expect(fs.stat).not.toHaveBeenCalled();
      expect(rl.history).toEqual([]);
    });
  });

  describe('adds lines to history', () => {
    it('persists them to file', () => {
      const rl = replHistory({
        historySize: 10,
        path: '~/.history',
        terminal: true,
      });

      rl._addHistory(); // eslint-disable-line no-underscore-dangle
      expect(streamWrite.mock.calls.length).toBe(1);
      expect(streamWrite).toHaveBeenCalledWith('qux\n', 'utf8');
    });
  });
});
<commit_msg>bump replHistory coverage to 100%<commit_after>/* @flow */

import replHistory from '../replHistory';

const readline = require('readline');
const fs = require('fs');

jest.mock('readline');

readline.createInterface = jest.fn(() => ({
  _addHistory: jest.fn(() => 'qux'),
  history: [],
}));

jest.mock('fs');

fs.stat = jest.fn((path: string, cb: Function) => {
  cb(null, { size: 10 });
});

fs.close = jest.fn((_: number, cb: Function) => cb());
fs.rename = jest.fn((old: string, newName: string, cb: Function) => cb());
fs.open = jest.fn((path: string, flags: string, cb: Function) => cb());
fs.unlink = jest.fn((_: string, cb: Function) => cb());

const streamWrite = jest.fn();

fs.createWriteStream = jest.fn(() => ({
  write: streamWrite,
  fd: 42,
}));

fs.createReadStream = jest.fn((path: string, opts: Object) => ({
  on: jest.fn((type: string, cb: Function) => {
    switch (type) {
      case 'data':
        return path === 'nonExistent' ? cb('') : cb('foo\nbar\n');
      case 'end':
        return cb();

      default: return undefined;
    }
  }),
}));

describe('replHistory', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('creates a readline interface and saves history when terminal is true', () => {
    replHistory({ terminal: true });

    expect(readline.createInterface).toHaveBeenCalled();
    expect(fs.createWriteStream).toHaveBeenCalled();
  });
  it('doesn\'t save history when terminal is false', () => {
    replHistory({});

    expect(fs.createWriteStream).not.toHaveBeenCalled();
  });

  it('loads REPL history from file if existent path and historySize passed', () => {
    const rl = replHistory({
      historySize: 10,
      path: '~/.history',
      terminal: true,
    });

    expect(rl.history.length).toBeGreaterThan(0);
  });

  describe('doesn\'t load REPL history from file', () => {
    it('if path isn\'t passed in options', () => {
      const rl = replHistory({
        terminal: true,
        historySize: 10,
      });

      expect(fs.stat).not.toHaveBeenCalled();
      expect(rl.history).toEqual([]);
    });

    it('if path doesn\'t exist', () => {
      const rl = replHistory({
        terminal: true,
        historySize: 10,
        path: 'nonExistent',
      });

      expect(rl.history).toEqual(['']);
    });

    it('if historySize not passed in options', () => {
      const rl = replHistory({
        terminal: true,
        path: 'foo',
      });

      expect(fs.stat).not.toHaveBeenCalled();
      expect(rl.history).toEqual([]);
    });
  });

  describe('adds lines to history', () => {
    it('persists them to file', () => {
      const rl = replHistory({
        historySize: 10,
        path: '~/.history',
        terminal: true,
      });

      rl._addHistory(); // eslint-disable-line no-underscore-dangle
      expect(streamWrite.mock.calls.length).toBe(1);
      expect(streamWrite).toHaveBeenCalledWith('qux\n', 'utf8');
    });
  });

  describe('renames an existent repl history file when it\'s past the maximum size', () => {
    const fsStat = fs.stat;

    beforeEach(() => {
      fs.stat = jest.fn()
        .mockImplementationOnce((path: string, cb: Function) => cb(null, { size: 0x10000000 }))
        .mockImplementationOnce((path: string, cb: Function) => cb(null, { size: 0x100 }));
    });

    afterAll(() => {
      fs.stat = fsStat;
    });

    it('if an old one doesn\'t exist', () => {
      fs.exists = jest.fn((_: string, cb: Function) => cb(false));

      replHistory({
        historySize: 10,
        path: '~/.history',
        terminal: true,
      });

      expect(fs.rename).toHaveBeenCalled();
      expect(fs.unlink).not.toHaveBeenCalled();
    });

    it('unlinking the old one if necessary', () => {
      fs.exists = jest.fn((_: string, cb: Function) => cb(true));

      replHistory({
        historySize: 10,
        path: '~/.history',
        terminal: true,
      });

      expect(fs.unlink).toHaveBeenCalled();
      expect(fs.rename).toHaveBeenCalled();
    });
  });
});
<|endoftext|>


<commit_before>{
  "code": 200,
  "status": "Ok",
  "copyright": "© 2016 MARVEL",
  "attributionText": "Data provided by Marvel. © 2016 MARVEL",
  "attributionHTML": "Data provided by Marvel. © 2016 MARVEL",
  "etag": "6cc693fe33938a475fb99437e14b3a0d52d83f94",
  "data": {
    "offset": 0,
    "limit": 20,
    "total": 1,
    "count": 1,
    "results": [
      {
        "id": 1009718,
        "name": "Wolverine",
        "description": "Born with super-human senses and the power to heal from almost any wound, Wolverine was captured by a secret Canadian organization and given an unbreakable skeleton and claws. Treated like an animal, it took years for him to control himself. Now, he's a premiere member of both the X-Men and the Avengers.",
        "modified": "2014-06-10T16:13:25-0400",
        "thumbnail": {
          "path": "http://i.annihil.us/u/prod/marvel/i/mg/2/60/537bcaef0f6cf",
          "extension": "jpg"
        },
        "resourceURI": "http://gateway.marvel.com/v1/public/characters/1009718",
        "comics": {
          "available": 1831,
          "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009718/comics",
          "items": [
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/41112",
              "name": "5 Ronin (Hardcover)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/41113",
              "name": "5 Ronin (Hardcover)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/38756",
              "name": "5 Ronin (2010) #1"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/36162",
              "name": "5 Ronin (2010) #1 (AJA Cover)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/29317",
              "name": "ACTS OF VENGEANCE CROSSOVERS OMNIBUS (Hardcover)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/29318",
              "name": "ACTS OF VENGEANCE CROSSOVERS OMNIBUS (DM Only) (Hardcover)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/24017",
              "name": "Agents of Atlas (2009) #3 (Wolverine Art Appreciation Variant)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/24221",
              "name": "Agents of Atlas (2009) #5"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/24222",
              "name": "Agents of Atlas (2009) #5 (MCGUINNESS VARIANT)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12690",
              "name": "Alpha Flight (1983) #3"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/38564",
              "name": "Alpha Flight (2011) #7"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12671",
              "name": "Alpha Flight (1983) #13"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12675",
              "name": "Alpha Flight (1983) #16"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12676",
              "name": "Alpha Flight (1983) #17"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12694",
              "name": "Alpha Flight (1983) #33"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12695",
              "name": "Alpha Flight (1983) #34"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12715",
              "name": "Alpha Flight (1983) #52"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12716",
              "name": "Alpha Flight (1983) #53"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12725",
              "name": "Alpha Flight (1983) #61"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/comics/12753",
              "name": "Alpha Flight (1983) #87"
            }
          ],
          "returned": 20
        },
        "series": {
          "available": 442,
          "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009718/series",
          "items": [
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/12429",
              "name": "5 Ronin (2010)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/15276",
              "name": "5 Ronin (2011)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/9994",
              "name": "ACTS OF VENGEANCE CROSSOVERS OMNIBUS (2011)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/9995",
              "name": "ACTS OF VENGEANCE CROSSOVERS OMNIBUS (DM Only) (2011)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/6807",
              "name": "Agents of Atlas (2009)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/2116",
              "name": "Alpha Flight (1983 - 1994)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/13907",
              "name": "Alpha Flight (2011 - 2012)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/1983",
              "name": "Alpha Flight Classic Vol. 1 (2007)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/1987",
              "name": "Amazing Spider-Man (1963 - 1998)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/454",
              "name": "Amazing Spider-Man (1999 - 2013)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/2984",
              "name": "Amazing Spider-Man Annual (1964 - 2009)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/18142",
              "name": "Amazing X-Men (2013 - Present)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/7197",
              "name": "Anita Blake: The Laughing Corpse - Necromancer (2009)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/14818",
              "name": "Annihilators: Earthfall (2011)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/9792",
              "name": "Astonishing Spider-Man/Wolverine (2010 - 2011)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/11110",
              "name": "Astonishing Spider-Man/Wolverine (2010 - Present)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/6792",
              "name": "Astonishing Tales (2009)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/6696",
              "name": "Astonishing Tales: Wolverine/Punisher (2008 - 2009)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/744",
              "name": "Astonishing X-Men (2004 - 2013)"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/series/7576",
              "name": "Astonishing X-Men by Joss Whedon & John Cassaday (2009 - Present)"
            }
          ],
          "returned": 20
        },
        "stories": {
          "available": 2484,
          "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009718/stories",
          "items": [
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/477",
              "name": "Cover #477",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/628",
              "name": "1 of 1 - Holiday Issue",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/630",
              "name": "1 of 5 - Golgotha",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/652",
              "name": "2 of 3 - House of Broken Dreams",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1051",
              "name": "Interior #1051",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1415",
              "name": "Interior #1415",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1499",
              "name": "Interior #1499",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1632",
              "name": "Interior #1632",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1767",
              "name": "Interior #1767",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1776",
              "name": "Cover #1776",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1779",
              "name": "Interior #1779",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1803",
              "name": "Interior #1803",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1847",
              "name": "Interior #1847",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1912",
              "name": "Interior #1912",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1936",
              "name": "4 of 5 - Quiet",
              "type": "cover"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/1979",
              "name": "Interior #1979",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/2070",
              "name": "Interior #2070",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/2084",
              "name": "Interior #2084",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/2154",
              "name": "3 of 6 - Enemy of the State",
              "type": "interiorStory"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/stories/2167",
              "name": "Interior #2167",
              "type": "interiorStory"
            }
          ],
          "returned": 20
        },
        "events": {
          "available": 33,
          "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009718/events",
          "items": [
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/116",
              "name": "Acts of Vengeance!"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/227",
              "name": "Age of Apocalypse"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/233",
              "name": "Atlantis Attacks"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/310",
              "name": "Avengers VS X-Men"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/296",
              "name": "Chaos War"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/238",
              "name": "Civil War"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/318",
              "name": "Dark Reign"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/240",
              "name": "Days of Future Present"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/245",
              "name": "Enemy of the State"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/246",
              "name": "Evolutionary War"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/248",
              "name": "Fall of the Mutants"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/249",
              "name": "Fatal Attractions"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/302",
              "name": "Fear Itself"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/251",
              "name": "House of M"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/252",
              "name": "Inferno"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/253",
              "name": "Infinity Gauntlet"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/29",
              "name": "Infinity War"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/37",
              "name": "Maximum Security"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/299",
              "name": "Messiah CompleX"
            },
            {
              "resourceURI": "http://gateway.marvel.com/v1/public/events/298",
              "name": "Messiah War"
            }
          ],
          "returned": 20
        },
        "urls": [
          {
            "type": "detail",
            "url": "http://marvel.com/comics/characters/1009718/wolverine?utm_campaign=apiRef&utm_source=6f769846a34acb7b0299a000d488f562"
          },
          {
            "type": "wiki",
            "url": "http://marvel.com/universe/Wolverine_(James_Howlett)?utm_campaign=apiRef&utm_source=6f769846a34acb7b0299a000d488f562"
          },
          {
            "type": "comiclink",
            "url": "http://marvel.com/comics/characters/1009718/wolverine?utm_campaign=apiRef&utm_source=6f769846a34acb7b0299a000d488f562"
          }
        ]
      }
    ]
  }
}<commit_msg>Delete wolvie.js<commit_after><|endoftext|>