<commit_before>/**
* DiscordForge - a plugin system for Discord.
* Copyright (C) 2017 DiscordForge Development
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

const assert = require('assert');
const fs = require('fs');
const {fork} = require('child_process');
const os = require('os');
const path = require('path');
const dforgeDir = path.join(os.homedir(), '.discordforge');
const checksum = require('checksum');
describe('Files', () => {
	it('should have bootstrap.js', () => {
		if (fs.existsSync('bootstrap.js') === false)
			throw new Error('File missing.');
	});
	it('should have index.js', () => {
		if (fs.existsSync('index.js') === false)
			throw new Error('File missing.');
	});
	it('should have modloader.js', () => {
		if (fs.existsSync('modloader.js') === false)
			throw new Error('File missing.');
	});
	it('should have setup.js', () => {
		if (fs.existsSync('setup.js') === false)
			throw new Error('File missing.');
	});
	it('should have LICENSE', () => {
		if (fs.existsSync('LICENSE') === false)
			throw new Error('File missing.');
	});
});
describe('Setup', () => {
	before(function(done) {
		this.timeout(60000);
		console.log('\nThis test requires the setup script to be executed first. We will now install DiscordForge as if the end user is installing it.\n');
		let setup = fork('setup.js');
		setup.on('exit', (code) => {
			if (code !== 0)
				throw new Error(`Setup exited with code ${code}`);
			console.log('\nDone installing. We will now continue with testing.\n');
			done();
		});
	});
	it('should have made a directory in the home directory', () => {
		if (fs.existsSync(dforgeDir) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a plugins directory', () => {
		if (fs.existsSync(path.join(dforgeDir, 'plugins')) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a modloader directory', () => {
		if (fs.existsSync(path.join(dforgeDir, 'modloader')) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a modloader.js', () => {
		if (fs.existsSync(path.join(dforgeDir, 'modloader', 'modloader.js')) === false)
			throw new Error('File missing.');
	});
	it('should have made an exact copy of the modloader', () => {
		let sumCurrent, sumCopy;
		checksum.file(path.join(dforgeDir, 'modloader', 'modloader.js'), (err, sum) => {
			sumCopy = sum;
		});
		checksum.file('modloader.js', (err, sum) => {
			sumCurrent = sum;
		});
		assert.equal(sumCurrent, sumCopy);
	});
});<commit_msg>modify prep messages<commit_after>/**
* DiscordForge - a plugin system for Discord.
* Copyright (C) 2017 DiscordForge Development
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

const assert = require('assert');
const fs = require('fs');
const {fork} = require('child_process');
const os = require('os');
const path = require('path');
const dforgeDir = path.join(os.homedir(), '.discordforge');
const checksum = require('checksum');
describe('Files', () => {
	it('should have bootstrap.js', () => {
		if (fs.existsSync('bootstrap.js') === false)
			throw new Error('File missing.');
	});
	it('should have index.js', () => {
		if (fs.existsSync('index.js') === false)
			throw new Error('File missing.');
	});
	it('should have modloader.js', () => {
		if (fs.existsSync('modloader.js') === false)
			throw new Error('File missing.');
	});
	it('should have setup.js', () => {
		if (fs.existsSync('setup.js') === false)
			throw new Error('File missing.');
	});
	it('should have LICENSE', () => {
		if (fs.existsSync('LICENSE') === false)
			throw new Error('File missing.');
	});
});
describe('Setup', () => {
	before(function(done) {
		this.timeout(60000);
		console.log('\nThis test requires the setup script to be executed first. We will now install DiscordForge as if the end user is installing it.\n[Timeout: 1 minute]\n');
		let setup = fork('setup.js');
		setup.on('exit', (code) => {
			if (code !== 0)
				throw new Error(`Setup exited with code ${code}`);
			console.log('\nDone installing. We will now continue with testing.\n');
			done();
		});
	});
	it('should have made a directory in the home directory', () => {
		if (fs.existsSync(dforgeDir) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a plugins directory', () => {
		if (fs.existsSync(path.join(dforgeDir, 'plugins')) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a modloader directory', () => {
		if (fs.existsSync(path.join(dforgeDir, 'modloader')) === false)
			throw new Error('Directory missing.');
	});
	it('should have made a modloader.js', () => {
		if (fs.existsSync(path.join(dforgeDir, 'modloader', 'modloader.js')) === false)
			throw new Error('File missing.');
	});
	it('should have made an exact copy of the modloader', () => {
		let sumCurrent, sumCopy;
		checksum.file(path.join(dforgeDir, 'modloader', 'modloader.js'), (err, sum) => {
			sumCopy = sum;
		});
		checksum.file('modloader.js', (err, sum) => {
			sumCurrent = sum;
		});
		assert.equal(sumCurrent, sumCopy);
	});
});<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var anagrams = function(s) {
    var n = s.length;

    if (n === 0) return [];

    if (n === 1) return [s];

    var r = [];

    for (var i=0;i<n;++i) {
	var rest = s.substr(0,i) + s.substr(i+1);
	r.push(s[i] + rest);
    }

    return r;
};

describe('anagrams', function() {

    it('anagrams of an empty string are empty', function() {
	assert.deepEqual([], anagrams(''));
    });

    it('anagrams of a single character', function() {
	assert.deepEqual(['a'], anagrams('a'));
	assert.deepEqual(['z'], anagrams('z'));
    });

    it('anagrams of multiple characters', function() {
	assert.deepEqual(['aa','aa'], anagrams('aa'));
	assert.deepEqual(['bb','bb'], anagrams('bb'));
    });
});
<commit_msg>test passes as expected<commit_after>"use strict";

var assert = require('assert');

var anagrams = function(s) {
    var n = s.length;

    if (n === 0) return [];

    if (n === 1) return [s];

    var r = [];

    for (var i=0;i<n;++i) {
	var rest = s.substr(0,i) + s.substr(i+1);
	r.push(s[i] + rest);
    }

    return r;
};

describe('anagrams', function() {

    it('anagrams of an empty string are empty', function() {
	assert.deepEqual([], anagrams(''));
    });

    it('anagrams of a single character', function() {
	assert.deepEqual(['a'], anagrams('a'));
	assert.deepEqual(['z'], anagrams('z'));
    });

    it('anagrams of multiple characters', function() {
	assert.deepEqual(['aa','aa'], anagrams('aa'));
	assert.deepEqual(['bb','bb'], anagrams('bb'));
    });

    it('anagrams of different characters', function() {
	assert.deepEqual(['ab','ba'], anagrams('ab'));
    });
});
<|endoftext|>


<commit_before>var assert = require('assert');

var anagrams = function(word) {
  if (word.length <= 1) {
    return [word];
  } else {
    var accum = [];

    var nextCases = drop1(word);

    for (var i=0;i<nextCases.length;++i) {
       var anagramsOfSubstrings = anagrams(nextCases[i]);

       for(var j=0;j<anagramsOfSubstrings.length;++j) {
         accum.push(word[i]+anagramsOfSubstrings[j]);
       }
    }

    return accum;
  }
};

var drop1 = function(word) {
  var withOneMissing = [];
  for (var i=0;i<word.length;++i) {
    withOneMissing.push(word.substr(0,i) + word.substr(i+1));
  }
  return withOneMissing;
};

var test = function() {

  // base case
  assert.deepEqual([''], anagrams(''));
  assert.deepEqual(['a'], anagrams('a'));

  var twoLetterAnagrams = anagrams('ab');
  assert.equal(2, twoLetterAnagrams.length);

  var dropLetter = drop1('abc');
  assert.deepEqual(['bc','ac','ab'], dropLetter);

  assert.deepEqual(['ab','ba'], twoLetterAnagrams);

  var threeLetterAnagrams = anagrams('abc');
  assert.deepEqual(['abc','acb','bac','bca', 'cab', 'cba'], threeLetterAnagrams);
};

var main = function() {
  console.log(anagrams('biro'));
};

test();

main();<commit_msg>note down retro notes<commit_after>"use strict";

var assert = require('assert');

var anagrams = function(word) {
  if (word.length <= 1) {
    return [word];
  } else {
    var accum = [];

    var nextCases = drop1(word);

    for (var i=0;i<nextCases.length;++i) {
       var anagramsOfSubstrings = anagrams(nextCases[i]);

       for(var j=0;j<anagramsOfSubstrings.length;++j) {
         accum.push(word[i]+anagramsOfSubstrings[j]);
       }
    }

    return accum;
  }
};

var drop1 = function(word) {
  var withOneMissing = [];
  for (var i=0;i<word.length;++i) {
    withOneMissing.push(word.substr(0,i) + word.substr(i+1));
  }
  return withOneMissing;
};

var test = function() {

  // base case
  assert.deepEqual([''], anagrams(''));
  assert.deepEqual(['a'], anagrams('a'));

  var twoLetterAnagrams = anagrams('ab');
  assert.equal(2, twoLetterAnagrams.length);

  var dropLetter = drop1('abc');
  assert.deepEqual(['bc','ac','ab'], dropLetter);

  assert.deepEqual(['ab','ba'], twoLetterAnagrams);

  var threeLetterAnagrams = anagrams('abc');
  assert.deepEqual(['abc','acb','bac','bca', 'cab', 'cba'], threeLetterAnagrams);
};

var main = function() {
  console.log(anagrams('biro'));
};

test();

main();

// What have I learnt with this one?
// - deepEqual
// - substr
// - use strict<|endoftext|>


<commit_before>var recipe = require('./recipe-functions.js');

recipe.test();
/*
recipe.table_create('demoservice',"Leaderboard", function(err, results){
				if (err)
					throw err;
				console.log(results);
			});
			*/<commit_msg>bug fix with function calls<commit_after><|endoftext|>


<commit_before>'use strict';

const path = require('path');

const test = require('ava');
const proxyquire = require('proxyquire').noPreserveCache().noCallThru();
const devnull = require('dev-null');
const qs = require('q-stream');
const naked = require('strip-ansi');

const dummyConfig = { inputStream: devnull(), outputStream: devnull() };
const dummyCrossSpawn = { sync: () => { return { status: 0 }; } };
const dummyBudoServer = { on: () => {} };
const dummyBudo = () => dummyBudoServer;
const dummyGaze = () => {};

test('Prints `--help`', (assert) => {
  assert.plan(3);

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'man',
      'spawns `man`'
    );

    assert.is(
      args[0],
      path.resolve(__dirname, 'manpages/elm-live.1'),
      'with the right manpage'
    );
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive(['--help'], dummyConfig);

  assert.is(exitCode, 0,
    'succeeds'
  );
});

test((
  'Shouts if `elm-make` can’t be found'
), (assert) => new Promise((resolve) => {
  assert.plan(3);

  const expectedMessage = new RegExp(
`^\nelm-live:
  I can’t find the command elm-make!`
  );

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { error: { code: 'ENOENT' } };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive([], { outputStream: qs((chunk) => {
    assert.ok(
      expectedMessage.test(naked(chunk)),
      'prints an informative message'
    );

    resolve();
  }), inputStream: devnull() });

  assert.is(exitCode, 1,
    'fails'
  );
}));

test('Exits if `--no-recover`', (assert) => {
  assert.plan(4);

  const status = 59;

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { status };
  } };

  const budo = () => {
    assert.fail(
      'doesn’t start the server until errors are fixed'
    );
  };

  const elmLive = proxyquire('./source/elm-live', {
    'cross-spawn': crossSpawn, budo, gaze: dummyGaze,
  });

  assert.is(
    elmLive(['--no-recover'], dummyConfig),
    status,
    'exits with the same status as `elm-make`'
  );

  assert.is(
    elmLive([], dummyConfig),
    null,
    'keeps running otherwise'
  );
});

test('Informs of compile errors', (assert) => new Promise((resolve) => {
  assert.plan(3);

  const message = 'whatever';
  const status = 9;

  const crossSpawn = { sync: (command, _, options) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    options.stdio[1].write(message);

    return { status };
  } };

  const elmLive = proxyquire('./source/elm-live', {
    'cross-spawn': crossSpawn, budo: dummyBudo, gaze: dummyGaze,
  });

  let run = 0;
  const outputStream = qs((chunk) => {
    if (run === 0) assert.is(chunk, message,
      'prints elm-make output first'
    );

    if (run === 1) resolve(assert.is(
      naked(chunk),
      (
`\nelm-live:
  elm-make failed! You can find more info above. Keep calm and take your time
  to fix your code. We’ll try to compile it again as soon as you change a file.

`
      ),
      'prints a friendly message afterwards'
    ));

    run++;
  });

  elmLive([], { outputStream, inputStream: devnull() });
}));

test('Prints any other `elm-make` error', (assert) => new Promise((resolve) => {
  assert.plan(3);

  const message = 'whatever';
  const status = 9;

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { status, error: { toString: () => message } };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive(['--no-recover'], { outputStream: qs((chunk) => {
    assert.is(
      naked(chunk),
      (
`\nelm-live: Error while calling elm-make! This output may be helpful:
  ${ message }

`
      ),
      'prints the error’s output'
    );

    resolve();
  }), inputStream: devnull() });

  assert.is(exitCode, status,
    'exits with whatever code `elm-make` returned'
  );
}));

test('Passes correct args to `elm-make`', (assert) => {
  assert.plan(2);

  const elmLiveArgs = ['--port=77', '--no-recover'];
  const otherArgs =
    ['--anything', 'whatever', 'with whitespace', '--beep=boop', '--no-flag'];

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.same(
      args,
      otherArgs,
      'passes all not understood arguments'
    );

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(elmLiveArgs.concat(otherArgs), dummyConfig);
});

test('Disambiguates `elm-make` args with `--`', (assert) => {
  assert.plan(2);

  const elmMakeBefore =
    ['--anything', 'whatever', 'whatever 2'];
  const elmLiveBefore =
    ['--open', '--no-recover'];
  const elmMakeAfter =
    ['--port=77', '--beep=boop'];
  const allArgs = [].concat(
    elmMakeBefore,
    elmLiveBefore,
    ['--'],
    elmMakeAfter
  );

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.same(
      args,
      elmMakeBefore.concat(elmMakeAfter),
      'passes all not understood commands and all commands after the `--` ' +
      'to elm-make'
    );

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(allArgs, dummyConfig);
});

test('Redirects elm-make stdio', (assert) => new Promise((resolve) => {
  assert.plan(4);

  const elmLiveOut = (
`Hello there!
How’s it going?
`
  );
  const elmLiveErr = (
`Not too well, to be honest
`
  );

  const inputStream = {};

  const crossSpawn = { sync: (command, _, options) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.is(
      options.stdio[0],
      inputStream,
      'takes stdin from the `inputStream`'
    );

    options.stdio[1].write(elmLiveOut);
    options.stdio[2].write(elmLiveErr);

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  let run = 0;
  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(['--no-recover'], { inputStream, outputStream: qs((chunk) => {
    if (run === 0) assert.is(
      chunk,
      elmLiveOut,
      'directs stdout to the `outputStream`'
    );

    if (run === 1) resolve(assert.is(
      chunk,
      elmLiveErr,
      'directs stderr to the `outputStream`'
    ));

    run++;
  }) });
}));

test('Starts budo and gaze with correct config', (assert) => {
  assert.plan(5);

  const budo = (options) => {
    assert.is(options.port, 8000,
      'uses port 8000 by default (or the next available one)'
    );

    assert.is(options.open, false,
      'doesn’t `--open` the app by default'
    );

    assert.is(options.watchGlob, '**/*.{html,css,js}',
      'reloads the app when an HTML, JS or CSS static file changes'
    );

    assert.is(options.stream, dummyConfig.outputStream,
      'directs all output to `outputStream`'
    );

    return dummyBudoServer;
  };

  const gaze = (glob) => {
    assert.is(glob, '**/*.elm',
      'watches all `*.elm` files in the current directory ' +
      'and its subdirectories'
    );
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive([], dummyConfig);
});

test('`--open`s the default browser', (assert) => {
  assert.plan(1);

  const budo = (options) => {
    assert.is(options.open, true,
      'passes `--open` to budo'
    );

    return dummyBudoServer;
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze: dummyGaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive(['--open'], dummyConfig);
});

test('Serves at the specified `--port`', (assert) => {
  assert.plan(1);

  const portNumber = 867;

  const budo = (options) => {
    assert.is(options.port, portNumber,
      'passes `--port` to budo'
    );

    return dummyBudoServer;
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze: dummyGaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive([`--port=${ portNumber }`], dummyConfig);
});

test((
  'Watches all `**/*.elm` files in the current directory'
), (assert) => new Promise((resolve) => {
  assert.plan(4);

  const event = 'touched';
  const relativePath = 'ab/c.elm';
  const absolutePath = path.resolve(process.cwd(), relativePath);

  const watcherMock = {
    on: (what, callback) => {
      callback(event, absolutePath);
    },
  };

  const gaze = (target, callback) => {
    assert.is(target, '**/*.elm',
      'passes the right glob to gaze'
    );

    callback(null, watcherMock);
  };

  let serverStarted = false;
  const budo = () => {
    serverStarted = true;
    return dummyBudoServer;
  };

  let elmMakeRun = 0;
  const success = { status: 0, error: {} };
  const failure = { status: 77, error: {} };
  const crossSpawn = { sync: (command) => {
    if (command !== 'elm-make') return success;
    elmMakeRun++;

    if (elmMakeRun === 1) return failure;

    assert.notOk(serverStarted,
      'doesn’t start the server immediately if things go wrong'
    );

    assert.pass(
      'retries spawning `elm-make` if things go wrong the first time'
    );

    return success;
  } };

  const elmLive = proxyquire('./source/elm-live', {
    gaze, budo, 'cross-spawn': crossSpawn,
  });

  let chunkNumber = 0;
  elmLive([], { inputStream: devnull(), outputStream: qs((chunk) => {
    chunkNumber++;
    if (chunkNumber !== 3) return;

    const expectedMessage = (
`\nelm-live:
  You’ve ${ event } \`${ relativePath }\`. Rebuilding!

`
    );

    assert.is(naked(chunk), expectedMessage,
      'prints a message when a file is changed'
    );

    resolve();
  }) });
}));
<commit_msg>Account for Windows path slash in test<commit_after>'use strict';

const path = require('path');

const test = require('ava');
const proxyquire = require('proxyquire').noPreserveCache().noCallThru();
const devnull = require('dev-null');
const qs = require('q-stream');
const naked = require('strip-ansi');

const dummyConfig = { inputStream: devnull(), outputStream: devnull() };
const dummyCrossSpawn = { sync: () => { return { status: 0 }; } };
const dummyBudoServer = { on: () => {} };
const dummyBudo = () => dummyBudoServer;
const dummyGaze = () => {};

test('Prints `--help`', (assert) => {
  assert.plan(3);

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'man',
      'spawns `man`'
    );

    assert.is(
      args[0],
      path.resolve(__dirname, 'manpages/elm-live.1'),
      'with the right manpage'
    );
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive(['--help'], dummyConfig);

  assert.is(exitCode, 0,
    'succeeds'
  );
});

test((
  'Shouts if `elm-make` can’t be found'
), (assert) => new Promise((resolve) => {
  assert.plan(3);

  const expectedMessage = new RegExp(
`^\nelm-live:
  I can’t find the command elm-make!`
  );

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { error: { code: 'ENOENT' } };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive([], { outputStream: qs((chunk) => {
    assert.ok(
      expectedMessage.test(naked(chunk)),
      'prints an informative message'
    );

    resolve();
  }), inputStream: devnull() });

  assert.is(exitCode, 1,
    'fails'
  );
}));

test('Exits if `--no-recover`', (assert) => {
  assert.plan(4);

  const status = 59;

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { status };
  } };

  const budo = () => {
    assert.fail(
      'doesn’t start the server until errors are fixed'
    );
  };

  const elmLive = proxyquire('./source/elm-live', {
    'cross-spawn': crossSpawn, budo, gaze: dummyGaze,
  });

  assert.is(
    elmLive(['--no-recover'], dummyConfig),
    status,
    'exits with the same status as `elm-make`'
  );

  assert.is(
    elmLive([], dummyConfig),
    null,
    'keeps running otherwise'
  );
});

test('Informs of compile errors', (assert) => new Promise((resolve) => {
  assert.plan(3);

  const message = 'whatever';
  const status = 9;

  const crossSpawn = { sync: (command, _, options) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    options.stdio[1].write(message);

    return { status };
  } };

  const elmLive = proxyquire('./source/elm-live', {
    'cross-spawn': crossSpawn, budo: dummyBudo, gaze: dummyGaze,
  });

  let run = 0;
  const outputStream = qs((chunk) => {
    if (run === 0) assert.is(chunk, message,
      'prints elm-make output first'
    );

    if (run === 1) resolve(assert.is(
      naked(chunk),
      (
`\nelm-live:
  elm-make failed! You can find more info above. Keep calm and take your time
  to fix your code. We’ll try to compile it again as soon as you change a file.

`
      ),
      'prints a friendly message afterwards'
    ));

    run++;
  });

  elmLive([], { outputStream, inputStream: devnull() });
}));

test('Prints any other `elm-make` error', (assert) => new Promise((resolve) => {
  assert.plan(3);

  const message = 'whatever';
  const status = 9;

  const crossSpawn = { sync: (command) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    return { status, error: { toString: () => message } };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });

  const exitCode = elmLive(['--no-recover'], { outputStream: qs((chunk) => {
    assert.is(
      naked(chunk),
      (
`\nelm-live: Error while calling elm-make! This output may be helpful:
  ${ message }

`
      ),
      'prints the error’s output'
    );

    resolve();
  }), inputStream: devnull() });

  assert.is(exitCode, status,
    'exits with whatever code `elm-make` returned'
  );
}));

test('Passes correct args to `elm-make`', (assert) => {
  assert.plan(2);

  const elmLiveArgs = ['--port=77', '--no-recover'];
  const otherArgs =
    ['--anything', 'whatever', 'with whitespace', '--beep=boop', '--no-flag'];

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.same(
      args,
      otherArgs,
      'passes all not understood arguments'
    );

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(elmLiveArgs.concat(otherArgs), dummyConfig);
});

test('Disambiguates `elm-make` args with `--`', (assert) => {
  assert.plan(2);

  const elmMakeBefore =
    ['--anything', 'whatever', 'whatever 2'];
  const elmLiveBefore =
    ['--open', '--no-recover'];
  const elmMakeAfter =
    ['--port=77', '--beep=boop'];
  const allArgs = [].concat(
    elmMakeBefore,
    elmLiveBefore,
    ['--'],
    elmMakeAfter
  );

  const crossSpawn = { sync: (command, args) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.same(
      args,
      elmMakeBefore.concat(elmMakeAfter),
      'passes all not understood commands and all commands after the `--` ' +
      'to elm-make'
    );

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(allArgs, dummyConfig);
});

test('Redirects elm-make stdio', (assert) => new Promise((resolve) => {
  assert.plan(4);

  const elmLiveOut = (
`Hello there!
How’s it going?
`
  );
  const elmLiveErr = (
`Not too well, to be honest
`
  );

  const inputStream = {};

  const crossSpawn = { sync: (command, _, options) => {
    assert.is(command, 'elm-make',
      'spawns `elm-make`'
    );

    assert.is(
      options.stdio[0],
      inputStream,
      'takes stdin from the `inputStream`'
    );

    options.stdio[1].write(elmLiveOut);
    options.stdio[2].write(elmLiveErr);

    // Kill after one attempt
    return { status: 77, error: {} };
  } };

  let run = 0;
  const elmLive = proxyquire('./source/elm-live', { 'cross-spawn': crossSpawn });
  elmLive(['--no-recover'], { inputStream, outputStream: qs((chunk) => {
    if (run === 0) assert.is(
      chunk,
      elmLiveOut,
      'directs stdout to the `outputStream`'
    );

    if (run === 1) resolve(assert.is(
      chunk,
      elmLiveErr,
      'directs stderr to the `outputStream`'
    ));

    run++;
  }) });
}));

test('Starts budo and gaze with correct config', (assert) => {
  assert.plan(5);

  const budo = (options) => {
    assert.is(options.port, 8000,
      'uses port 8000 by default (or the next available one)'
    );

    assert.is(options.open, false,
      'doesn’t `--open` the app by default'
    );

    assert.is(options.watchGlob, '**/*.{html,css,js}',
      'reloads the app when an HTML, JS or CSS static file changes'
    );

    assert.is(options.stream, dummyConfig.outputStream,
      'directs all output to `outputStream`'
    );

    return dummyBudoServer;
  };

  const gaze = (glob) => {
    assert.is(glob, '**/*.elm',
      'watches all `*.elm` files in the current directory ' +
      'and its subdirectories'
    );
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive([], dummyConfig);
});

test('`--open`s the default browser', (assert) => {
  assert.plan(1);

  const budo = (options) => {
    assert.is(options.open, true,
      'passes `--open` to budo'
    );

    return dummyBudoServer;
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze: dummyGaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive(['--open'], dummyConfig);
});

test('Serves at the specified `--port`', (assert) => {
  assert.plan(1);

  const portNumber = 867;

  const budo = (options) => {
    assert.is(options.port, portNumber,
      'passes `--port` to budo'
    );

    return dummyBudoServer;
  };

  const elmLive = proxyquire('./source/elm-live', {
    budo, gaze: dummyGaze, 'cross-spawn': dummyCrossSpawn,
  });

  elmLive([`--port=${ portNumber }`], dummyConfig);
});

test((
  'Watches all `**/*.elm` files in the current directory'
), (assert) => new Promise((resolve) => {
  assert.plan(4);

  const event = 'touched';
  const absolutePath = path.resolve(process.cwd(), 'ab/c.elm');
  const relativePath = path.relative(process.cwd(), absolutePath);

  const watcherMock = {
    on: (what, callback) => {
      callback(event, absolutePath);
    },
  };

  const gaze = (target, callback) => {
    assert.is(target, '**/*.elm',
      'passes the right glob to gaze'
    );

    callback(null, watcherMock);
  };

  let serverStarted = false;
  const budo = () => {
    serverStarted = true;
    return dummyBudoServer;
  };

  let elmMakeRun = 0;
  const success = { status: 0, error: {} };
  const failure = { status: 77, error: {} };
  const crossSpawn = { sync: (command) => {
    if (command !== 'elm-make') return success;
    elmMakeRun++;

    if (elmMakeRun === 1) return failure;

    assert.notOk(serverStarted,
      'doesn’t start the server immediately if things go wrong'
    );

    assert.pass(
      'retries spawning `elm-make` if things go wrong the first time'
    );

    return success;
  } };

  const elmLive = proxyquire('./source/elm-live', {
    gaze, budo, 'cross-spawn': crossSpawn,
  });

  let chunkNumber = 0;
  elmLive([], { inputStream: devnull(), outputStream: qs((chunk) => {
    chunkNumber++;
    if (chunkNumber !== 3) return;

    const expectedMessage = (
`\nelm-live:
  You’ve ${ event } \`${ relativePath }\`. Rebuilding!

`
    );

    assert.is(naked(chunk), expectedMessage,
      'prints a message when a file is changed'
    );

    resolve();
  }) });
}));
<|endoftext|>


<commit_before>

42 lines (36 sloc)  1.41 KB
'use strict';

function sum (x,y) {
  return [x + y, 'The sum of 4 and 7 is 11.'];
}

function testSum() { //eslint-disable-line
if (sum(4,7)[1] === 'The sum of 4 and 7 is 11.') {
console.log('%c TEST FOR sum() PASSES', 'color: green');
} else {
console.log('%c TEST FOR sum() FAILS', 'color: red');
}
}
testSum();

function multiply(x , y) {
  return [x * y, 'The product of 5 and 9 is 45.'];
}

function testMultiply() { //eslint-disable-line
  if (multiply(5,9)[1] === 'The product of 5 and 9 is 45.') {
    console.log('%c TEST FOR multiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiply() FAILS', 'color: red');
  }
}
testMultiply();

function sumAndMultiply (x , y , z) {
  return [x + y + z, x * y * z, '4 and 7 and 5 sum to 16.', 'The product of 4 and 7 and 5 is 140.'];
}

function testSumAndMultiply() { //eslint-disable-line
  if (sumAndMultiply(4, 7, 5)[2] === '4 and 7 and 5 sum to 16.' && sumAndMultiply(4, 7, 5)[3] === 'The product of 4 and 7 and 5 is 140.') {
    console.log('%c TEST FOR sumAndMultiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumAndMultiply() FAILS', 'color: red');
  }
}
testSumAndMultiply();

function testSumArray() { //eslint-disable-line
  if (sumArray(testArray)[1] === '2,3,4 was passed in as an array of numbers, and 9 is their sum.') {
    console.log('%c TEST FOR sumArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumArray() FAILS', 'color: red');
  }
}

function testMultiplyArray() { //eslint-disable-line
  if (multiplyArray(testArray)[1] === 'The numbers 2,3,4 have a product of 24.') {
    console.log('%c TEST FOR multiplyArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiplyArray() FAILS', 'color: red');
  }
}
<commit_msg>problem-04<commit_after>

42 lines (36 sloc)  1.41 KB
'use strict';

function sum (x,y) {
  return [x + y, 'The sum of 4 and 7 is 11.'];
}

function testSum() { //eslint-disable-line
if (sum(4,7)[1] === 'The sum of 4 and 7 is 11.') {
console.log('%c TEST FOR sum() PASSES', 'color: green');
} else {
console.log('%c TEST FOR sum() FAILS', 'color: red');
}
}
testSum();

function multiply(x , y) {
  return [x * y, 'The product of 5 and 9 is 45.'];
}

function testMultiply() { //eslint-disable-line
  if (multiply(5,9)[1] === 'The product of 5 and 9 is 45.') {
    console.log('%c TEST FOR multiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiply() FAILS', 'color: red');
  }
}
testMultiply();

function sumAndMultiply (x , y , z) {
  return [x + y + z, x * y * z, '4 and 7 and 5 sum to 16.', 'The product of 4 and 7 and 5 is 140.'];
}

function testSumAndMultiply() { //eslint-disable-line
  if (sumAndMultiply(4, 7, 5)[2] === '4 and 7 and 5 sum to 16.' && sumAndMultiply(4, 7, 5)[3] === 'The product of 4 and 7 and 5 is 140.') {
    console.log('%c TEST FOR sumAndMultiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumAndMultiply() FAILS', 'color: red');
  }
}
testSumAndMultiply();

var testArray = [2 , 3, 4];

function sumArray(testArray) {
  return [sum, '2,3,4 was passed in as an array of numbers, and 9 is their sum.'];
}

function testSumArray() { //eslint-disable-line
  if (sumArray(testArray)[1] === '2,3,4 was passed in as an array of numbers, and 9 is their sum.') {
    console.log('%c TEST FOR sumArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumArray() FAILS', 'color: red');
  }
}
testSumArray();

function testMultiplyArray() { //eslint-disable-line
  if (multiplyArray(testArray)[1] === 'The numbers 2,3,4 have a product of 24.') {
    console.log('%c TEST FOR multiplyArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiplyArray() FAILS', 'color: red');
  }
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 09:35:49<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var spawn = require('cross-spawn-async')

var runBrowserTests = process.env.TRAVIS && (!process.env.TRAVIS_PULL_REQUEST ||
  process.env.TRAVIS_PULL_REQUEST === 'false')

npmRun('test-node', function (code) {
  if (code === 0) {
    var scriptName = runBrowserTests ? 'test-browser' : 'test-browser-headless'
    npmRun(scriptName, function (code) {
      process.exit(code)
    })
  } else {
    process.exit(code)
  }
})

function npmRun (scriptName, onClose) {
  spawn('npm', ['run', scriptName], { stdio: 'inherit' }).on('close', onClose)
}
<commit_msg>Tests check for saucelabs environment variables, not Travis<commit_after>#!/usr/bin/env node

var spawn = require('cross-spawn-async')

var runSauceLabs = process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY

npmRun('test-node', function (code) {
  if (code === 0) {
    var scriptName = runSauceLabs ? 'test-browser' : 'test-browser-headless'
    npmRun(scriptName, function (code) {
      process.exit(code)
    })
  } else {
    process.exit(code)
  }
})

function npmRun (scriptName, onClose) {
  spawn('npm', ['run', scriptName], { stdio: 'inherit' }).on('close', onClose)
}
<|endoftext|>


<commit_before>'use strict'

var assert = require('assert');

var sum = require('.');

describe('sum()', function() {
  describe('return type', function () {
    it('should return a number when the argument is not present', function () {
      assert.equal('number', typeof sum());
    });

    it('should return a function when the argument is present', function () {
      assert.equal('function', typeof sum(0));
    });

    it('returned function should behave in the same way', function () {
      var f = sum(0);
      assert.equal('number', typeof f());
      assert.equal('function', typeof f(0));
    });

    it('could make chained call as many as wanted', function () {
      var f = sum(0)(0)(0);
      assert.equal('number', typeof f());
      assert.equal('function', typeof f(0));
    });
  })

  describe('return value', function () {
    it('should return 0 when called without arguments directly', function () {
      assert.equal(0, sum());
    });

    it('should return the same value when called with arguments one times', function () {
      assert.equal(3, sum(3)());
    });
  })
});<commit_msg>連續呼叫會累計總和 (test case only)<commit_after>'use strict'

var assert = require('assert');

var sum = require('.');

describe('sum()', function() {
  describe('return type', function () {
    it('should return a number when the argument is not present', function () {
      assert.equal('number', typeof sum());
    });

    it('should return a function when the argument is present', function () {
      assert.equal('function', typeof sum(0));
    });

    it('returned function should behave in the same way', function () {
      var f = sum(0);
      assert.equal('number', typeof f());
      assert.equal('function', typeof f(0));
    });

    it('could make chained call as many as wanted', function () {
      var f = sum(0)(0)(0);
      assert.equal('number', typeof f());
      assert.equal('function', typeof f(0));
    });
  })

  describe('return value', function () {
    it('should return 0 when called without arguments directly', function () {
      assert.equal(0, sum());
    });

    it('should return the same value when called with arguments one times', function () {
      assert.equal(3, sum(3)());
    });

    it('should return sum of each arguments when called with arguments multiple times', function () {
      assert.equal(7, sum(3)(4)());
      assert.equal(12, sum(3)(4)(5)());
    });
  })
});<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-12-3 21:13:56<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const timeline = require("./src/visualizations/timeline.js");

var dom = new JSDOM("")
global.window = dom.window;
global.document = dom.window.document;

var root_el = dom.window.document.createElement("div");

var example_events = [
    {"timestamp": "<timestamp>", "duration": 10, "data": {"title": "lololtitle", "app": "lololapp"}},
    {"timestamp": "<timestamp>", "duration": 10, "data": {"title": "lololtitle", "app": "lololapp"}}
]

var total_duration = 20;

timeline.create(root_el)
timeline.update(root_el, example_events, total_duration)

<commit_msg>removed unused file<commit_after><|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-6 08:33:55<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict';

require('mocha');
require('should');
var assert = require('assert');
var context = require('code-context');
var extract = require('./');
var fs = require('fs');

function read(fp) {
  return fs.readFileSync(__dirname + '/fixtures/' + fp, 'utf8');
}

describe('block comments', function () {
  it('should extract a block comment', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].raw === '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should not extract comments in quoted strings', function () {
    var a = '/* this is a block comment */\n\nvar foo = "/* bar */"';
    var actual = extract(a);
    assert(actual.length === 1);
    assert(actual[0].raw === '/* this is a block comment */');

    var b = '/* this is a block comment */\n\nvar foo = "abc /* bar */ xyz "';
    var actual = extract(b);
    assert(actual.length === 1);
    assert(actual[0].raw === '/* this is a block comment */');
  });

  it('should extract comments in functions', function () {
    var a = 'function foo(/*a, b, c*/);';
    var actual = extract(a);
    assert(actual[0].raw === '/*a, b, c*/');
  });

  it('should strip leading stars to create the "value" property', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].value === 'this is\na comment');
  });

  it('should split the comment into lines', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].lines[0] === 'this is');
    assert(actual[0].lines[1] === 'a comment');
  });

  it('should get the starting line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.line === 1);
  });

  it('should get the starting index', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.pos === 0);
  });

  it('should get the ending line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.line === 5);
  });

  it('should get the ending index', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.pos === 33);
  });
});

describe('code', function () {
  it('should get the code line that follows the comment', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].code.value === 'var foo = "bar";');
  });

  it('should get the code starting and ending indices', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.pos;
    var end = code.loc.end.pos;
    assert(start === 36);
    assert(end === 52);
    assert(str.slice(start, end) === 'var foo = "bar";');
  });

  it('should get the code line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.line;
    var lines = str.split('\n');
    var line = lines.indexOf('var foo = "bar";');
    assert(line === start);
  });
});

describe('line comments', function () {
  it('should extract a line comment', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].raw === '// this is a line comment');
  });

  it('should not extract comments in quoted strings', function () {
    var a = '// this is a line comment\n\nvar foo = ". // \' \\ . // \' \\ .";\n';
    var actual = extract(a);
    assert(actual.length === 1);
    assert(actual[0].raw === '// this is a line comment');

    var b = '// this is a line comment\n\nvar foo = "// one two"';
    var actual = extract(b);
    assert(actual.length === 1);
    assert(actual[0].raw === '// this is a line comment');
  });

  it('should strip leading slashes to create the "value" property', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].value === 'this is a line comment');
  });

  it('should get the starting line number', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.line === 1);
  });

  it('should get the starting index', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.pos === 0);
  });

  it('should get the ending line number', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.line === 1);
  });

  it('should get the ending index', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.pos === 25);
  });
});

describe('first', function () {
  it('should extract the first comment only', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert(actual === '/**\n * this is\n *\n * a comment\n*/');
  });
});
<commit_msg>adding test for comments after quoted strings<commit_after>'use strict';

require('mocha');
require('should');
var assert = require('assert');
var context = require('code-context');
var extract = require('./');
var fs = require('fs');

function read(fp) {
  return fs.readFileSync(__dirname + '/fixtures/' + fp, 'utf8');
}

describe('block comments', function () {
  it('should extract a block comment', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].raw === '/**\n * this is\n *\n * a comment\n*/');
  });

  it('should not extract comments in quoted strings', function () {
    var a = '/* this is a block comment */\n\nvar foo = "/* bar */"';
    var actual = extract(a);
    assert(actual.length === 1);
    assert(actual[0].raw === '/* this is a block comment */');

    var b = '/* this is a block comment */\n\nvar foo = "abc /* bar */ xyz "';
    var actual = extract(b);
    assert(actual.length === 1);
    assert(actual[0].raw === '/* this is a block comment */');
  });

  it('should extract comments in functions', function () {
    var a = 'function foo(/*a, b, c*/);';
    var actual = extract(a);
    assert(actual[0].raw === '/*a, b, c*/');
  });

  it('should extract comments after quoted strings', function () {
    var a = '"some code"\n/**\n * some comment\n*/\n';
    var actual = extract(a);
    assert(actual.length === 1);
  });

  it('should strip leading stars to create the "value" property', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].value === 'this is\na comment');
  });

  it('should split the comment into lines', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].lines[0] === 'this is');
    assert(actual[0].lines[1] === 'a comment');
  });

  it('should get the starting line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.line === 1);
  });

  it('should get the starting index', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.pos === 0);
  });

  it('should get the ending line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.line === 5);
  });

  it('should get the ending index', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.pos === 33);
  });
});

describe('code', function () {
  it('should get the code line that follows the comment', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].code.value === 'var foo = "bar";');
  });

  it('should get the code starting and ending indices', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.pos;
    var end = code.loc.end.pos;
    assert(start === 36);
    assert(end === 52);
    assert(str.slice(start, end) === 'var foo = "bar";');
  });

  it('should get the code line number', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\n\n\nvar foo = "bar";\n';
    var actual = extract(str);
    var code = actual[0].code;
    var start = code.loc.start.line;
    var lines = str.split('\n');
    var line = lines.indexOf('var foo = "bar";');
    assert(line === start);
  });
});

describe('line comments', function () {
  it('should extract a line comment', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].raw === '// this is a line comment');
  });

  it('should not extract comments in quoted strings', function () {
    var a = '// this is a line comment\n\nvar foo = ". // \' \\ . // \' \\ .";\n';
    var actual = extract(a);
    assert(actual.length === 1);
    assert(actual[0].raw === '// this is a line comment');

    var b = '// this is a line comment\n\nvar foo = "// one two"';
    var actual = extract(b);
    assert(actual.length === 1);
    assert(actual[0].raw === '// this is a line comment');
  });

  it('should strip leading slashes to create the "value" property', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].value === 'this is a line comment');
  });

  it('should get the starting line number', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.line === 1);
  });

  it('should get the starting index', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.start.pos === 0);
  });

  it('should get the ending line number', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.line === 1);
  });

  it('should get the ending index', function () {
    var str = '// this is a line comment\n\nvar foo = "bar";\n';
    var actual = extract(str);
    assert(actual[0].loc.end.pos === 25);
  });
});

describe('first', function () {
  it('should extract the first comment only', function () {
    var str = '/**\n * this is\n *\n * a comment\n*/\nvar foo = "bar";\n/* baz */';
    var actual = extract.first(str);
    assert(actual === '/**\n * this is\n *\n * a comment\n*/');
  });
});
<|endoftext|>


<commit_before>/*
Name:           requestbin - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-requestbin
Feedback:       https://github.com/fvdm/nodejs-requestbin/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-requestbin/raw/develop/UNLICENSE)
*/

// Setup
var app = require ('./');
var pkg = require ('./package.json');
var http = require ('httpreq');
var timeout = process.env.REQUESTBIN_TIMEOUT || 5000;
var cache = {
  bin: null,
  request: null,
  post: {
    node: process.version,
    module: pkg.version
  }
};
var errors = 0;
var queue = [];
var next = 0;

// handle exits
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\u001b[1mDONE, no errors.\u001b[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\u001b[1mFAIL, ' + errors + ' error' + (errors > 1 ? 's' : '') + ' occurred!\u001b[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.trace ();
  console.log ();
  errors++;
});

// Queue to prevent flooding
function doNext () {
  next++;
  if (queue [next]) {
    queue [next] ();
  }
}

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  var testErrors = [];
  var i;

  if (err instanceof Error) {
    console.error ('\u001b[1m\u001b[31mERROR\u001b[0m - ' + label + '\n');
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    for (i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

    if (testErrors.length === 0) {
      console.log ('\u001b[1m\u001b[32mgood\u001b[0m - ' + label);
    } else {
      console.error ('\u001b[1m\u001b[31mFAIL\u001b[0m - ' + label + ' (' + testErrors.join (', ') + ')');
    }
  }

  doNext ();
}

queue.push (function () {
  app.create ('invalid', function (err) {
    doTest (null, 'Error: request failed', [
      ['type', err instanceof Error],
      ['message', err && err.message === 'request failed'],
      ['error', err && err.error]
    ]);
  });
});

queue.push (function () {
  app.create (false, function (err, data) {
    cache.bin = data || null;
    if (data) {
      http.post ('http://requestb.in/' + data.name, { parameters: cache.post }, function (e, r) {});
      console.log ('info - http://requestb.in/' + data.name + '?inspect');
    }
    doTest (err, '.create', [
      ['type', data instanceof Object],
      ['name', data && typeof data.name === 'string']
    ]);
  });
});

queue.push (function () {
  if (!cache.bin) {
    console.log ('skip - .get');
    return;
  }
  app.get (cache.bin.name, function (err, data) {
    doTest (err, '.get', [
      ['type', data instanceof Object],
      ['name', data && data.name === cache.bin.name]
    ]);
  });
});

queue.push (function () {
  if (!cache.bin) {
    console.log ('skip - .requests');
    return;
  }
  app.requests (cache.bin.name, function (err, data) {
    cache.request = data && data [0] || null;
    doTest (err, '.requests', [
      ['type', data instanceof Array],
      ['item', data && data [0] instanceof Object]
    ]);
  });
});

queue.push (function () {
  if (!cache.request) {
    console.log ('skip - .request');
    return;
  }
  app.request (cache.bin.name, cache.request.id, function (err, data) {
    doTest (err, '.request', [
      ['type', data instanceof Object],
      ['id', data && data.id === cache.request.id]
    ]);
  });
});

console.log ('Running tests...');
queue [0] ();
<commit_msg>Test: set timeout in config<commit_after>/*
Name:           requestbin - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-requestbin
Feedback:       https://github.com/fvdm/nodejs-requestbin/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-requestbin/raw/develop/UNLICENSE)
*/

// Setup
var app = require ('./');
var pkg = require ('./package.json');
var http = require ('httpreq');
var timeout = process.env.REQUESTBIN_TIMEOUT || 5000;
var cache = {
  bin: null,
  request: null,
  post: {
    node: process.version,
    module: pkg.version
  }
};
var errors = 0;
var queue = [];
var next = 0;

app.config ('timeout', timeout);

// handle exits
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\u001b[1mDONE, no errors.\u001b[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\u001b[1mFAIL, ' + errors + ' error' + (errors > 1 ? 's' : '') + ' occurred!\u001b[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.trace ();
  console.log ();
  errors++;
});

// Queue to prevent flooding
function doNext () {
  next++;
  if (queue [next]) {
    queue [next] ();
  }
}

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  var testErrors = [];
  var i;

  if (err instanceof Error) {
    console.error ('\u001b[1m\u001b[31mERROR\u001b[0m - ' + label + '\n');
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    for (i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

    if (testErrors.length === 0) {
      console.log ('\u001b[1m\u001b[32mgood\u001b[0m - ' + label);
    } else {
      console.error ('\u001b[1m\u001b[31mFAIL\u001b[0m - ' + label + ' (' + testErrors.join (', ') + ')');
    }
  }

  doNext ();
}

queue.push (function () {
  app.config ('timeout', 1);
  app.create ('invalid', function (err) {
    doTest (null, 'Error: request failed', [
      ['type', err instanceof Error],
      ['message', err && err.message === 'request failed'],
      ['error', err && err.error]
    ]);
  });
});

queue.push (function () {
  app.config ('timeout', timeout);
  app.create (false, function (err, data) {
    cache.bin = data || null;
    if (data) {
      http.post ('http://requestb.in/' + data.name, { parameters: cache.post }, function (e, r) {});
      console.log ('info - http://requestb.in/' + data.name + '?inspect');
    }
    doTest (err, '.create', [
      ['type', data instanceof Object],
      ['name', data && typeof data.name === 'string']
    ]);
  });
});

queue.push (function () {
  if (!cache.bin) {
    console.log ('skip - .get');
    return;
  }
  app.get (cache.bin.name, function (err, data) {
    doTest (err, '.get', [
      ['type', data instanceof Object],
      ['name', data && data.name === cache.bin.name]
    ]);
  });
});

queue.push (function () {
  if (!cache.bin) {
    console.log ('skip - .requests');
    return;
  }
  app.requests (cache.bin.name, function (err, data) {
    cache.request = data && data [0] || null;
    doTest (err, '.requests', [
      ['type', data instanceof Array],
      ['item', data && data [0] instanceof Object]
    ]);
  });
});

queue.push (function () {
  if (!cache.request) {
    console.log ('skip - .request');
    return;
  }
  app.request (cache.bin.name, cache.request.id, function (err, data) {
    doTest (err, '.request', [
      ['type', data instanceof Object],
      ['id', data && data.id === cache.request.id]
    ]);
  });
});

console.log ('Running tests...');
queue [0] ();
<|endoftext|>


<commit_before>describe('strategy', function () {
  'use strict';

  var Negotiation = require('negotiation')
    , TL = require('transport-layer')
    , assume = require('assume')
    , Strategy = require('./')
    , strategy
    , tls = [];

  beforeEach(function () {
    strategy = new Strategy(tls);
  });

  afterEach(function () {
    strategy.destroy();
  });

  it('is exported as function', function () {
    assume(Strategy).is.a('function');
  });

  it('can be construced without `new` keyword', function () {
    strategy.destroy();
    strategy = Strategy();

    assume(strategy).instanceOf(Strategy);
    assume(strategy.push).is.a('function');
  });

  it('exposes the Attempt constructor', function () {
    assume(Strategy.Attempt).is.a('function');
  });

  it('can add transports through the constructor', function () {
    strategy.destroy();
    strategy = new Strategy([
      new Strategy.Attempt('foo', {})
    ]);

    assume(strategy).length(1);
    assume(strategy.transports[0].name).equals('foo');
  });

  describe('Attempt', function () {
    it('uses the provided name of the transport', function () {
      var named = TL.extend({ name: 'named' })
        , attempt = new Strategy.Attempt(undefined, named);

      assume(attempt.name).equals('named');
    });
  });

  describe('#select', function () {
    var readyState = require('transport-layer/exports').readystate;

    beforeEach(function () {
      strategy.push('readable', r);
      strategy.push('writable', w);
      strategy.push('crossdomain', xd);
      strategy.push('read & write', rw);
    });

    var r = TL.extend({}, { supported: true, readable: true })
      , w = TL.extend({}, { supported: true, writable: true })
      , xd = TL.extend({}, { supported: true, crossdomain: true })
      , rw = TL.extend({}, { supported: true, readable: true, writable: true });

    it('selects only readable transports', function (next) {
      strategy.select({ readable: true }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.instanceOf(Strategy.Attempt);
        assume(strategy.transport).equals(attempt.id);
        assume(attempt.transport).equals(r);

        next();
      });
    });

    it('it waits until a transport is available', function (next) {
      var ready = false;

      //
      // Reset the readyState so we can trigger a change event.
      //
      readyState.readyState = 0;

      strategy.select({
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.instanceOf(Strategy.Attempt);
        assume(strategy.transport).equals(attempt.id);
        assume(attempt.transport).equals(r);
        ready = true;
      });

      setTimeout(function () {
        assume(ready).is.false();
        readyState.change('complete');
        assume(ready).is.true();
        next();
      }, 100);

      assume(ready).is.false();
    });

    it('can filter out transports based on name', function (next) {
      strategy.select({
        not: { readable: true },
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(rw);

        next();
      });
    });

    it('can find writable transports', function (next) {
      strategy.select({
        writable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(w);

        next();
      });
    });

    it('can find crossdomain transports', function (next) {
      strategy.select({
        crossdomain: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(xd);

        next();
      });
    });

    it('can filter based upon id', function (next) {
      strategy.select({
        id: 3
      }, function (err, attempt)  {
        if (err) return next(err);

        assume(attempt.transport).equals(rw);

        next();
      });
    });

    it('calls the callback even if there are no matches', function (next) {
      strategy.select({
        id: 10 // non-existing id
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.undefined();
        next();
      });
    });

    it('selects an available transport', function (next) {
      strategy.select({
        available: true,
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport.available()).is.true();

        next();
      });
    });
  });

  describe('#push', function () {
    it('is a function', function () {
      assume(strategy.push).is.a('function');
    });

    it('returns it self', function () {
      assume(strategy.push('foo', {})).equals(strategy);
    });

    it('saves the newly added transport and increments the length', function () {
      strategy.destroy();
      strategy = new Strategy();

      assume(strategy).has.length(0);

      strategy.push('foo', {});
      assume(strategy).has.length(1);

      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
    });

    it('accepts Attempt instances', function () {
      var attempt = new Strategy.Attempt('foo', 1);

      strategy.push(attempt);

      assume(strategy).has.length(1);
      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
      assume(strategy.transports[0].id).equals(0);
    });

    it('increments ids', function () {
      assume(strategy.id).equals(0);

      strategy.push('foo', {});

      assume(strategy.id).equals(1);
      assume(strategy.transports[0].id).equals(0);

      strategy.push('foo', {});
      assume(strategy.id).equals(2);
      assume(strategy.transports[1].id).equals(1);
    });

    it('does not override the id', function () {
      var attempt = new Strategy.Attempt('foo', 1);
      attempt.id = 'foo';

      strategy.push(attempt);

      assume(strategy).has.length(1);
      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
      assume(strategy.transports[0].id).equals('foo');
    });
  });
});
<commit_msg>[test] Ignore tests for coverage<commit_after>/* istanbul ignore next */
describe('strategy', function () {
  'use strict';

  var Negotiation = require('negotiation')
    , TL = require('transport-layer')
    , assume = require('assume')
    , Strategy = require('./')
    , strategy
    , tls = [];

  beforeEach(function () {
    strategy = new Strategy(tls);
  });

  afterEach(function () {
    strategy.destroy();
  });

  it('is exported as function', function () {
    assume(Strategy).is.a('function');
  });

  it('can be construced without `new` keyword', function () {
    strategy.destroy();
    strategy = Strategy();

    assume(strategy).instanceOf(Strategy);
    assume(strategy.push).is.a('function');
  });

  it('exposes the Attempt constructor', function () {
    assume(Strategy.Attempt).is.a('function');
  });

  it('can add transports through the constructor', function () {
    strategy.destroy();
    strategy = new Strategy([
      new Strategy.Attempt('foo', {})
    ]);

    assume(strategy).length(1);
    assume(strategy.transports[0].name).equals('foo');
  });

  describe('Attempt', function () {
    it('uses the provided name of the transport', function () {
      var named = TL.extend({ name: 'named' })
        , attempt = new Strategy.Attempt(undefined, named);

      assume(attempt.name).equals('named');
    });
  });

  describe('#select', function () {
    var readyState = require('transport-layer/exports').readystate;

    beforeEach(function () {
      strategy.push('readable', r);
      strategy.push('writable', w);
      strategy.push('crossdomain', xd);
      strategy.push('read & write', rw);
    });

    var r = TL.extend({}, { supported: true, readable: true })
      , w = TL.extend({}, { supported: true, writable: true })
      , xd = TL.extend({}, { supported: true, crossdomain: true })
      , rw = TL.extend({}, { supported: true, readable: true, writable: true });

    it('selects only readable transports', function (next) {
      strategy.select({ readable: true }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.instanceOf(Strategy.Attempt);
        assume(strategy.transport).equals(attempt.id);
        assume(attempt.transport).equals(r);

        next();
      });
    });

    it('it waits until a transport is available', function (next) {
      var ready = false;

      //
      // Reset the readyState so we can trigger a change event.
      //
      readyState.readyState = 0;

      strategy.select({
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.instanceOf(Strategy.Attempt);
        assume(strategy.transport).equals(attempt.id);
        assume(attempt.transport).equals(r);
        ready = true;
      });

      setTimeout(function () {
        assume(ready).is.false();
        readyState.change('complete');
        assume(ready).is.true();
        next();
      }, 100);

      assume(ready).is.false();
    });

    it('can filter out transports based on name', function (next) {
      strategy.select({
        not: { readable: true },
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(rw);

        next();
      });
    });

    it('can find writable transports', function (next) {
      strategy.select({
        writable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(w);

        next();
      });
    });

    it('can find crossdomain transports', function (next) {
      strategy.select({
        crossdomain: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport).equals(xd);

        next();
      });
    });

    it('can filter based upon id', function (next) {
      strategy.select({
        id: 3
      }, function (err, attempt)  {
        if (err) return next(err);

        assume(attempt.transport).equals(rw);

        next();
      });
    });

    it('calls the callback even if there are no matches', function (next) {
      strategy.select({
        id: 10 // non-existing id
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt).is.undefined();
        next();
      });
    });

    it('selects an available transport', function (next) {
      strategy.select({
        available: true,
        readable: true
      }, function (err, attempt) {
        if (err) return next(err);

        assume(attempt.transport.available()).is.true();

        next();
      });
    });
  });

  describe('#push', function () {
    it('is a function', function () {
      assume(strategy.push).is.a('function');
    });

    it('returns it self', function () {
      assume(strategy.push('foo', {})).equals(strategy);
    });

    it('saves the newly added transport and increments the length', function () {
      strategy.destroy();
      strategy = new Strategy();

      assume(strategy).has.length(0);

      strategy.push('foo', {});
      assume(strategy).has.length(1);

      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
    });

    it('accepts Attempt instances', function () {
      var attempt = new Strategy.Attempt('foo', 1);

      strategy.push(attempt);

      assume(strategy).has.length(1);
      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
      assume(strategy.transports[0].id).equals(0);
    });

    it('increments ids', function () {
      assume(strategy.id).equals(0);

      strategy.push('foo', {});

      assume(strategy.id).equals(1);
      assume(strategy.transports[0].id).equals(0);

      strategy.push('foo', {});
      assume(strategy.id).equals(2);
      assume(strategy.transports[1].id).equals(1);
    });

    it('does not override the id', function () {
      var attempt = new Strategy.Attempt('foo', 1);
      attempt.id = 'foo';

      strategy.push(attempt);

      assume(strategy).has.length(1);
      assume(strategy.transports[0]).is.instanceOf(Strategy.Attempt);
      assume(strategy.transports[0].name).equals('foo');
      assume(strategy.transports[0].id).equals('foo');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.0.9'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth     : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
recordint: 100,
reservename: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
}
}

  // called every second
};

module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.0.9'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth       : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
recordint: 100,
reservename: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
}
}

  // called every second
};

module.exports = this; // dont touch
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var http = require('http')
var enableDestroy = require('server-destroy')
var reverseHttp = require('./')

test('default values', function (t) {
  t.plan(4)

  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var n = 0
    var rserver = reverseHttp({ port: server.address().port }, function (req, res) {
      res.end()
      switch (++n) {
        case 1:
          t.equal(req.method, 'GET')
          t.equal(req.url, '/foo')
          break
        case 2:
          rserver.close()
          server.destroy()
          t.equal(req.method, 'GET')
          t.equal(req.url, '/bar')
          break
      }
    })

    rserver.on('error', function (err) {
      t.error(err)
    })
  })

  server.on('upgrade', function (req, socket, head) {
    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    socket.write('GET /foo HTTP/1.1\r\n\r\n')

    setTimeout(function () {
      socket.write('GET /bar HTTP/1.1\r\n\r\n')
    }, 50)
  })
})

test('reconnect', function (t) {
  t.plan(5)

  var n = 0
  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var rserver = reverseHttp({ port: server.address().port }, function (req, res) {
      res.end()

      t.equal(req.method, 'GET')
      t.equal(req.url, '/foo')

      if (n === 2) {
        rserver.close()
        server.destroy()
        t.ok(true)
      }
    })

    rserver.on('error', function (err) {
      t.error(err)
    })
  })

  server.on('upgrade', function (req, socket, head) {
    if (++n === 1) {
      setTimeout(function () {
        socket.destroy()
      }, 50)
    }

    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    socket.write('GET /foo HTTP/1.1\r\n\r\n')
  })
})

test('remote server goes offline', function (t) {
  t.plan(1)

  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var rserver = reverseHttp({ port: server.address().port })
    rserver.on('error', function (err) {
      t.equal(err.code, 'ECONNREFUSED')
    })
  })

  server.on('upgrade', function (req, socket, head) {
    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    setTimeout(function () {
      server.destroy()
    }, 50)
  })
})
<commit_msg>Add respond test<commit_after>'use strict'

var test = require('tape')
var http = require('http')
var enableDestroy = require('server-destroy')
var reverseHttp = require('./')

test('default values', function (t) {
  t.plan(4)

  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var n = 0
    var rserver = reverseHttp({ port: server.address().port }, function (req, res) {
      res.end()
      switch (++n) {
        case 1:
          t.equal(req.method, 'GET')
          t.equal(req.url, '/foo')
          break
        case 2:
          rserver.close()
          server.destroy()
          t.equal(req.method, 'GET')
          t.equal(req.url, '/bar')
          break
      }
    })

    rserver.on('error', function (err) {
      t.error(err)
    })
  })

  server.on('upgrade', function (req, socket, head) {
    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    socket.write('GET /foo HTTP/1.1\r\n\r\n')

    setTimeout(function () {
      socket.write('GET /bar HTTP/1.1\r\n\r\n')
    }, 50)
  })
})

test('reconnect', function (t) {
  t.plan(5)

  var n = 0
  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var rserver = reverseHttp({ port: server.address().port }, function (req, res) {
      res.end()

      t.equal(req.method, 'GET')
      t.equal(req.url, '/foo')

      if (n === 2) {
        rserver.close()
        server.destroy()
        t.ok(true)
      }
    })

    rserver.on('error', function (err) {
      t.error(err)
    })
  })

  server.on('upgrade', function (req, socket, head) {
    if (++n === 1) {
      setTimeout(function () {
        socket.destroy()
      }, 50)
    }

    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    socket.write('GET /foo HTTP/1.1\r\n\r\n')
  })
})

test('remote server goes offline', function (t) {
  t.plan(1)

  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })

  enableDestroy(server)

  server.listen(function () {
    var rserver = reverseHttp({ port: server.address().port })
    rserver.on('error', function (err) {
      t.equal(err.code, 'ECONNREFUSED')
    })
  })

  server.on('upgrade', function (req, socket, head) {
    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    setTimeout(function () {
      server.destroy()
    }, 50)
  })
})

test('respond', function (t) {
  t.plan(1)

  var server = http.createServer(function (req, res) {
    t.fail('Unexpected HTTP request')
  })
  var rserver

  enableDestroy(server)

  server.listen(function () {
    rserver = reverseHttp({ port: server.address().port }, function (req, res) {
      res.writeHead(418)
      res.write('foo')
      res.end()
    })
  })

  server.on('upgrade', function (req, socket, head) {
    socket.write('HTTP/1.1 101 Switching Protocols\r\n' +
                 'Upgrade: PTTH/1.0\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n')

    setTimeout(function () {
      socket.write('GET /foo HTTP/1.1\r\n\r\n')
    }, 50)

    socket.on('data', function (chunk) {
      var lines = chunk.toString().split('\r\n')
      t.equal(lines[0], 'HTTP/1.1 418 I\'m a teapot')
      rserver.close()
      server.destroy()
    })
  })
})
<|endoftext|>


<commit_before>'use strict';
var assert = require('assert');
var Md = require('markdown-it');
var markdownItAttrs = require('./');
var utils = require('./utils.js');

describe('markdown-it-attrs.utils', function() {
  it('should parse {.class #id key=val}', function () {
    var src = '{.red #head key=val}';
    var expected = [['class', 'red'], ['id', 'head'], ['key', 'val']];
    var res = utils.getAttrs(src, 1, src.length-1);
    assert.deepEqual(res, expected);
  });
});

describe('markdown-it-attrs', function() {
  var md;
  beforeEach(function(){
    md = Md().use(markdownItAttrs);
  });

  it('should add attributes when {} in end of last inline', function () {
    var src = 'some text {with=attrs}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add attributes when {} in last line', function () {
    var src = 'some text\n{with=attrs}';
    var expected = '
some text\n
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes with {.class} dot notation', function () {
    var src = 'some text {.green}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add identifiers with {#id} hashtag notation', function () {
    var src = 'some text {#section2}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support classes, identifiers and attributes in same {}', function () {
    var src = 'some text {attr=lorem .class #id}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support attributes inside " {attr="lorem ipsum"}', function () {
    var src = 'some text {attr="lorem ipsum"}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes in same class attribute {.c1 .c2} -> class="c1 c2"', function () {
    var src = 'some text {.c1 .c2}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support empty inline tokens', function(){
    var src = ' 1 | 2 \n --|-- \n a | ';
    md.render(src);  // should not crash / throw error
  });

  it('should add classes to inline elements', function(){
    var src = 'paragraph **bold**{.red} asdf';
    var expected = '
paragraph bold asdf
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should only remove last {}', function(){
    var src = '{{.red}';
    var expected = '
{
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes for list items', function(){
    var src = '- item 1{.red}\n- item 2';
    var expected = '
\n';
    expected += '
item 1
\n';
    expected += '
item 2
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should work with nested inline elements', function(){
    var src = '- **bold *italics*{.blue}**{.green}';
    var expected = '
\n';
    expected += '
bold italics
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add class to inline code block', function(){
    var src = 'bla `click()`{.c}';
    var expected = '
bla click()
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should not trim unrelated white space', function(){
    var src = '- **bold** text {.red}';
    var expected = '
\n';
    expected += '
bold text
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should not create empty attributes', function(){
    var src = 'text { .red }';
    var expected = '
text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add attributes to ul when below last bullet point', function(){
    var src = '- item\n{.red}';
    var expected = '
\n
item
\n
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });
});
<commit_msg>add test for #11<commit_after>'use strict';
var assert = require('assert');
var Md = require('markdown-it');
var markdownItAttrs = require('./');
var utils = require('./utils.js');

describe('markdown-it-attrs.utils', function() {
  it('should parse {.class #id key=val}', function () {
    var src = '{.red #head key=val}';
    var expected = [['class', 'red'], ['id', 'head'], ['key', 'val']];
    var res = utils.getAttrs(src, 1, src.length-1);
    assert.deepEqual(res, expected);
  });
});

describe('markdown-it-attrs', function() {
  var md;
  beforeEach(function(){
    md = Md().use(markdownItAttrs);
  });

  it('should add attributes when {} in end of last inline', function () {
    var src = 'some text {with=attrs}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add attributes when {} in last line', function () {
    var src = 'some text\n{with=attrs}';
    var expected = '
some text\n
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes with {.class} dot notation', function () {
    var src = 'some text {.green}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add identifiers with {#id} hashtag notation', function () {
    var src = 'some text {#section2}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support classes, identifiers and attributes in same {}', function () {
    var src = 'some text {attr=lorem .class #id}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support attributes inside " {attr="lorem ipsum"}', function () {
    var src = 'some text {attr="lorem ipsum"}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes in same class attribute {.c1 .c2} -> class="c1 c2"', function () {
    var src = 'some text {.c1 .c2}';
    var expected = '
some text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should support empty inline tokens', function(){
    var src = ' 1 | 2 \n --|-- \n a | ';
    md.render(src);  // should not crash / throw error
  });

  it('should add classes to inline elements', function(){
    var src = 'paragraph **bold**{.red} asdf';
    var expected = '
paragraph bold asdf
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should only remove last {}', function(){
    var src = '{{.red}';
    var expected = '
{
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add classes for list items', function(){
    var src = '- item 1{.red}\n- item 2';
    var expected = '
\n';
    expected += '
item 1
\n';
    expected += '
item 2
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should work with nested inline elements', function(){
    var src = '- **bold *italics*{.blue}**{.green}';
    var expected = '
\n';
    expected += '
bold italics
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add class to inline code block', function(){
    var src = 'bla `click()`{.c}';
    var expected = '
bla click()
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should not trim unrelated white space', function(){
    var src = '- **bold** text {.red}';
    var expected = '
\n';
    expected += '
bold text
\n';
    expected += '
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should not create empty attributes', function(){
    var src = 'text { .red }';
    var expected = '
text
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should add attributes to ul when below last bullet point', function(){
    var src = '- item\n{.red}';
    var expected = '
\n
item
\n
\n';
    var res = md.render(src);
    assert.equal(res, expected);
  });

  it('should work with typography enabled', function(){
    var src = 'text {key="val with spaces"}';
    var expected = '
text
\n';
    var res = md.set({ typographer: true }).render(src);
    assert.equal(res, expected);
  });
});
<|endoftext|>


<commit_before>const express = require('express');
const ser = require('./services/nyt.api.service');

var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world');
});

app.get('/search/:queryString/:startDate/:endDate', function(req, res) {
  // Llamada al service
  // Habria que verificar si estan bien los parametros
  // Quizas la logica de la validacion hay que ubicarla en otro lado
  ser.getNews(req.params.startDate, req.params.endDate, req.params.queryString)
    .then((data) => {
        console.log(data);
        res.send(data);
    }, (error)=>{
        console.log(error);
        res.send('Error');
    });

  //res.send();
});

app.get('*', function(req, res) {
  res.send('404. Not found.');
});

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

<commit_msg>new routes<commit_after>const express = require('express');
const ser = require('./services/nyt.api.service');

var app = express();

// get an instance of router
var router = express.Router();

// route middleware that will happen on every request
router.use(function(req, res, next) {
    // log each request to the console
    console.log(req.method, req.url);
    // continue doing what we were doing and go to the route
    next();
});

// home page route
router.get('/', function(req, res) {
    res.send('hello world');
});

router.get('/search/:queryString/:startDate/:endDate', function(req, res) {
    ser.getNews(req.params.startDate, req.params.endDate, req.params.queryString)
    .then((data) => {
        console.log(data);
        res.send(data);
    }, (error)=>{
        console.log(error);
        res.send('Error');
    });

});

router.get('*', function(req, res) {
    res.send('404');
});

// apply the routes to our application
app.use('/', router);

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-3 11:12:42<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>