<commit_before>import { mount } from 'enzyme';
import Pagination from '..';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import ConfigProvider from '../../config-provider';
import Select from '../../select';

describe('Pagination', () => {
  mountTest(Pagination);
  rtlTest(Pagination);

  it('should pass disabled to prev and next buttons', () => {
    const itemRender = (current, type, originalElement) => {
      if (type === 'prev') {
        return <button type="button">prev</button>;
      }
      if (type === 'next') {
        return <button type="button">next</button>;
      }
      return originalElement;
    };
    const wrapper = mount(<Pagination defaultCurrent={1} total={50} itemRender={itemRender} />);
    expect(wrapper.find('button').at(0).props().disabled).toBe(true);
  });

  it('should autometically be small when size is not specified', async () => {
    const wrapper = mount(<Pagination responsive />);
    expect(wrapper.find('ul').at(0).hasClass('ant-pagination-mini')).toBe(true);
  });

  // https://github.com/ant-design/ant-design/issues/24913
  // https://github.com/ant-design/ant-design/issues/24501
  it('should onChange called when pageSize change', () => {
    const onChange = jest.fn();
    const onShowSizeChange = jest.fn();
    const wrapper = mount(
      <Pagination
        defaultCurrent={1}
        total={500}
        onChange={onChange}
        onShowSizeChange={onShowSizeChange}
      />,
    );
    wrapper.find('.ant-select-selector').simulate('mousedown');
    expect(wrapper.find('.ant-select-item-option').length).toBe(4);
    wrapper.find('.ant-select-item-option').at(1).simulate('click');
    expect(onChange).toHaveBeenCalledWith(1, 20);
  });

  it('should support custom selectComponentClass', () => {
    const CustomSelect = ({ className, ...props }) => (
      <Select className={`${className} custom-select`} {...props} />
    );

    CustomSelect.Option = Select.Option;

    const wrapper = mount(
      <Pagination defaultCurrent={1} total={500} selectComponentClass={CustomSelect} />,
    );
    expect(wrapper.find('.custom-select').length).toBeTruthy();
  });

  describe('ConfigProvider', () => {
    it('should be rendered correctly in RTL', () => {
      const wrapper = mount(
        <ConfigProvider direction="rtl">
          <Pagination defaultCurrent={1} total={50} />
        </ConfigProvider>,
      );
      expect(wrapper.render()).toMatchSnapshot();
    });

    it('should be rendered correctly when componentSize is large', () => {
      const wrapper = mount(
        <ConfigProvider componentSize="large">
          <Pagination defaultCurrent={1} total={50} showSizeChanger />
        </ConfigProvider>,
      );
      expect(wrapper.render()).toMatchSnapshot();
      expect(wrapper.find('.ant-select-lg').length).toBe(0);
    });
  });
});
<commit_msg>chore: code clean<commit_after>import { mount } from 'enzyme';
import React from 'react';
import Pagination from '..';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import ConfigProvider from '../../config-provider';
import Select from '../../select';

describe('Pagination', () => {
  mountTest(Pagination);
  rtlTest(Pagination);

  it('should pass disabled to prev and next buttons', () => {
    const itemRender = (current, type, originalElement) => {
      if (type === 'prev') {
        return <button type="button">prev</button>;
      }
      if (type === 'next') {
        return <button type="button">next</button>;
      }
      return originalElement;
    };
    const wrapper = mount(<Pagination defaultCurrent={1} total={50} itemRender={itemRender} />);
    expect(wrapper.find('button').at(0).props().disabled).toBe(true);
  });

  it('should autometically be small when size is not specified', async () => {
    const wrapper = mount(<Pagination responsive />);
    expect(wrapper.find('ul').at(0).hasClass('ant-pagination-mini')).toBe(true);
  });

  // https://github.com/ant-design/ant-design/issues/24913
  // https://github.com/ant-design/ant-design/issues/24501
  it('should onChange called when pageSize change', () => {
    const onChange = jest.fn();
    const onShowSizeChange = jest.fn();
    const wrapper = mount(
      <Pagination
        defaultCurrent={1}
        total={500}
        onChange={onChange}
        onShowSizeChange={onShowSizeChange}
      />,
    );
    wrapper.find('.ant-select-selector').simulate('mousedown');
    expect(wrapper.find('.ant-select-item-option').length).toBe(4);
    wrapper.find('.ant-select-item-option').at(1).simulate('click');
    expect(onChange).toHaveBeenCalledWith(1, 20);
  });

  it('should support custom selectComponentClass', () => {
    const CustomSelect = ({ className, ...props }) => (
      <Select className={`${className} custom-select`} {...props} />
    );

    CustomSelect.Option = Select.Option;

    const wrapper = mount(
      <Pagination defaultCurrent={1} total={500} selectComponentClass={CustomSelect} />,
    );
    expect(wrapper.find('.custom-select').length).toBeTruthy();
  });

  describe('ConfigProvider', () => {
    it('should be rendered correctly in RTL', () => {
      const wrapper = mount(
        <ConfigProvider direction="rtl">
          <Pagination defaultCurrent={1} total={50} />
        </ConfigProvider>,
      );
      expect(wrapper.render()).toMatchSnapshot();
    });

    it('should be rendered correctly when componentSize is large', () => {
      const wrapper = mount(
        <ConfigProvider componentSize="large">
          <Pagination defaultCurrent={1} total={50} showSizeChanger />
        </ConfigProvider>,
      );
      expect(wrapper.render()).toMatchSnapshot();
      expect(wrapper.find('.ant-select-lg').length).toBe(0);
    });
  });
});
<|endoftext|>


<commit_before>$(document).ready(function($) {
	var assetData = {};

	function loadData() {
		var $body = $('body');
		var $returned = $('#returned');
		var asset = $('#wiki-asset').val();

		var wikiRequestTimeout = setTimeout(function() {
			$('body').append("Failed to get wikipedia resources");
		}, 8000);

		var wikiUrl = "http://10.151.4.115/mediawiki/api.php?format=json&action=parse&page=" + asset;
		$.ajax({
			url: wikiUrl,
			dataType: "jsonp",
			success: function( response ) {
				console.log("Mediawiki connection successful");
				var page = response.parse;
				console.log(response);
				var title = page.displaytitle;
				var text = page.text["*"];

				$returned.html(text);
				var $table = $('.wikitable tbody').first();
				$table.children('tr').each(function(e) {
					var key = $(this).find('th').text().trim();
					var value = $(this).find('td').text().trim();
					assetData[key] = value;
				});
				// createForm();
				insertData(assetData);
				clearTimeout(wikiRequestTimeout);
			}
		});
		return false;
	}

	$('#wiki-submit-btn').on('click', function(e) {
		e.preventDefault();
		loadData();
		var asset = $('#wiki-asset').val();
		$('#asset-id-form').hide();
		$('#slip_assetTag').val(asset);
	});

	function insertData(assetData) {
		$('#slip_manufacturer').val(assetData['Manufacturer']);
		$('#slip_deviceName').val(assetData['Device Name']);
		$('#slip_modelNumber').val(assetData['Model Number']);
		$('#slip_serialNumber').val(assetData['Serial Number']);
	}

	$('.select-address').change(function() {
		var $val = $('select option:selected');
		if($val.val() == 'viz' ) {
			console.log('viz preset');
			$('#slip_shipAddress').val('101 Billerica Ave Bldg 6');
			$('#slip_shipCity').val('North Billerica');
			$('#slip_shipState').val('MA');
			$('#slip_shipZip').val('01862');
		} else if ($val.val() == 'troll') {
			console.log('troll preset');
			$('#slip_shipAddress').val('24950 Anza Drive');
			$('#slip_shipCity').val('Valencia');
			$('#slip_shipState').val('CA');
			$('#slip_shipZip').val('91355');
		} else {
			console.log('no preset');
			$('#slip_shipAddress').val(' ');
			$('#slip_shipCity').val(' ');
			$('#slip_shipState').val(' ');
			$('#slip_shipZip').val(' ');
		}
	});

	function resetTextFields() {
		$("#manufacturer").val(' ');
		$("#device-name").val(' ');
		$("#model-number").val(' ');
		$("#serial-number").val(' ');
		$("#quantity").val(' ');
		$("#address").val(' ');
		$("#city").val(' ');
		$("#state").val(' ');
		$("#zip").val(' ');
		$("#FedEx-Tracking-Number").val(' ');
		$("#RMA-Number").val(' ');
		$("#Additinal-Comments").val(' ');
	}

	$("#cancel").click(function() {
		resetTextFields();
	});
	$("#refresh").click(function() {
		location.reload();
	});

});

<commit_msg>Cleaned up js, removed debug console.logs and added slip_shipName data to presets<commit_after>$(document).ready(function($) {
	var assetData = {};

	function loadData() {
		var $body = $('body');
		var $returned = $('#returned');
		var asset = $('#wiki-asset').val();

		var wikiRequestTimeout = setTimeout(function() {
			$('body').append("Failed to get wikipedia resources");
		}, 8000);

		var wikiUrl = "http://10.151.4.115/mediawiki/api.php?format=json&action=parse&page=" + asset;
		$.ajax({
			url: wikiUrl,
			dataType: "jsonp",
			success: function( response ) {
				var page = response.parse;
				var title = page.displaytitle;
				var text = page.text["*"];

				$returned.html(text);
				var $table = $('.wikitable tbody').first();
				$table.children('tr').each(function(e) {
					var key = $(this).find('th').text().trim();
					var value = $(this).find('td').text().trim();
					assetData[key] = value;
				});
				insertData(assetData);
				clearTimeout(wikiRequestTimeout);
			}
		});
		return false;
	}

	$('#wiki-submit-btn').on('click', function(e) {
		e.preventDefault();
		loadData();
		var asset = $('#wiki-asset').val();
		$('#asset-id-form').hide();
		$('#slip_assetTag').val(asset);
	});

	function insertData(assetData) {
		$('#slip_manufacturer').val(assetData['Manufacturer']);
		$('#slip_deviceName').val(assetData['Device Name']);
		$('#slip_modelNumber').val(assetData['Model Number']);
		$('#slip_serialNumber').val(assetData['Serial Number']);
	}

	$('.select-address').change(function() {
		var $val = $('select option:selected');
		if($val.val() == 'viz' ) {
			$('#slip_shipName').val('Vizlink');
			$('#slip_shipAddress').val('101 Billerica Ave Bldg 6');
			$('#slip_shipCity').val('North Billerica');
			$('#slip_shipState').val('MA');
			$('#slip_shipZip').val('01862');
		} else if ($val.val() == 'troll') {
			$('#slip_shipName').val('Troll');
			$('#slip_shipAddress').val('24950 Anza Drive');
			$('#slip_shipCity').val('Valencia');
			$('#slip_shipState').val('CA');
			$('#slip_shipZip').val('91355');
		} else {
			$('#slip_shipAddress').val(' ');
			$('#slip_shipCity').val(' ');
			$('#slip_shipState').val(' ');
			$('#slip_shipZip').val(' ');
		}
	});

	function resetTextFields() {
		$("#manufacturer").val(' ');
		$("#device-name").val(' ');
		$("#model-number").val(' ');
		$("#serial-number").val(' ');
		$("#quantity").val(' ');
		$("#address").val(' ');
		$("#city").val(' ');
		$("#state").val(' ');
		$("#zip").val(' ');
		$("#FedEx-Tracking-Number").val(' ');
		$("#RMA-Number").val(' ');
		$("#Additinal-Comments").val(' ');
	}

	$("#cancel").click(function() {
		resetTextFields();
	});
	$("#refresh").click(function() {
		location.reload();
	});

});

<|endoftext|>


<commit_before>// **********************************************************************
// 設定項目
// **********************************************************************

// マップサイズ
var worldSize = {x: 1600, y: 1600};

// 表示区画の数とサイズ
// マス目状にマップを区切るときの数とサイズです
var divideNumber = 16;
var divideSize = 100;

// ファイル名と色の指定
var alliances = [
    ["neko_data.csv", "rgba(0, 0, 255, 1)"],
//    ["neko_sibu_data.csv", "rgba(0, 255, 255, 1)"],
    ["kir_data.csv", "rgba(0, 255, 255, 1)"],
    ["taiten_data.csv", "rgba(255, 165, 0, 1)"],
//    ["taiten_shibu_data.csv", "rgba(200, 100, 0, 1)"],
    ["tsuki_data.csv", "rgba(255, 0, 0, 1)"],
//    ["tsuki_sibu_data.csv", "rgba(139, 0, 0, 1)"],
    ["furikuma.csv", "rgba(0, 200, 0, 1)"],
    ["dc.csv", "rgba(173, 255, 47, 1)"],
    ["gonta.csv", "rgba(173, 255, 47, 1)"],
    ["fn.csv", "rgba(173, 255, 47, 1)"],
    ["var.csv", "rgba(210,105,30, 1)"],
    ["kkisk.csv", "rgba(255, 105, 180, 1)"]
]

var urlBase = "http://m17.3gokushi.jp/map.php?x=[x]&y=[y]";

var defaultColors = {
    friend: ["rgba(0, 0, 255, 1)", "rgba(0, 255, 255, 1)", "rgba(80, 77, 203, 1)"],
    enemy: ["rgba(255, 0, 0, 1)", "rgba(255, 165, 0, 1)", "rgba(183, 65, 14, 1)"],
    neutral: ["rgba(0, 200, 0, 1)", "rgba(173, 255, 47, 1)", "rgba(103, 228, 126, 1)"],
    friendIndex: 0,
    enemyIndex: 0,
    neutralIndex: 0
}

<commit_msg>initial commit<commit_after>// **********************************************************************
// 設定項目
// **********************************************************************

// マップサイズ
var worldSize = {x: 1600, y: 1600};

// 表示区画の数とサイズ
// マス目状にマップを区切るときの数とサイズです
var divideNumber = 16;
var divideSize = 100;

// ファイル名と色の指定
var alliances = [
    ["neko_data.csv", "rgba(0, 0, 255, 1)"],
    ["kir_data.csv", "rgba(0, 255, 255, 1)"],
    ["taiten_data.csv", "rgba(255, 165, 0, 1)"],
    ["tsuki_data.csv", "rgba(255, 0, 0, 1)"],
    ["furikuma.csv", "rgba(0, 200, 0, 1)"],
    ["dc.csv", "rgba(173, 255, 47, 1)"],
    ["gonta.csv", "rgba(173, 255, 47, 1)"],
    ["fn.csv", "rgba(173, 255, 47, 1)"],
    ["var.csv", "rgba(210,105,30, 1)"],
    ["kkisk.csv", "rgba(255, 105, 180, 1)"]
]

var urlBase = "http://m17.3gokushi.jp/map.php?x=[x]&y=[y]";

var defaultColors = {
    friend: ["rgba(0, 0, 255, 1)", "rgba(0, 255, 255, 1)", "rgba(80, 77, 203, 1)"],
    enemy: ["rgba(255, 0, 0, 1)", "rgba(255, 165, 0, 1)", "rgba(183, 65, 14, 1)"],
    neutral: ["rgba(0, 200, 0, 1)", "rgba(173, 255, 47, 1)", "rgba(103, 228, 126, 1)"],
    friendIndex: 0,
    enemyIndex: 0,
    neutralIndex: 0
}

<|endoftext|>


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

    // hide the output box first
    $('#output').hide();

    // Load all the archive formats
	loadArchiveFormats(['rar', 'zip', 'tar']);

    $("#fileup").change(function(){

        $('#output').hide();

        // init the gallery plugin, when there is a first click on a image
        // re-bind this function when opening new comic
        $(document).one('click','#comicImg',function(){
            event.preventDefault();
            // initialize gallery
            $('#output').lightGallery({
                selector: 'a',
                zoom: true,
                fullScreen: true,
                download: false,
                enableTouch: true,
            });
            $(this).click();
        });

        // show loading
		$('.se-pre-con').fadeIn('slow');

        // destroy lightGallery
        var $lg = $('#output');
        $lg.lightGallery();
        $lg.data('lightGallery').destroy(true);

        // clear previous blobs
        clearBlobs();

        // clear previous output data
        $('#output').empty();

        var file = $(this)[0].files[0];

        // Open the file as an archive
        archiveOpenFile(file, function(archive, err) {
            if (archive)
            {
                $('#output').append(""+archive.file_name+"
Click on the image to enlarge

");
                readContents(archive);

                // hide loading
                $('.se-pre-con').fadeOut('slow');

                // show output box
                $('#output').fadeIn('slow');
            }
            else
            {
                $('#output').append(""+err+"
");

                // hide loading
                $('.se-pre-con').fadeOut('slow');

                // show output box
                $('#output').fadeIn('slow');
            }
        });
    });

    // function for reading the contents of the archive
    function readContents(archive)
    {
        var entries = archive.entries;

        // iterate through all the contents
        for(var i=0;i<entries.length;i++)
        {
            filename = entries[i].name;
            // check, only output file, not folder
            if(getExt(filename) != '')
            {
                // call function to create blob and url. allow us to read/view the contents
                createBlobs(entries[i]);
            }
        }
    }

    // function to return file extension based on file name
    function getExt(filename)
    {
        var ext = filename.split('.').pop();
        return (ext == filename) ? '' : ext;
    }

    // function to return MIME type based on the file extension
    // NOTE: THIS FUNCTION IS NOT EFFICIENT
    function getMIME(filename)
    {
        var ext = getExt(filename).toLowerCase();

        switch(ext)
        {
            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
                break;
            case 'png':
                return 'image/png';
                break;
            case 'gif':
                return 'image/gif';
                break;
            case 'bmp':
                return 'image/bmp';
                break;
            case 'webp':
                return 'image/webp';
                break;
            default:
                return 'image/jpeg';
        }
    }

    // function to convert the archive contents into blobs, and return URL
    function createBlobs(entry)
    {
        entry.readData(function(data, err) {
            // Convert the data into an Object URL
            var blob = new Blob([data], {type: getMIME(entry.name)});
            var url = URL.createObjectURL(blob);

            // output the images
            $('#output').append("");
        });

    }

    // function to clear all previous blobs, free up memory
    function clearBlobs()
    {
        $('.imgUrl').each(function(){
            URL.revokeObjectURL($(this).attr('src'));
        });
    }

});<commit_msg>implement setTimeout to reduce browser crash<commit_after>$(document).ready(function(){

    // hide the output box first
    $('#output').hide();

    // Load all the archive formats
	loadArchiveFormats(['rar', 'zip', 'tar']);

    $("#fileup").change(function(){

        $('#output').hide();

        // init the gallery plugin, when there is a first click on a image
        // re-bind this function when opening new comic
        $(document).one('click','#comicImg',function(){
            event.preventDefault();
            // initialize gallery
            $('#output').lightGallery({
                selector: 'a',
                zoom: true,
                fullScreen: true,
                download: false,
                enableTouch: true,
            });
            $(this).click();
        });

        // show loading
		$('.se-pre-con').fadeIn('slow');

        // destroy lightGallery
        var $lg = $('#output');
        $lg.lightGallery();
        $lg.data('lightGallery').destroy(true);

        // clear previous blobs
        clearBlobs();

        // clear previous output data
        $('#output').empty();

        var file = $(this)[0].files[0];

        // Open the file as an archive
        archiveOpenFile(file, function(archive, err) {
            if (archive)
            {
                $('#output').append(""+archive.file_name+"
Click on the image to enlarge

");
                readContents(archive);
            }
            else
            {
                $('#output').append(""+err+"
");

                // hide loading
                $('.se-pre-con').fadeOut('slow');

                // show output box
                $('#output').fadeIn('slow');
            }
        });
    });

    // function for reading the contents of the archive
    function readContents(archive)
    {
        var entries = archive.entries;

        // iterate through all the contents
        for(var i=0;i<entries.length;i++)
        {
			processEntries(entries, i, entries.length);
        }
    }

	// implement setTimout()
	// This can minimize browser from overprocessing which can caused browser to be not responding
	// simple way to mimics multi threading
	function processEntries(entries, i, max)
	{
		setTimeout(function() {
			filename = entries[i].name;
			// check, only output file, not folder
			if(getExt(filename) != '')
			{
				// call function to create blob and url. allow us to read/view the contents
				createBlobs(entries[i], i, max);
			}
		}, i*700);
	}

    // function to return file extension based on file name
    function getExt(filename)
    {
        var ext = filename.split('.').pop();
        return (ext == filename) ? '' : ext;
    }

    // function to return MIME type based on the file extension
    // NOTE: THIS FUNCTION IS NOT EFFICIENT
    function getMIME(filename)
    {
        var ext = getExt(filename).toLowerCase();

        switch(ext)
        {
            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
                break;
            case 'png':
                return 'image/png';
                break;
            case 'gif':
                return 'image/gif';
                break;
            case 'bmp':
                return 'image/bmp';
                break;
            case 'webp':
                return 'image/webp';
                break;
            default:
                return 'image/jpeg';
        }
    }

    // function to convert the archive contents into blobs, and return URL
    function createBlobs(entry, i, max)
    {
        entry.readData(function(data, err) {
            // Convert the data into an Object URL
            var blob = new Blob([data], {type: getMIME(entry.name)});
            var url = URL.createObjectURL(blob);

            // output the images
            $('#output').append("");

			// only hide loading spinnder when done process all
			if(i == (max-1)) {
				// hide loading
                $('.se-pre-con').fadeOut('slow');

                // show output box
                $('#output').fadeIn('slow');
			}
        });
    }

    // function to clear all previous blobs, free up memory
    function clearBlobs()
    {
        $('.imgUrl').each(function(){
            URL.revokeObjectURL($(this).attr('src'));
        });
    }

});<|endoftext|>


<commit_before>
// require dependencies
const config     = require ('config');
const extend     = require ('extendify');
const controller = require ('controller');
const middleware = require ('i18next-express-middleware');

// require helpers
const locale = helper ('locale');

/**
 * build locale controller class
 *
 * @priority 100
 */
class localeController extends controller {

  /**
   * construct locale controller class
   */
  constructor () {
    // run super
    super ();

    // bind variables
    this.extend = extend ({
      'isDeep'  : true,
      'inPlace' : false
    });
    this.sessions = {};

    // bind methods
    this.build = this.build.bind (this);

    // bind private methods
    this._create     = this._create.bind (this);
    this._remove     = this._remove.bind (this);
    this._socket     = this._socket.bind (this);
    this._middleware = this._middleware.bind (this);

    // build
    this.building = this.build ();
  }

  /**
   * build locale controller
   */
  build () {
    // run this
    this.eden.pre  ('view.render', this._create);
    this.eden.post ('view.render', this._remove);

    // hooks
    this.eden.pre ('socket.call.opts',     this._socket);
    this.eden.pre ('socket.endpoint.opts', this._socket);

    // use middleware
    this.eden.router.use (middleware.handle (locale.locale));

    // add middleware
    this.eden.router.use (this._middleware);

    // use get
    this.eden.router.get ('/locales/:ns.:lng.json', (req, res) => {
      // run try/catch
      try {
        // require locales
        res.json (require (global.appRoot + '/app/cache/locales/' + req.params.ns + '.' + req.params.lng + '.json'));
      } catch (e) {
        // return nothing
        res.json ({});
      }
    });
  }

  /**
   * sets session language
   *
   * @param  {String} lang
   * @param  {Object} opts
   *
   * @call lang
   */
  langAction (lang, opts) {
    // get session ID
    let sessionID = opts.socket.request.cookie[config.get ('session.key') || 'eden.session.id'];

    // set language
    this.sessions[sessionID] = lang;
  }

  /**
   * create helper functions
   *
   * @param {Object} obj
   */
  _create (obj) {
    // let render
    let req    = obj.req;
    let render = obj.render;

    // set language
    req.language = req.language || config.get ('i18n.fallbackLng');

    // set i18n variables
    if (!render.i18n) render.i18n = this.extend ({
      'lng'      : req.language.split (' ')[req.language.split (' ').length - 1],
      'load'     : 'currentOnly',
      'defaults' : {},
      'backend'  : {
        'backends'       : [],
        'backendOptions' : [config.get ('i18n.cache'), {
          'loadPath'          : '/locales/{{ns}}.{{lng}}.json',
          'allowMultiLoading' : false
        }]
      }
    }, config.get ('i18n') || {});

    // set helpers
    if (!render.helpers) render.helpers = {};

    // set helper
    render.helpers.i18n = {
      // return helper translate function
      't' : function () {
        // let key
        let key = JSON.stringify (arguments);

        // set defaults
        if (!render.i18n.defaults[key]) render.i18n.defaults[key] = req.i18n.t (...arguments);

        // return rendered
        return render.i18n.defaults[key];
      }
    };
  }

  /**
   * socket middleware
   *
   * @param  {Object} opts
   */
  _socket (opts) {
    // add opts
    opts.t = (str, data) => {
      // check opts
      data = data || {};

      // get session ID
      let sessionID = opts.socket.request.cookie[config.get ('session.key') || 'eden.session.id'];

      // get language
      if (this.sessions[sessionID]) {
        // set lang
        data.lng = this.sessions[sessionID];
      }

      // return helper translate
      return locale.t (opts.user, str, data);
    };
  }

  /**
   * remove helper functions
   *
   * @param {Object} obj
   */
  _remove (obj) {
    // remove helpers
    if (obj.render.helpers) delete obj.render.helpers;
  }

  /**
   * add language middleware
   *
   * @param {Request}  req
   * @param {Response} res
   * @param {Function} next
   *
   * @return {*}
   */
  async _middleware (req, res, next) {
    // set user language
    if (!req.user) return next ();

    // check user
    if (!req.user.get ('lang') || req.user.get ('lang') !== req.language) {
      // set language
      req.user.set ('lang', req.language.split (' ')[req.language.split (' ').length - 1]);

      // save user
      await req.user.save ();
    }

    // return next
    return next ();
  }
}

/**
 * export localeController controller class
 *
 * @type {localeController}
 */
exports = module.exports = localeController;
<commit_msg>load locales with cache bust string<commit_after>
// require dependencies
const config     = require ('config');
const extend     = require ('extendify');
const controller = require ('controller');
const middleware = require ('i18next-express-middleware');

// require helpers
const locale = helper ('locale');

/**
 * build locale controller class
 *
 * @priority 100
 */
class localeController extends controller {

  /**
   * construct locale controller class
   */
  constructor () {
    // run super
    super ();

    // bind variables
    this.extend = extend ({
      'isDeep'  : true,
      'inPlace' : false
    });
    this.sessions = {};

    // bind methods
    this.build = this.build.bind (this);

    // bind private methods
    this._create     = this._create.bind (this);
    this._remove     = this._remove.bind (this);
    this._socket     = this._socket.bind (this);
    this._middleware = this._middleware.bind (this);

    // build
    this.building = this.build ();
  }

  /**
   * build locale controller
   */
  build () {
    // run this
    this.eden.pre  ('view.render', this._create);
    this.eden.post ('view.render', this._remove);

    // hooks
    this.eden.pre ('socket.call.opts',     this._socket);
    this.eden.pre ('socket.endpoint.opts', this._socket);

    // use middleware
    this.eden.router.use (middleware.handle (locale.locale));

    // add middleware
    this.eden.router.use (this._middleware);

    // use get
    this.eden.router.get ('/locales/:ns.:lng.json', (req, res) => {
      // run try/catch
      try {
        // require locales
        res.json (require (global.appRoot + '/app/cache/locales/' + req.params.ns + '.' + req.params.lng + '.json'));
      } catch (e) {
        // return nothing
        res.json ({});
      }
    });
  }

  /**
   * sets session language
   *
   * @param  {String} lang
   * @param  {Object} opts
   *
   * @call lang
   */
  langAction (lang, opts) {
    // get session ID
    let sessionID = opts.socket.request.cookie[config.get ('session.key') || 'eden.session.id'];

    // set language
    this.sessions[sessionID] = lang;
  }

  /**
   * create helper functions
   *
   * @param {Object} obj
   */
  _create (obj) {
    // let render
    let req    = obj.req;
    let render = obj.render;

    // set language
    req.language = req.language || config.get ('i18n.fallbackLng');

    // set i18n variables
    if (!render.i18n) render.i18n = this.extend ({
      'lng'      : req.language.split (' ')[req.language.split (' ').length - 1],
      'load'     : 'currentOnly',
      'defaults' : {},
      'backend'  : {
        'backends'       : [],
        'backendOptions' : [config.get ('i18n.cache'), {
          'loadPath'          : '/locales/{{ns}}.{{lng}}.json',
          'queryStringParams' : {
            'v' : config.get ('version')
          },
          'allowMultiLoading' : false
        }]
      }
    }, config.get ('i18n') || {});

    // set helpers
    if (!render.helpers) render.helpers = {};

    // set helper
    render.helpers.i18n = {
      // return helper translate function
      't' : function () {
        // let key
        let key = JSON.stringify (arguments);

        // set defaults
        if (!render.i18n.defaults[key]) render.i18n.defaults[key] = req.i18n.t (...arguments);

        // return rendered
        return render.i18n.defaults[key];
      }
    };
  }

  /**
   * socket middleware
   *
   * @param  {Object} opts
   */
  _socket (opts) {
    // add opts
    opts.t = (str, data) => {
      // check opts
      data = data || {};

      // get session ID
      let sessionID = opts.socket.request.cookie[config.get ('session.key') || 'eden.session.id'];

      // get language
      if (this.sessions[sessionID]) {
        // set lang
        data.lng = this.sessions[sessionID];
      }

      // return helper translate
      return locale.t (opts.user, str, data);
    };
  }

  /**
   * remove helper functions
   *
   * @param {Object} obj
   */
  _remove (obj) {
    // remove helpers
    if (obj.render.helpers) delete obj.render.helpers;
  }

  /**
   * add language middleware
   *
   * @param {Request}  req
   * @param {Response} res
   * @param {Function} next
   *
   * @return {*}
   */
  async _middleware (req, res, next) {
    // set user language
    if (!req.user) return next ();

    // check user
    if (!req.user.get ('lang') || req.user.get ('lang') !== req.language) {
      // set language
      req.user.set ('lang', req.language.split (' ')[req.language.split (' ').length - 1]);

      // save user
      await req.user.save ();
    }

    // return next
    return next ();
  }
}

/**
 * export localeController controller class
 *
 * @type {localeController}
 */
exports = module.exports = localeController;
<|endoftext|>


<commit_before>define("amber/helpers", ["amber_vm/smalltalk", "require"], function (smalltalk, require) {
    var exports = {
        popupHelios: function () {
            window.open(require.toUrl('amber_html/helios.html'), "Helios", "menubar=no, status=no, scrollbars=no, menubar=no, width=1000, height=600");
        }
    };
    Object.defineProperty(exports, "smalltalk", {
        get: function () { return smalltalk; },
        enumerable: true, configurable: true
    });
    return  exports;
});
<commit_msg>use (non-writable if supported) property, not getter<commit_after>define("amber/helpers", ["amber_vm/smalltalk", "require"], function (smalltalk, require) {
    var exports = {
        popupHelios: function () {
            window.open(require.toUrl('amber_html/helios.html'), "Helios", "menubar=no, status=no, scrollbars=no, menubar=no, width=1000, height=600");
        }
    };
    Object.defineProperty(exports, "smalltalk", {
        value: smalltalk,
        enumerable: true, configurable: true, writable: false
    });
    return  exports;
});
<|endoftext|>


<commit_before>var Application = require('<%= modulePrefix %>/app')['default'];
var Router = require('<%= modulePrefix %>/router')['default'];

function startApp(attrs) {
  var App;

  var attributes = Ember.merge({
    // useful Test defaults
    rootElement: '#ember-testing',
    LOG_ACTIVE_GENERATION:false,
    LOG_VIEW_LOOKUPS: false
  }, attrs); // but you can override;

  Router.reopen({
    location: 'none'
  });

  Ember.run(function(){
    App = Application.create(attributes);
    App.setupForTesting();
    App.injectTestHelpers();
  });

  App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL"

  return App;
}

export default startApp;
<commit_msg>idiomatic export of startApp<commit_after>var Application = require('<%= modulePrefix %>/app')['default'];
var Router = require('<%= modulePrefix %>/router')['default'];

export default function startApp(attrs) {
  var App;

  var attributes = Ember.merge({
    // useful Test defaults
    rootElement: '#ember-testing',
    LOG_ACTIVE_GENERATION:false,
    LOG_VIEW_LOOKUPS: false
  }, attrs); // but you can override;

  Router.reopen({
    location: 'none'
  });

  Ember.run(function(){
    App = Application.create(attributes);
    App.setupForTesting();
    App.injectTestHelpers();
  });

  App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL"

  return App;
}
<|endoftext|>


<commit_before>exports.names = ['.lastseen', '.seen'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 5;
exports.cd_user = 10;
exports.cd_manager = 5;
exports.handler = function (data) {
    if (data.from.role > 2 || data.from.username == 'PAJLADA') {
        var params = _.rest(data.message.split(' '), 1);
        if (params.length < 1) {
            bot.sendChat('/me usage: .lastseen username');
            return;
        }

        username = params.join(' ').trim()
        usernameFormatted = S(username).chompLeft('@').s;

        user = _.findWhere(bot.getUsers(), {username: usernameFormatted});
        if (user) {
            bot.sendChat(usernameFormatted + ' is in the room!');
        } else {
            User.find({where: {username: usernameFormatted}}).on('success', function (row) {
                if (row === null) {
                    bot.sendChat(usernameFormatted + ' was not found.');
                } else {
                    bot.sendChat(row.username + ' was last seen ' + timeSince(row.last_seen) + '.');
                }
            });
        }
    }
};
<commit_msg>.lastseen can now be used by bouncers+.<commit_after>exports.names = ['.lastseen', '.seen'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 5;
exports.cd_user = 10;
exports.cd_manager = 5;
exports.handler = function (data) {
    if (data.from.role > 1) {
        var params = _.rest(data.message.split(' '), 1);
        if (params.length < 1) {
            bot.sendChat('/me usage: .lastseen username');
            return;
        }

        username = params.join(' ').trim()
        usernameFormatted = S(username).chompLeft('@').s;

        user = _.findWhere(bot.getUsers(), {username: usernameFormatted});
        if (user) {
            bot.sendChat(usernameFormatted + ' is in the room!');
        } else {
            User.find({where: {username: usernameFormatted}}).on('success', function (row) {
                if (row === null) {
                    bot.sendChat(usernameFormatted + ' was not found.');
                } else {
                    bot.sendChat(row.username + ' was last seen ' + timeSince(row.last_seen) + '.');
                }
            });
        }
    }
};
<|endoftext|>


<commit_before>/* @flow */

import type { RegistryNames } from "./registries";
import type Reporter from "./reporters/_base";
import type Registry from "./registries/_base";
import ConstraintResolver from "./package-constraint-resolver";
import RequestManager from "./util/request-manager";
import { registries } from "./registries";
import * as fs from "./util/fs";
import map from "./util/map";

let invariant = require("invariant");
let path      = require("path");
let os        = require("os");

type ConfigOptions = {
  cwd?: string,
  packagesRoot?: string,
  tempFolder?: string
};

export default class Config {
  constructor(reporter: Reporter, opts?: ConfigOptions = {}) {
    this.constraintResolver = new ConstraintResolver(this, reporter);
    this.requestManager     = new RequestManager(reporter);
    this.reporter           = reporter;

    this.registries = map();
    this.cwd        = process.cwd();

    this.packagesRoot = opts.packagesRoot;
    this.tempFolder   = opts.tempFolder;
  }

  constraintResolver: ConstraintResolver;
  requestManager: RequestManager;
  modulesFolder: string;
  packagesRoot: ?string;
  tempFolder: ?string;
  reporter: Reporter;
  cwd: string;

  registries: {
    [name: RegistryNames]: Registry
  };

  resolveConstraints(versions: Array<string>, range: string): Promise<string> {
    return this.constraintResolver.reduce(versions, range);
  }

  async init(opts: ConfigOptions = {}): Promise<void> {
    if (opts.cwd) {
      this.cwd = opts.cwd;
    }

    if (!this.tempFolder) {
      this.tempFolder = await this.getTempFolder();
    }

    this.packagesRoot = await this.getPackageRoot(opts);

    for (let key of Object.keys(registries)) {
      let Registry = registries[key];

      // instantiate registry
      let registry = new Registry(this.cwd);
      await registry.init();

      this.registries[key] = registry;
    }
  }

  generateHardModulePath(pkg: ?{
    name: string,
    uid: string,
    version: string,
    registry: RegistryNames
  }): string {
    invariant(pkg, "Undefined package");
    invariant(pkg.name, "No name field in package");
    invariant(pkg.uid, "No uid field in package");
    invariant(this.packagesRoot, "No package root");

    let name = pkg.name;
    let uid = pkg.uid;
    if (pkg.registry) {
      name = `${pkg.registry}-${name}`;
      uid = pkg.version || uid;
    }

    return path.join(this.packagesRoot, `${name}-${uid}`);
  }

  getTemp(filename: string): string {
    invariant(this.tempFolder, "No temp folder");
    return path.join(this.tempFolder, filename);
  }

  async getTempFolder(): Promise<string> {
    invariant(this.packagesRoot, "No package root");
    let folder = path.join(this.packagesRoot, ".tmp");
    await fs.mkdirp(folder);
    return folder;
  }

  async getPackageRoot(opts: ConfigOptions): Promise<string> {
    if (opts.packagesRoot) {
      return opts.packagesRoot;
    }

    // walk up from current directory looking for kpm_modules folders
    let parts = this.cwd.split(path.sep);
    for (let i = parts.length; i > 0; i--) {
      let loc = parts.slice(0, i).concat("kpm_modules").join(path.sep);
      if (await fs.exists(loc)) return loc;
    }

    // try and create ~/.kpm
    let loc = path.join(os.homedir(), ".kpm");
    await fs.mkdirp(loc);
    return loc;
  }
}
<commit_msg>move up packagesRoot config init method<commit_after>/* @flow */

import type { RegistryNames } from "./registries";
import type Reporter from "./reporters/_base";
import type Registry from "./registries/_base";
import ConstraintResolver from "./package-constraint-resolver";
import RequestManager from "./util/request-manager";
import { registries } from "./registries";
import * as fs from "./util/fs";
import map from "./util/map";

let invariant = require("invariant");
let path      = require("path");
let os        = require("os");

type ConfigOptions = {
  cwd?: string,
  packagesRoot?: string,
  tempFolder?: string
};

export default class Config {
  constructor(reporter: Reporter, opts?: ConfigOptions = {}) {
    this.constraintResolver = new ConstraintResolver(this, reporter);
    this.requestManager     = new RequestManager(reporter);
    this.reporter           = reporter;

    this.registries = map();
    this.cwd        = process.cwd();

    this.packagesRoot = opts.packagesRoot;
    this.tempFolder   = opts.tempFolder;
  }

  constraintResolver: ConstraintResolver;
  requestManager: RequestManager;
  modulesFolder: string;
  packagesRoot: ?string;
  tempFolder: ?string;
  reporter: Reporter;
  cwd: string;

  registries: {
    [name: RegistryNames]: Registry
  };

  resolveConstraints(versions: Array<string>, range: string): Promise<string> {
    return this.constraintResolver.reduce(versions, range);
  }

  async init(opts: ConfigOptions = {}): Promise<void> {
    if (opts.cwd) {
      this.cwd = opts.cwd;
    }

    this.packagesRoot = await this.getPackageRoot(opts);

    if (!this.tempFolder) {
      this.tempFolder = await this.getTempFolder();
    }

    for (let key of Object.keys(registries)) {
      let Registry = registries[key];

      // instantiate registry
      let registry = new Registry(this.cwd);
      await registry.init();

      this.registries[key] = registry;
    }
  }

  generateHardModulePath(pkg: ?{
    name: string,
    uid: string,
    version: string,
    registry: RegistryNames
  }): string {
    invariant(pkg, "Undefined package");
    invariant(pkg.name, "No name field in package");
    invariant(pkg.uid, "No uid field in package");
    invariant(this.packagesRoot, "No package root");

    let name = pkg.name;
    let uid = pkg.uid;
    if (pkg.registry) {
      name = `${pkg.registry}-${name}`;
      uid = pkg.version || uid;
    }

    return path.join(this.packagesRoot, `${name}-${uid}`);
  }

  getTemp(filename: string): string {
    invariant(this.tempFolder, "No temp folder");
    return path.join(this.tempFolder, filename);
  }

  async getTempFolder(): Promise<string> {
    invariant(this.packagesRoot, "No package root");
    let folder = path.join(this.packagesRoot, ".tmp");
    await fs.mkdirp(folder);
    return folder;
  }

  async getPackageRoot(opts: ConfigOptions): Promise<string> {
    if (opts.packagesRoot) {
      return opts.packagesRoot;
    }

    // walk up from current directory looking for kpm_modules folders
    let parts = this.cwd.split(path.sep);
    for (let i = parts.length; i > 0; i--) {
      let loc = parts.slice(0, i).concat("kpm_modules").join(path.sep);
      if (await fs.exists(loc)) return loc;
    }

    // try and create ~/.kpm
    let loc = path.join(os.homedir(), ".kpm");
    await fs.mkdirp(loc);
    return loc;
  }
}
<|endoftext|>


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

    // Load all the archive formats
	loadArchiveFormats(['rar', 'zip', 'tar']);

    $("#fileup").change(function(){

        // init the gallery plugin, when there is a first click on a image
        // re-bind this function when opening new comic
        $(document).one('click','#comicImg',function(){
            event.preventDefault();
            // initialize gallery
            $('#output').lightGallery({
                selector: 'a',
                zoom: true,
                fullScreen: true,
            });
            $(this).click();
        });

        // show loading
		$('.se-pre-con').fadeIn('slow');

        // destroy lightGallery
        var $lg = $('#output');
        $lg.lightGallery();
        $lg.data('lightGallery').destroy(true);

        // clear previous blobs
        clearBlobs();

        // clear previous output data
        $('#output').empty();

        var file = $(this)[0].files[0];

        // Open the file as an archive
        archiveOpenFile(file, function(archive, err) {
            if (archive)
            {
                $('#output').append(""+archive.file_name+"
");
                readContents(archive);

                // hide loading
                $('.se-pre-con').fadeOut('slow');
            }
            else
            {
                console.log(err);

                // hide loading
                $('.se-pre-con').fadeOut('slow');
            }
        });
    });

    // function for reading the contents of the archive
    function readContents(archive)
    {
        var entries = archive.entries;

        // iterate through all the contents
        for(var i=0;i<entries.length;i++)
        {
            filename = entries[i].name;
            // check, only output file, not folder
            if(getExt(filename) != '')
            {
                // call function to create blob and url. allow us to read/view the contents
                createBlobs(entries[i]);
            }
        }
    }

    // function to return file extension based on file name
    function getExt(filename)
    {
        var ext = filename.split('.').pop();
        return (ext == filename) ? '' : ext;
    }

    // function to return MIME type based on the file extension
    // NOTE: THIS FUNCTION IS NOT EFFICIENT
    function getMIME(filename)
    {
        var ext = getExt(filename).toLowerCase();

        switch(ext)
        {
            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
                break;
            case 'png':
                return 'image/png';
                break;
            case 'gif':
                return 'image/gif';
                break;
            case 'bmp':
                return 'image/bmp';
                break;
            case 'webp':
                return 'image/webp';
                break;
            default:
                return 'image/jpeg';
        }
    }

    // function to convert the archive contents into blobs, and return URL
    function createBlobs(entry)
    {
        entry.readData(function(data, err) {
            // Convert the data into an Object URL
            var blob = new Blob([data], {type: getMIME(entry.name)});
            var url = URL.createObjectURL(blob);

            // output the images
            $('#output').append("");
        });

    }

    // function to clear all previous blobs, free up memory
    function clearBlobs()
    {
        $('.imgUrl').each(function(){
            URL.revokeObjectURL($(this).attr('src'));
        });
    }

    // toggle full screen
    $('#btnFullscreen').click(function(){
       //toggleFullScreen(document.body);
        toggleFullScreen();
    });

    // function for fullscreen
    // thanks http://stackoverflow.com/a/10627148/5784900
    function toggleFullScreen() {
      if ((document.fullScreenElement && document.fullScreenElement !== null) ||
       (!document.mozFullScreen && !document.webkitIsFullScreen)) {
        if (document.documentElement.requestFullScreen) {
          document.documentElement.requestFullScreen();
        } else if (document.documentElement.mozRequestFullScreen) {
          document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullScreen) {
          document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      } else {
        if (document.cancelFullScreen) {
          document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        }
      }
    }

});<commit_msg>Remove javascript fullscreen function, not needed anymore<commit_after>$(document).ready(function(){

    // Load all the archive formats
	loadArchiveFormats(['rar', 'zip', 'tar']);

    $("#fileup").change(function(){

        // init the gallery plugin, when there is a first click on a image
        // re-bind this function when opening new comic
        $(document).one('click','#comicImg',function(){
            event.preventDefault();
            // initialize gallery
            $('#output').lightGallery({
                selector: 'a',
                zoom: true,
                fullScreen: true,
            });
            $(this).click();
        });

        // show loading
		$('.se-pre-con').fadeIn('slow');

        // destroy lightGallery
        var $lg = $('#output');
        $lg.lightGallery();
        $lg.data('lightGallery').destroy(true);

        // clear previous blobs
        clearBlobs();

        // clear previous output data
        $('#output').empty();

        var file = $(this)[0].files[0];

        // Open the file as an archive
        archiveOpenFile(file, function(archive, err) {
            if (archive)
            {
                $('#output').append(""+archive.file_name+"
");
                readContents(archive);

                // hide loading
                $('.se-pre-con').fadeOut('slow');
            }
            else
            {
                console.log(err);

                // hide loading
                $('.se-pre-con').fadeOut('slow');
            }
        });
    });

    // function for reading the contents of the archive
    function readContents(archive)
    {
        var entries = archive.entries;

        // iterate through all the contents
        for(var i=0;i<entries.length;i++)
        {
            filename = entries[i].name;
            // check, only output file, not folder
            if(getExt(filename) != '')
            {
                // call function to create blob and url. allow us to read/view the contents
                createBlobs(entries[i]);
            }
        }
    }

    // function to return file extension based on file name
    function getExt(filename)
    {
        var ext = filename.split('.').pop();
        return (ext == filename) ? '' : ext;
    }

    // function to return MIME type based on the file extension
    // NOTE: THIS FUNCTION IS NOT EFFICIENT
    function getMIME(filename)
    {
        var ext = getExt(filename).toLowerCase();

        switch(ext)
        {
            case 'jpg':
            case 'jpeg':
                return 'image/jpeg';
                break;
            case 'png':
                return 'image/png';
                break;
            case 'gif':
                return 'image/gif';
                break;
            case 'bmp':
                return 'image/bmp';
                break;
            case 'webp':
                return 'image/webp';
                break;
            default:
                return 'image/jpeg';
        }
    }

    // function to convert the archive contents into blobs, and return URL
    function createBlobs(entry)
    {
        entry.readData(function(data, err) {
            // Convert the data into an Object URL
            var blob = new Blob([data], {type: getMIME(entry.name)});
            var url = URL.createObjectURL(blob);

            // output the images
            $('#output').append("");
        });

    }

    // function to clear all previous blobs, free up memory
    function clearBlobs()
    {
        $('.imgUrl').each(function(){
            URL.revokeObjectURL($(this).attr('src'));
        });
    }

});<|endoftext|>


<commit_before>const currentGuilds = require('../util/storage.js').currentGuilds
const log = require('../util/logger.js')
const config = require('../config.js')
const dbOps = require('../util/dbOps.js')
const explanation = guildRss => `This command adds users for direct messaging (instead of posting such alerts to the feed's channel by default) when there are any warnings or alerts concerning feeds, such as feed limit changes or feed failures. **The user you're adding or removing will be notified.** The correct syntaxes are:\n\n\`${guildRss.prefix || config.bot.prefix}rssalert add <user id/mention>\` - Add a user to alerted.\n\`${guildRss.prefix || config.bot.prefix}rssalert remove <user id/mention>\` - Remove a user currently receiving alerts\n\`${guildRss.prefix || config.bot.prefix}rssalert list\` - Show all users currently receiving alerts`

module.exports = async (bot, message, automatic) => { // automatic indicates invokation by the bot
  const guildRss = currentGuilds.get(message.guild.id)
  try {
    if (!guildRss || !guildRss.sources || Object.keys(guildRss.sources).length === 0) return await message.channel.send('You cannot set up user alerts if you have not added any feeds.')
    const contentArray = message.content.split(' ').map(item => item.trim())

    switch (contentArray[1]) {
      case 'add':
      case 'remove':
        if (!contentArray[2]) return await message.channel.send(explanation(guildRss))
        const userMention = message.mentions.users.first()
        const member = userMention || await message.guild.members.get(contentArray[2] === 'me' ? message.author.id : contentArray[2])
        if (!member) return await message.channel.send(`The user ${userMention || `with ID \`${contentArray[2]}\``} was not found in this server.`)
        if (contentArray[1] === 'add') {
          if (!Array.isArray(guildRss.sendAlertsTo)) guildRss.sendAlertsTo = [ member.id ]
          else {
            if (guildRss.sendAlertsTo.includes(member.id)) return await message.channel.send(`That user is already enabled for direct messaging feed warnings/failures in this server.`)
            guildRss.sendAlertsTo.push(member.id)
          }
          log.command.info(`Added user to alerts`, member.user)
          await member.send(`At the request of ${member}, you will now be notified of any warnings/failures of feeds in the server \`${guildRss.name}\` (ID \`${guildRss.id}\`).`)
          await message.channel.send(`Successfully enabled user ${member} for direct messaging feed warnings/failures. The user has been notified of this change.`)
        } else {
          if (Array.isArray(guildRss.sendAlertsTo)) {
            const removeIndex = guildRss.sendAlertsTo.indexOf(member.id)
            if (removeIndex === -1) return await message.channel.send('You cannot remove a user that is not currently enabled for feed warning/failure direct messaging alerts.')
            guildRss.sendAlertsTo.splice(removeIndex, 1)
            if (guildRss.sendAlertsTo.length === 0) guildRss.sendAlertsTo = undefined
            log.command.info(`Removed user from alerts`, member.user)
            await member.send(`At the request of ${member}, you will no longer be notified of any warnings or failures of feeds in the server \`${guildRss.name}\` (ID \`${guildRss.id}\`).`)
            await message.channel.send(`Successfully removed user ${member} from direct messaging feed warnings/failures. The user has been notified of this change.`)
          } else return await message.channel.send('You cannot remove a user that is not currently enabled for feed warning/failure direct messaging alerts.')
        }
        await dbOps.guildRss.update(guildRss, true)
        break
      case 'list':
        if (!Array.isArray(guildRss.sendAlertsTo) || guildRss.sendAlertsTo.length === 0) return await message.channel.send(`There are currently no users that will be notified through direct messaging when there are feed warnings/failures in this server.`)
        let msg = `The current list of users below will be notified through direct messaging when there are feed warnings/failures in this server:\n\n`
        for (const id of guildRss.sendAlertsTo) {
          msg += `${await message.guild.members.get(id)}\n`
        }
        await message.channel.send(msg)
        break
      default:
        return await message.channel.send(explanation(guildRss))
    }
  } catch (err) {
    log.command.warning('rssalert', err, true)
    if (err.code !== 50013) message.channel.send(err.message).catch(err => log.command.warning('rssalert 1', message.guild, err))
  }
}
<commit_msg>Fix logging user for rssalert<commit_after>const currentGuilds = require('../util/storage.js').currentGuilds
const log = require('../util/logger.js')
const config = require('../config.js')
const dbOps = require('../util/dbOps.js')
const explanation = guildRss => `This command adds users for direct messaging (instead of posting such alerts to the feed's channel by default) when there are any warnings or alerts concerning feeds, such as feed limit changes or feed failures. **The user you're adding or removing will be notified.** The correct syntaxes are:\n\n\`${guildRss.prefix || config.bot.prefix}rssalert add <user id/mention>\` - Add a user to alerted.\n\`${guildRss.prefix || config.bot.prefix}rssalert remove <user id/mention>\` - Remove a user currently receiving alerts\n\`${guildRss.prefix || config.bot.prefix}rssalert list\` - Show all users currently receiving alerts`

module.exports = async (bot, message, automatic) => { // automatic indicates invokation by the bot
  const guildRss = currentGuilds.get(message.guild.id)
  try {
    if (!guildRss || !guildRss.sources || Object.keys(guildRss.sources).length === 0) return await message.channel.send('You cannot set up user alerts if you have not added any feeds.')
    const contentArray = message.content.split(' ').map(item => item.trim())

    switch (contentArray[1]) {
      case 'add':
      case 'remove':
        if (!contentArray[2]) return await message.channel.send(explanation(guildRss))
        const userMention = message.mentions.users.first()
        const member = userMention || await message.guild.members.get(contentArray[2] === 'me' ? message.author.id : contentArray[2])
        if (!member) return await message.channel.send(`The user ${userMention || `with ID \`${contentArray[2]}\``} was not found in this server.`)
        if (contentArray[1] === 'add') {
          if (!Array.isArray(guildRss.sendAlertsTo)) guildRss.sendAlertsTo = [ member.id ]
          else {
            if (guildRss.sendAlertsTo.includes(member.id)) return await message.channel.send(`That user is already enabled for direct messaging feed warnings/failures in this server.`)
            guildRss.sendAlertsTo.push(member.id)
          }
          log.command.info(`Added user to alerts`, message.guild, userMention || member.user)
          await member.send(`At the request of ${member}, you will now be notified of any warnings/failures of feeds in the server \`${guildRss.name}\` (ID \`${guildRss.id}\`).`)
          await message.channel.send(`Successfully enabled user ${member} for direct messaging feed warnings/failures. The user has been notified of this change.`)
        } else {
          if (Array.isArray(guildRss.sendAlertsTo)) {
            const removeIndex = guildRss.sendAlertsTo.indexOf(member.id)
            if (removeIndex === -1) return await message.channel.send('You cannot remove a user that is not currently enabled for feed warning/failure direct messaging alerts.')
            guildRss.sendAlertsTo.splice(removeIndex, 1)
            if (guildRss.sendAlertsTo.length === 0) guildRss.sendAlertsTo = undefined
            log.command.info(`Removed user from alerts`, message.guild, userMention || member.user)
            await member.send(`At the request of ${member}, you will no longer be notified of any warnings or failures of feeds in the server \`${guildRss.name}\` (ID \`${guildRss.id}\`).`)
            await message.channel.send(`Successfully removed user ${member} from direct messaging feed warnings/failures. The user has been notified of this change.`)
          } else return await message.channel.send('You cannot remove a user that is not currently enabled for feed warning/failure direct messaging alerts.')
        }
        await dbOps.guildRss.update(guildRss, true)
        break
      case 'list':
        if (!Array.isArray(guildRss.sendAlertsTo) || guildRss.sendAlertsTo.length === 0) return await message.channel.send(`There are currently no users that will be notified through direct messaging when there are feed warnings/failures in this server.`)
        let msg = `The current list of users below will be notified through direct messaging when there are feed warnings/failures in this server:\n\n`
        for (const id of guildRss.sendAlertsTo) {
          msg += `${await message.guild.members.get(id)}\n`
        }
        await message.channel.send(msg)
        break
      default:
        return await message.channel.send(explanation(guildRss))
    }
  } catch (err) {
    log.command.warning('rssalert', err, true)
    if (err.code !== 50013) message.channel.send(err.message).catch(err => log.command.warning('rssalert 1', message.guild, err))
  }
}
<|endoftext|>


<commit_before>'use strict';

var blockDoc = require('../lib/block-doc.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.loader = {
  'hello-world': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/hello-world.js');

    test.equal(typeof text, 'string',
        'Loaded file data is a string');
    test.equal(text, "'Hello, World!';",
        'Read the contents of hello-world.js correctly.');

    test.done();
  }

  ,'bad-input-file': function (test) {
    test.throws(
        function () {
          blockDoc.loader.load('./test/fixtures/invalid.js');
        },
        'PARSE_ERROR: ./test/fixtures/invalid.js',
        'Invalid JavaScript file threw an exception.');

    test.done();
  }
};

exports.parser = {
  'parse-named-function': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parsed single method.');
    test.equals(meta[0].name, 'sum',
        'Parsed method name.');

    test.done();
  }

  ,'parse-anonymous-var-function': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-anonymous-var.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parsed single method.');
    test.equals(meta[0].name, 'sum',
        'Parsed method name.');

    test.done();
  }

  ,'parse-anonymous-property-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/sum-anonymous-in-object.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parsed single method.');
    test.equals(meta[0].name, 'sum',
        'Parsed method name.');

    test.done();
  }

  ,'parse-prototype-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/sum-prototype.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parsed single method.');
    test.equals(meta[0].name, 'Base.prototype.sum',
        'Parsed method name.');

    test.done();
  }

  ,'parse-multiple-mixed-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/mixed-function-formats.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 3,
        'Parsed multiple methods.');
    test.equals(meta[0].name, 'sum',
        'Parsed first method name.');
    test.equals(meta[1].name, 'subtract',
        'Parsed second method name.');
    test.equals(meta[2].name, 'multiply',
        'Parsed third method name.');

    test.done();
  }

  ,'parse-function-description': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].description, 'A function that adds two numbers.',
        'Parsed the description.');
    test.done();
  }

  ,'parse-multi-line-function-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/multi-line-function-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].description,
        'Hi. I am a multiline function description. Have a nice day!',
        'Parsed the description.');
    test.done();
  }

  ,'parse-params': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 2,
        'Parsed the list of @params');
    test.equals(meta[0].params[0].type, 'number',
        'Parsed the first parameter type.');
    test.equals(meta[0].params[1].type, 'number',
        'Parsed the second parameter type.');
    test.equals(meta[0].params[0].name, 'num1',
        'Parsed the first parameter name.');
    test.equals(meta[0].params[1].name, 'num2',
        'Parsed the second parameter name.');
    test.equals(meta[0].params[0].description,
        'The first number to add.',
        'Parsed the first parameter description.');
    test.equals(meta[0].params[1].description,
        'The second number to add.',
        'Parsed the second parameter description.');

    test.done();
  }

  ,'parse-multiline-method-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/multi-line-param-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 1,
        'Parsed the list of @params');
    test.equals(meta[0].params[0].type, 'null',
        'Parsed the parameter type.');
    test.equals(meta[0].params[0].name, 'nothing',
        'Parsed the parameter name.');
    test.equals(meta[0].params[0].description,
        'This is nothing.  There\'s no good reason to pass a value here.',
        'Parsed the parameter description.');

    test.done();
  }

  ,'parse-return-no-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-no-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'number',
        'Parsed the return type.');
    test.equals(meta[0]['return'].description, '',
        'Parsed the return description.');

    test.done();
  }

  ,'parse-return-with-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'number',
        'Parsed the return type.');
    test.equals(meta[0]['return'].description,
        'The sum of num1 and num2.',
        'Parsed the return description.');

    test.done();
  }

  ,'parse-return-with-multi-line-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-multi-line-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'null',
        'Parsed the return type.');
    test.equals(meta[0]['return'].description,
        'This method returns null. How very exciting!',
        'Parsed the return description.');

    test.done();
  }

  ,'parse-block-with-all-annotations': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/all-annotations.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 2,
        'Parsed the list of @params');
    test.equals(meta[0].params[0].type, 'number',
        'Parsed the first parameter type.');
    test.equals(meta[0].params[1].type, 'number',
        'Parsed the second parameter type.');
    test.equals(meta[0].params[0].name, 'num1',
        'Parsed the first parameter name.');
    test.equals(meta[0].params[1].name, 'num2',
        'Parsed the second parameter name.');
    test.equals(meta[0].params[0].description,
        'The first number to add.',
        'Parsed the first parameter description.');
    test.equals(meta[0].params[1].description,
        'The second number to add.',
        'Parsed the second parameter description.');
    test.equals(meta[0]['return'].type, 'number',
        'Parsed the return type.');
    test.equals(meta[0]['return'].description,
        'The sum of num1 and num2.',
        'Parsed the return description.');

    test.done();
  }
};

exports.htmlGenerator = {
  'generate-blank-page': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(generatedHtml.match(/<!DOCTYPE html>/).length, 1,
        'Generated an HTML page.');

    test.done();
  }

  ,'generate-custom-title': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {}, {
      'title': 'foobar'
    });

    test.equals(generatedHtml.match(/<title>foobar<\/title>/).length, 1,
        'Generated a custom title.');

    test.done();
  }

  ,'generate-default-title': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(
        generatedHtml.match(/<title>Generated by JSBlockDoc<\/title>/).length,
        1, 'Generated the default title.');

    test.done();
  }

  ,'generate-custom-top-level-header': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {}, {
      'name': 'foobar'
    });

    test.equals(generatedHtml.match(/
foobar<\/h1>/).length, 1,
        'Generated a custom top-level header.');
    test.equals(generatedHtml.match(/
/g).length, 1,
        'Only renders one
.');

    test.done();
  }

  ,'generate-default-top-level-header': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(generatedHtml.match(/
API Reference<\/h1>/).length, 1,
        'Generated the default top-level header.');
    test.equals(generatedHtml.match(/
/g).length, 1,
        'Only renders one
.');

    test.done();
  }
};
<commit_msg>Changes the phrasing of the test assertions.<commit_after>'use strict';

var blockDoc = require('../lib/block-doc.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.loader = {
  'hello-world': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/hello-world.js');

    test.equal(typeof text, 'string',
        'Loads file data is a string');
    test.equal(text, "'Hello, World!';",
        'Read the contents of hello-world.js correctly.');

    test.done();
  }

  ,'bad-input-file': function (test) {
    test.throws(
        function () {
          blockDoc.loader.load('./test/fixtures/invalid.js');
        },
        'PARSE_ERROR: ./test/fixtures/invalid.js',
        'Invalid JavaScript file threw an exception.');

    test.done();
  }
};

exports.parser = {
  'parse-named-function': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parses single method.');
    test.equals(meta[0].name, 'sum',
        'Parses method name.');

    test.done();
  }

  ,'parse-anonymous-var-function': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-anonymous-var.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parses single method.');
    test.equals(meta[0].name, 'sum',
        'Parses method name.');

    test.done();
  }

  ,'parse-anonymous-property-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/sum-anonymous-in-object.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parses single method.');
    test.equals(meta[0].name, 'sum',
        'Parses method name.');

    test.done();
  }

  ,'parse-prototype-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/sum-prototype.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 1,
        'Parses single method.');
    test.equals(meta[0].name, 'Base.prototype.sum',
        'Parses method name.');

    test.done();
  }

  ,'parse-multiple-mixed-function': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/mixed-function-formats.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta.length, 3,
        'Parses multiple methods.');
    test.equals(meta[0].name, 'sum',
        'Parses first method name.');
    test.equals(meta[1].name, 'subtract',
        'Parses second method name.');
    test.equals(meta[2].name, 'multiply',
        'Parses third method name.');

    test.done();
  }

  ,'parse-function-description': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].description, 'A function that adds two numbers.',
        'Parses the description.');
    test.done();
  }

  ,'parse-multi-line-function-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/multi-line-function-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].description,
        'Hi. I am a multiline function description. Have a nice day!',
        'Parses the description.');
    test.done();
  }

  ,'parse-params': function (test) {
    var text = blockDoc.loader.load('./test/fixtures/sum-named.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 2,
        'Parses the list of @params');
    test.equals(meta[0].params[0].type, 'number',
        'Parses the first parameter type.');
    test.equals(meta[0].params[1].type, 'number',
        'Parses the second parameter type.');
    test.equals(meta[0].params[0].name, 'num1',
        'Parses the first parameter name.');
    test.equals(meta[0].params[1].name, 'num2',
        'Parses the second parameter name.');
    test.equals(meta[0].params[0].description,
        'The first number to add.',
        'Parses the first parameter description.');
    test.equals(meta[0].params[1].description,
        'The second number to add.',
        'Parses the second parameter description.');

    test.done();
  }

  ,'parse-multiline-method-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/multi-line-param-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 1,
        'Parses the list of @params');
    test.equals(meta[0].params[0].type, 'null',
        'Parses the parameter type.');
    test.equals(meta[0].params[0].name, 'nothing',
        'Parses the parameter name.');
    test.equals(meta[0].params[0].description,
        'This is nothing.  There\'s no good reason to pass a value here.',
        'Parses the parameter description.');

    test.done();
  }

  ,'parse-return-no-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-no-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'number',
        'Parses the return type.');
    test.equals(meta[0]['return'].description, '',
        'Parses the return description.');

    test.done();
  }

  ,'parse-return-with-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'number',
        'Parses the return type.');
    test.equals(meta[0]['return'].description,
        'The sum of num1 and num2.',
        'Parses the return description.');

    test.done();
  }

  ,'parse-return-with-multi-line-description': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/return-multi-line-description.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0]['return'].type, 'null',
        'Parses the return type.');
    test.equals(meta[0]['return'].description,
        'This method returns null. How very exciting!',
        'Parses the return description.');

    test.done();
  }

  ,'parse-block-with-all-annotations': function (test) {
    var text = blockDoc.loader.load(
        './test/fixtures/all-annotations.js');
    var meta = blockDoc.parser.parseMetadataList(text);

    test.equals(meta[0].params.length, 2,
        'Parses the list of @params');
    test.equals(meta[0].params[0].type, 'number',
        'Parses the first parameter type.');
    test.equals(meta[0].params[1].type, 'number',
        'Parses the second parameter type.');
    test.equals(meta[0].params[0].name, 'num1',
        'Parses the first parameter name.');
    test.equals(meta[0].params[1].name, 'num2',
        'Parses the second parameter name.');
    test.equals(meta[0].params[0].description,
        'The first number to add.',
        'Parses the first parameter description.');
    test.equals(meta[0].params[1].description,
        'The second number to add.',
        'Parses the second parameter description.');
    test.equals(meta[0]['return'].type, 'number',
        'Parses the return type.');
    test.equals(meta[0]['return'].description,
        'The sum of num1 and num2.',
        'Parses the return description.');

    test.done();
  }
};

exports.htmlGenerator = {
  'generate-blank-page': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(generatedHtml.match(/<!DOCTYPE html>/).length, 1,
        'Generates an HTML page.');

    test.done();
  }

  ,'generate-custom-title': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {}, {
      'title': 'foobar'
    });

    test.equals(generatedHtml.match(/<title>foobar<\/title>/).length, 1,
        'Generates a custom title.');

    test.done();
  }

  ,'generate-default-title': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(
        generatedHtml.match(/<title>Generated by JSBlockDoc<\/title>/).length,
        1, 'Generates the default title.');

    test.done();
  }

  ,'generate-custom-top-level-header': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {}, {
      'name': 'foobar'
    });

    test.equals(generatedHtml.match(/
foobar<\/h1>/).length, 1,
        'Generates a custom top-level header.');
    test.equals(generatedHtml.match(/
/g).length, 1,
        'Only renders one
.');

    test.done();
  }

  ,'generate-default-top-level-header': function (test) {
    var generatedHtml = blockDoc.htmlGenerator.generate('./template', {});

    test.equals(generatedHtml.match(/
API Reference<\/h1>/).length, 1,
        'Generates the default top-level header.');
    test.equals(generatedHtml.match(/
/g).length, 1,
        'Only renders one
.');

    test.done();
  }
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */
'use strict';

import type {Map} from 'immutable';
import type Store from './Store';

function nodeMatchesText(node: Map, needle: string, key: string, store: Store): boolean {
  var name = node.get('name');
  if (node.get('nodeType') === 'Native' && store.get(store.getParent(key)).get('nodeType') === 'NativeWrapper') {
    return false;
  }
  if (name) {
    if (node.get('nodeType') !== 'Wrapper' && name.toLowerCase().indexOf(needle) !== -1) {
      return true;
    }
  }
  var text = node.get('text');
  if (text && text.toLowerCase().indexOf(needle) !== -1) {
    return true;
  }
  var children = node.get('children');
  if (typeof children === 'string' && children.toLowerCase().indexOf(needle) !== -1) {
    return true;
  }
  return false;
}

module.exports = nodeMatchesText;
<commit_msg>Fix NativeWrapper check in nodeMatchesText<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */
'use strict';

import type {Map} from 'immutable';
import type Store from './Store';

function nodeMatchesText(node: Map, needle: string, key: string, store: Store): boolean {
  var name = node.get('name');
  var wrapper = store.get(store.getParent(key));
  if (node.get('nodeType') === 'Native' && wrapper && wrapper.get('nodeType') === 'NativeWrapper') {
    return false;
  }
  if (name) {
    if (node.get('nodeType') !== 'Wrapper' && name.toLowerCase().indexOf(needle) !== -1) {
      return true;
    }
  }
  var text = node.get('text');
  if (text && text.toLowerCase().indexOf(needle) !== -1) {
    return true;
  }
  var children = node.get('children');
  if (typeof children === 'string' && children.toLowerCase().indexOf(needle) !== -1) {
    return true;
  }
  return false;
}

module.exports = nodeMatchesText;
<|endoftext|>


<commit_before>var fs = require('fs'),
    fsutil = require('../lib/fsutil'),
    path = require('path'),
    Step = require('step');

commands['start'].options['port'] = {
    'title': 'port=[port]',
    'description': 'Server port.',
    'default': 8889
};

commands['start'].options['examples'] = {
    'title': 'examples=1|0',
    'description': 'Copy example projects on first start.',
    'default': 1
};

commands['start'].prototype.bootstrap = function(plugin, callback) {
    var settings = Bones.plugin.config;
    if (!path.existsSync(settings.files)) {
        console.warn('Creating files dir %s', settings.files);
        fsutil.mkdirpSync(settings.files, 0755);
    }
    ['export', 'project', 'data', 'cache', 'cache/tile'].forEach(function(key) {
        var dir = path.join(settings.files, key);
        if (!path.existsSync(dir)) {
            console.warn('Creating %s dir %s', key, dir);
            fsutil.mkdirpSync(dir, 0755);
            if (key === 'project' && settings.examples) {
                var examples = path.resolve(path.join(__dirname, '..', 'examples'));
                fsutil.cprSync(examples, dir);
            }
        }
    });

    // Apply server-side mixins/overrides.
    var sync = require('backbone-dirty')(settings.files + '/app.db').sync;
    Backbone.sync = sync;

    // Process any waiting exports.
    (new models.Exports).fetch();
    callback();
};

<commit_msg>Catch and log node-dirty load errors. Fixes #432.<commit_after>var fs = require('fs'),
    fsutil = require('../lib/fsutil'),
    path = require('path'),
    Step = require('step');

commands['start'].options['port'] = {
    'title': 'port=[port]',
    'description': 'Server port.',
    'default': 8889
};

commands['start'].options['examples'] = {
    'title': 'examples=1|0',
    'description': 'Copy example projects on first start.',
    'default': 1
};

commands['start'].prototype.bootstrap = function(plugin, callback) {
    var settings = Bones.plugin.config;
    if (!path.existsSync(settings.files)) {
        console.warn('Creating files dir %s', settings.files);
        fsutil.mkdirpSync(settings.files, 0755);
    }
    ['export', 'project', 'data', 'cache', 'cache/tile'].forEach(function(key) {
        var dir = path.join(settings.files, key);
        if (!path.existsSync(dir)) {
            console.warn('Creating %s dir %s', key, dir);
            fsutil.mkdirpSync(dir, 0755);
            if (key === 'project' && settings.examples) {
                var examples = path.resolve(path.join(__dirname, '..', 'examples'));
                fsutil.cprSync(examples, dir);
            }
        }
    });

    // Apply server-side mixins/overrides.
    var db = require('backbone-dirty')(settings.files + '/app.db');
    db.dirty.on('error', console.log);
    Backbone.sync = db.sync;

    // Process any waiting exports.
    (new models.Exports).fetch();
    callback();
};

<|endoftext|>