<commit_before>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var WebAudioSound = require('./WebAudioSound');
//  Phaser.Loader.WebAudioSoundManager
var WebAudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function WebAudioSoundManager(game) {
        /**
         * Flag indicating if Web Audio implementation is webkit or standards based.
         * There are certain cases where they have to be handled differently.
         *
         * https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
         *
         * @property {boolean} webkit
         */
        this.webkit = !!window['webkitAudioContext'] && !window['AudioContext'];
        /**
         * The AudioContext being used for playback.
         *
         * @property {AudioContext} context
         */
        this.context = this.createAudioContext(game);
        /**
         * [description]
         *
         * @property {GainNode} masterMuteNode
         */
        this.masterMuteNode = this.context.createGain();
        /**
         * [description]
         *
         * @property {GainNode} masterVolumeNode
         */
        this.masterVolumeNode = this.context.createGain();
        this.masterMuteNode.connect(this.masterVolumeNode);
        this.masterVolumeNode.connect(this.context.destination);
        /**
         * Destination node for connecting individual sounds to.
         *
         * @property {AudioNode} destination
         */
        this.destination = this.masterMuteNode;
        /**
         * Property that actually holds the value of global playback rate.
         *
         * @property {number} _rate
         * @private
         */
        this._rate = 1;
        /**
         * Property that actually holds the value of global detune.
         *
         * @property {number} _detune
         * @private
         */
        this._detune = 0;
        this.unlock();
        BaseSoundManager.call(this, game);
    },
    /**
     * @private
     * @param game
     * @returns {AudioContext}
     */
    createAudioContext: function (game) {
        var audioConfig = game.config.audio;
        if (audioConfig && audioConfig.context) {
            return audioConfig.context;
        }
        return new (window['AudioContext'] || window['webkitAudioContext'])();
    },
    add: function (key, config) {
        var sound = new WebAudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    /**
     * @private
     */
    unlock: function () {
        var _this = this;
        if (this.context.state === 'suspended') {
            var unlock_1 = function () {
                document.body.removeEventListener('touchstart', unlock_1);
                _this.context.resume();
            };
            document.body.addEventListener('touchstart', unlock_1, false);
        }
    },
    onBlur: function () {
        this.context.suspend();
    },
    onFocus: function () {
        this.context.resume();
    }
});
/**
 * Global mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'mute', {
    get: function () {
        return this.masterMuteNode.gain.value === 0;
    },
    set: function (value) {
        this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0);
    }
});
/**
 * Global volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'volume', {
    get: function () {
        return this.masterVolumeNode.gain.value;
    },
    set: function (value) {
        this.masterVolumeNode.gain.setValueAtTime(value, 0);
    }
});
/**
 * Global playback rate.
 * @property {number} rate
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'rate', {
    get: function () {
        return this._rate;
    },
    set: function (value) {
        this._rate = value;
        this.sounds.forEach(function (sound) {
            sound.setRate();
        }, this);
    }
});
/**
 * Global detune.
 * @property {number} detune
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'detune', {
    get: function () {
        return this._detune;
    },
    set: function (value) {
        this._detune = value;
        this.sounds.forEach(function (sound) {
            // invoke sound's detune setter method to update
            // value based on new global detune value
            sound.detune = sound.detune;
        }, this);
    }
});
module.exports = WebAudioSoundManager;
<commit_msg>Calling setRate method on all sound objects when updating global detune value<commit_after>var Class = require('../../utils/Class');
var BaseSoundManager = require('../BaseSoundManager');
var WebAudioSound = require('./WebAudioSound');
//  Phaser.Loader.WebAudioSoundManager
var WebAudioSoundManager = new Class({
    Extends: BaseSoundManager,
    initialize: function WebAudioSoundManager(game) {
        /**
         * Flag indicating if Web Audio implementation is webkit or standards based.
         * There are certain cases where they have to be handled differently.
         *
         * https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext
         *
         * @property {boolean} webkit
         */
        this.webkit = !!window['webkitAudioContext'] && !window['AudioContext'];
        /**
         * The AudioContext being used for playback.
         *
         * @property {AudioContext} context
         */
        this.context = this.createAudioContext(game);
        /**
         * [description]
         *
         * @property {GainNode} masterMuteNode
         */
        this.masterMuteNode = this.context.createGain();
        /**
         * [description]
         *
         * @property {GainNode} masterVolumeNode
         */
        this.masterVolumeNode = this.context.createGain();
        this.masterMuteNode.connect(this.masterVolumeNode);
        this.masterVolumeNode.connect(this.context.destination);
        /**
         * Destination node for connecting individual sounds to.
         *
         * @property {AudioNode} destination
         */
        this.destination = this.masterMuteNode;
        /**
         * Property that actually holds the value of global playback rate.
         *
         * @property {number} _rate
         * @private
         */
        this._rate = 1;
        /**
         * Property that actually holds the value of global detune.
         *
         * @property {number} _detune
         * @private
         */
        this._detune = 0;
        this.unlock();
        BaseSoundManager.call(this, game);
    },
    /**
     * @private
     * @param game
     * @returns {AudioContext}
     */
    createAudioContext: function (game) {
        var audioConfig = game.config.audio;
        if (audioConfig && audioConfig.context) {
            return audioConfig.context;
        }
        return new (window['AudioContext'] || window['webkitAudioContext'])();
    },
    add: function (key, config) {
        var sound = new WebAudioSound(this, key, config);
        this.sounds.push(sound);
        return sound;
    },
    /**
     * @private
     */
    unlock: function () {
        var _this = this;
        if (this.context.state === 'suspended') {
            var unlock_1 = function () {
                document.body.removeEventListener('touchstart', unlock_1);
                _this.context.resume();
            };
            document.body.addEventListener('touchstart', unlock_1, false);
        }
    },
    onBlur: function () {
        this.context.suspend();
    },
    onFocus: function () {
        this.context.resume();
    }
});
/**
 * Global mute setting.
 * @property {boolean} mute
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'mute', {
    get: function () {
        return this.masterMuteNode.gain.value === 0;
    },
    set: function (value) {
        this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0);
    }
});
/**
 * Global volume setting.
 * @property {number} volume
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'volume', {
    get: function () {
        return this.masterVolumeNode.gain.value;
    },
    set: function (value) {
        this.masterVolumeNode.gain.setValueAtTime(value, 0);
    }
});
/**
 * Global playback rate.
 * @property {number} rate
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'rate', {
    get: function () {
        return this._rate;
    },
    set: function (value) {
        this._rate = value;
        this.sounds.forEach(function (sound) {
            sound.setRate();
        }, this);
    }
});
/**
 * Global detune.
 * @property {number} detune
 */
Object.defineProperty(WebAudioSoundManager.prototype, 'detune', {
    get: function () {
        return this._detune;
    },
    set: function (value) {
        this._detune = value;
        this.sounds.forEach(function (sound) {
            sound.setRate();
        }, this);
    }
});
module.exports = WebAudioSoundManager;
<|endoftext|>


<commit_before>"use babel";

describe('The languagetool-linter for AtomLinter', () => {
  const lint = require('../lib/linter-languagetool').provideLinter().lint;

  beforeEach(() => {
    waitsForPromise(() => {
      return atom.packages.activatePackage("linter-languagetool");
    });
  });

  it('checks the example text taken from the languagetool homepage', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/languagetool-hp-test.txt').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(8);

          expect(messages[0].type).toBeDefined();
          expect(messages[0].type).toEqual('Error');
          expect(messages[0].text).toBeDefined();
          expect(messages[0].text).toEqual('This sentence does not start with an uppercase letter');
          expect(messages[0].filePath).toBeDefined();
          expect(messages[0].filePath).toMatch(/.+languagetool-hp-test\.txt$/);
          expect(messages[0].range).toBeDefined();
          expect(messages[0].range.length).toEqual(2);
          expect(messages[0].range).toEqual([[2, 0], [2, 2]]);
        });
      });
    });
  });
});
<commit_msg>adapt test case to linter v2 api<commit_after>"use babel";

describe('The languagetool-linter for AtomLinter', () => {
  const lint = require('../lib/linter-languagetool').provideLinter().lint;

  beforeEach(() => {
    waitsForPromise(() => {
      return atom.packages.activatePackage("linter-languagetool");
    });
  });

  it('checks the example text taken from the languagetool homepage', () => {
    waitsForPromise(() => {
      return atom.workspace.open(__dirname + '/test_files/languagetool-hp-test.txt').then(editor => {
        return lint(editor).then(messages => {
          expect(messages.length).toEqual(8);

          expect(messages[0].severity).toBeDefined();
          expect(messages[0].severity).toEqual('error');
          expect(messages[0].excerpt).toBeDefined();
          expect(messages[0].excerpt).toEqual('This sentence does not start with an uppercase letter');
          expect(messages[0].location.file).toBeDefined();
          expect(messages[0].location.file).toMatch(/.+languagetool-hp-test\.txt$/);
          expect(messages[0].location.position).toBeDefined();
          expect(messages[0].location.position.length).toEqual(2);
          expect(messages[0].location.position).toEqual([[2, 0], [2, 2]]);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var txt = null;
describe('Simple color picker', function() {

	var get_box = function() {
		return $('div#' + txt.attr('id').replace(/-/g, '') + '_color-picker');
	};

	beforeEach(function() {
		// add an input id="txt"
		txt = $(document.createElement('input'));
		txt.attr('id', 'txt');
		$('body').append(txt);
	});

	afterEach(function() {
		get_box().remove();
		txt.remove();
	});

	describe('default markup', function() {
		beforeEach(function() {
			txt.simpleColorPicker();
		});

		it('appends div#txt_color-picker to the body', function() {
			expect(get_box().length).toBe(1);
		});

		it('which is hidden', function() {
			expect(get_box().is(':hidden')).toBeTruthy();
		});

		it('with a ul inside', function() {
			expect(get_box().find('ul').length).toBe(1);
		});

		it('and 64 li.color-box', function() {
			expect(get_box().find('li.color-box').length).toBe(64);
		});

		it('of which 8 have clear:both (according to colorsPerLine default value)', function() {
			expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(8);
		});
	});

	describe('options', function() {
		it('16 colors per line makes 4 clear:boths', function() {
			txt.simpleColorPicker({ colorsPerLine: 16 });
			expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(4);
		});

		describe('black and white only', function() {
			beforeEach(function(){
				txt.simpleColorPicker({ colors: ['#000000', '#ffffff'] });
			});

			it('makes 2 li.color-box', function() {
				expect(get_box().find('li.color-box').length).toBe(2);
			});

			it('one has background-color: #000000', function() {
				expect(get_box().find('li.color-box[style*="background-color: #000000"]').length).toBe(1);
			});

			it('another has background-color: #ffffff', function() {
				expect(get_box().find('li.color-box[style*="background-color: #ffffff"]').length).toBe(1);
			});

			it('one of which has clear:both', function() {
				expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(1);
			});

		});
	});

});
<commit_msg>Adding more tests<commit_after>var txt = null;
describe('Simple color picker', function() {

	var get_box = function() {
		return $('div#' + txt.attr('id').replace(/-/g, '') + '_color-picker');
	};

	beforeEach(function() {
		// add an input id="txt"
		txt = $(document.createElement('input'));
		txt.attr('id', 'txt');
		$('body').append(txt);
	});

	afterEach(function() {
		get_box().remove();
		txt.remove();
	});

	describe('default markup', function() {
		beforeEach(function() {
			txt.simpleColorPicker();
		});

		it('appends div#txt_color-picker to the body', function() {
			expect(get_box().length).toBe(1);
		});

		it('which is hidden', function() {
			expect(get_box().is(':hidden')).toBeTruthy();
		});

		it('with a ul inside', function() {
			expect(get_box().find('ul').length).toBe(1);
		});

		it('and 64 li.color-box', function() {
			expect(get_box().find('li.color-box').length).toBe(64);
		});

		it('of which 8 have clear:both (according to colorsPerLine default value)', function() {
			expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(8);
		});

		it('the first li.color-box has background-color #000000', function() {
			expect(get_box().find('li.color-box:first').attr('style').indexOf('background-color: #000000')).toBeGreaterThan(-1);
		});

		it('and title #000000', function() {
			expect(get_box().find('li.color-box:first').attr('title')).toBe('#000000');
		});
	});

	describe('options', function() {
		it('16 colors per line makes 4 clear:boths', function() {
			txt.simpleColorPicker({ colorsPerLine: 16 });
			expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(4);
		});

		describe('black and white only', function() {
			beforeEach(function(){
				txt.simpleColorPicker({ colors: ['#000000', '#ffffff'] });
			});

			it('makes 2 li.color-box', function() {
				expect(get_box().find('li.color-box').length).toBe(2);
			});

			it('one has background-color: #000000', function() {
				expect(get_box().find('li.color-box[style*="background-color: #000000"]').length).toBe(1);
			});

			it('another has background-color: #ffffff', function() {
				expect(get_box().find('li.color-box[style*="background-color: #ffffff"]').length).toBe(1);
			});

			it('one of which has clear:both', function() {
				expect(get_box().find('li.color-box[style*="clear: both"]').length).toBe(1);
			});
		});
	});

	describe('behavior', function() {
		var box = null;

		beforeEach(function() {
			txt.simpleColorPicker();
			box = get_box();
		});

		describe('focusing input', function() {
			it('positions color picker aligned to input right', function() {
				txt.focus();
				expect(box.offset().left + box.outerWidth()).toBe(txt.offset().left + txt.outerWidth());
			});

			it('or to left, if picker is wider than input', function() {
				txt.width(10).focus();
				expect(box.offset().left).toBe(txt.offset().left);
			});

			it('shows color picker', function() {
				expect(box.is(':hidden')).toBeTruthy();
				txt.focus();
				expect(box.is(':hidden')).not.toBeTruthy();
			});
		});

		describe('after picker is open', function() {
			beforeEach(function() {
				txt.focus();
			});

			it('clicking outside closes it', function() {
				expect(box.is(':hidden')).not.toBeTruthy();
				$('body').click();
				expect(box.is(':hidden')).toBeTruthy();
			});

			it('clicking another element closes it', function() {
				expect(box.is(':hidden')).not.toBeTruthy();
				var btn = $(document.createElement('button'));
				$('body').append(btn);
				btn.click();
				expect(box.is(':hidden')).toBeTruthy();
				btn.remove();
			});

			describe('clicking a color', function() {
				var color_li = null;
				beforeEach(function() {
					color_li = box.find('li.color-box:first');
					color_li.click();
				});

				it('fills the input with the right color code', function() {
					expect(txt.val()).toBe(color_li.attr('title'));
				});

				it('hides the picker', function() {
					expect(box.is(':hidden')).toBeTruthy();
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>/**
 * Setup coverage via istanbul.
 *
 * @author Manuel Leuenberger
 */

var path = require('path');
var istanbul = require('istanbul');

var REPORTER = __dirname + '/reporter.js';
var DEFAULT_TEMPLATE = 'node_modules/grunt-contrib-jasmine/tasks/jasmine/'
		+ 'templates/DefaultRunner.tmpl';

exports.process = function (grunt, task, context) {
	// prepare reports
	var reports = [];
	if (typeof context.options.report == 'string'
			|| context.options.report instanceof String) {
		reports.push(istanbul.Report.create('html', {
			dir: context.options.report
		}));
	} else if (context.options.report instanceof Array) {
		for (var i = 0; i < context.options.report.length; i++) {
			var report = context.options.report[i];
			reports.push(istanbul.Report.create(report.type, report.options));
		}
	} else {
		reports.push(istanbul.Report.create(context.options.report.type,
				context.options.report.options));
	}
	// prepend coverage reporter
	context.scripts.reporters.unshift(REPORTER);
	// instrument sources
	var instrumenter = new istanbul.Instrumenter();
	var instrumentedSrc = [];
	context.scripts.src.forEach(function (src) {
		var tmpSrc = path.join(context.temp, src);
		grunt.file.write(tmpSrc, instrumenter.instrumentSync(
				grunt.file.read(src), src));
		instrumentedSrc.push(tmpSrc);
	});
	context.scripts.src = instrumentedSrc;
	// listen to coverage event dispatched by reporter and write reports
	var collector = new istanbul.Collector();
	var coverageJson = context.options.coverage;
	task.phantomjs.on('jasmine.coverage', function (coverage) {
		grunt.file.write(coverageJson, JSON.stringify(coverage));
		collector.add(coverage);
		for (var i = 0; i < reports.length; i++) {
			reports[i].writeReport(collector, true);
		}
	});
	// use template option to mix in coverage
	var template = context.options.template;
	context.options = context.options.templateOptions || {};
	if (!template) {
		template = DEFAULT_TEMPLATE;
	}
	if (template.process) {
		return template.process(grunt, task, context);
	} else {
		return grunt.util._.template(grunt.file.read(template), context);
	}
};<commit_msg>use explicit folder path as __dirname gives problems (uses absolute path)<commit_after>/**
 * Setup coverage via istanbul.
 *
 * @author Manuel Leuenberger
 */

var path = require('path');
var istanbul = require('istanbul');

var REPORTER = "node_modules/grunt-template-jasmine-istanbul/src/main/js/reporter.js";
var DEFAULT_TEMPLATE = 'node_modules/grunt-contrib-jasmine/tasks/jasmine/'
		+ 'templates/DefaultRunner.tmpl';

exports.process = function (grunt, task, context) {
	// prepare reports
	var reports = [];
	if (typeof context.options.report == 'string'
			|| context.options.report instanceof String) {
		reports.push(istanbul.Report.create('html', {
			dir: context.options.report
		}));
	} else if (context.options.report instanceof Array) {
		for (var i = 0; i < context.options.report.length; i++) {
			var report = context.options.report[i];
			reports.push(istanbul.Report.create(report.type, report.options));
		}
	} else {
		reports.push(istanbul.Report.create(context.options.report.type,
				context.options.report.options));
	}
	// prepend coverage reporter
	context.scripts.reporters.unshift(REPORTER);
	// instrument sources
	var instrumenter = new istanbul.Instrumenter();
	var instrumentedSrc = [];
	context.scripts.src.forEach(function (src) {
		var tmpSrc = path.join(context.temp, src);
		grunt.file.write(tmpSrc, instrumenter.instrumentSync(
				grunt.file.read(src), src));
		instrumentedSrc.push(tmpSrc);
	});
	context.scripts.src = instrumentedSrc;
	// listen to coverage event dispatched by reporter and write reports
	var collector = new istanbul.Collector();
	var coverageJson = context.options.coverage;
	task.phantomjs.on('jasmine.coverage', function (coverage) {
		grunt.file.write(coverageJson, JSON.stringify(coverage));
		collector.add(coverage);
		for (var i = 0; i < reports.length; i++) {
			reports[i].writeReport(collector, true);
		}
	});
	// use template option to mix in coverage
	var template = context.options.template;
	context.options = context.options.templateOptions || {};
	if (!template) {
		template = DEFAULT_TEMPLATE;
	}
	if (template.process) {
		return template.process(grunt, task, context);
	} else {
		return grunt.util._.template(grunt.file.read(template), context);
	}
};<|endoftext|>


<commit_before>const {promisify} = require('util');
const {tokenize} = require('kuromojin');
const {katakanize, hiraganize} = require('japanese');
const fs = require('fs');
const path = require('path');
const qs = require('querystring');
const storage = require('node-persist');
const download = require('download');
const cloudinary = require('cloudinary');
const {escapeRegExp, uniq} = require('lodash');
const toJapanese = require('jp-num/toJapanese');
const iconv = require('iconv-lite');
const {toZenKana} = require('jaconv');

module.exports = async ({rtmClient: rtm, webClient: slack}) => {
	const cities = (await promisify(fs.readFile)(path.resolve(__dirname, 'cities.csv')))
		.toString()
		.split('\n')
		.filter((line) => line)
		.map((line) => line.split(','))
		.map(([prefecture, name, reading, year]) => ({
			type: 'city',
			prefecture,
			name,
			reading,
			year: year === '' ? null : parseInt(year),
		}));

	const stations = (await promisify(fs.readFile)(path.resolve(__dirname, 'stations.csv')))
		.toString()
		.split('\n')
		.filter((line) => line)
		.map((line) => line.split(','))
		.map(([name, reading, description, year]) => ({
			type: 'station',
			name,
			reading,
			description,
			year,
		}));

	const readings = uniq([
		...cities.map(({reading}) => reading),
		...stations.map(({reading}) => reading).filter((reading) => reading.length >= 4),
	]).sort((a, b) => b.length - a.length);

	const names = uniq([...cities.map(({name}) => name), ...stations.map(({name}) => name).filter((reading) => reading.length >= 3)]).sort(
		(a, b) => b.length - a.length
	);

	const yearSortedCities = cities.slice().sort((a, b) => (a.year || 10000) - (b.year || 10000));

	const yearSortedStations = stations.slice().sort((a, b) => (a.year ? 0 : 1) - (b.year ? 0 : 1));

	const citiesRegex = new RegExp(
		`(${[...names.map((name) => escapeRegExp(name)), ...readings.map((reading) => escapeRegExp(reading))].join('|')})$`
	);

	const citiesMap = new Map([
		...yearSortedStations.map((station) => [station.reading, station]),
		...yearSortedStations.map((station) => [station.name, station]),
		...yearSortedCities.map((city) => [city.reading, city]),
		...yearSortedCities.map((city) => [city.name, city]),
	]);

	await storage.init({
		dir: path.resolve(__dirname, '__cache__'),
	});

	const englishDictPath = path.resolve(__dirname, 'bep-ss-2.3', 'bep-eng.dic');

	const englishDictExists = await new Promise((resolve) => {
		fs.access(englishDictPath, fs.constants.F_OK, (error) => {
			resolve(!error);
		});
	});

	if (!englishDictExists) {
		await download('http://www.argv.org/bep/files/linux/beta/bep-ss-2.3.tar.gz', __dirname, {extract: true});
	}

	const englishDictBuffer = await promisify(fs.readFile)(englishDictPath);
	const englishDictText = iconv.decode(englishDictBuffer, 'sjis');
	const englishDict = new Map([
		...englishDictText
			.split('\n')
			.map((line) => {
				const [english, japanese] = line.split(' ');
				if (!japanese) {
					return null;
				}
				return [english.toLowerCase(), toZenKana(japanese)];
			})
			.filter((entry) => entry),
		['a', 'えー'],
		['b', 'びー'],
		['c', 'しー'],
		['d', 'でぃー'],
		['e', 'いー'],
		['f', 'えふ'],
		['g', 'じー'],
		['h', 'えいち'],
		['i', 'あい'],
		['j', 'じぇい'],
		['k', 'けい'],
		['l', 'える'],
		['m', 'えむ'],
		['n', 'えぬ'],
		['o', 'おー'],
		['p', 'ぴー'],
		['q', 'きゅー'],
		['r', 'あーる'],
		['s', 'えす'],
		['t', 'てぃー'],
		['u', 'ゆー'],
		['v', 'ぶい'],
		['w', 'だぶりゅー'],
		['x', 'えっくす'],
		['y', 'わい'],
		['z', 'ずぃー'],
	]);
	const englishDictRegex = new RegExp(
		`\\b(${Array.from(englishDict.keys())
			.map((word) => escapeRegExp(word))
			.join('|')})\\b`,
		'gi'
	);

	const getReading = async (text) => {
		const tokens = await tokenize(text.replace(/[\d,]+/g, (number) => toJapanese(number.replace(/,/g, ''))));
		const reading = Array.from(katakanize(tokens.map(({reading: read, surface_form}) => read || surface_form || '').join('')))
			.join('')
			.replace(/\P{Script_Extensions=Katakana}/gu, '');
		return toZenKana(reading);
	};

	rtm.on('message', async (message) => {
		if (message.channel !== process.env.CHANNEL_SANDBOX) {
			return;
		}

		if (!message.text) {
			return;
		}

		if (message.text && message.text.startsWith('@tashibot')) {
			const reading = hiraganize(
				await getReading(
					message.text.replace(/^@tashibot/, '').replace(englishDictRegex, (english) => englishDict.get(english.toLowerCase()) || english)
				)
			);
			await slack.chat.postMessage({
				channel: process.env.CHANNEL_SANDBOX,
				text: reading,
				username: 'tashibot',
				icon_emoji: ':japan:',
			});
			return;
		}

		if (message.text.slice(-20).match(/^[\x00-\x7F]+$/)) {
			return;
		}

		if (message.username === 'tashibot') {
			return;
		}

		const text = message.text.replace(englishDictRegex, (english) => englishDict.get(english.toLowerCase()) || english).slice(-20);
		const reading = await getReading(text);

		const matches = katakanize(text).match(citiesRegex) || reading.match(citiesRegex);

		if (matches === null) {
			return;
		}

		const city = citiesMap.get(matches[1]);
		const placeText = city.type === 'city' ? `${city.name},${city.prefecture}` : `${city.name},${city.description}`;
		const imageUrl = `https://maps.googleapis.com/maps/api/staticmap?${qs.encode({
			center: placeText,
			zoom: city.type === 'city' ? 9 : 15,
			scale: 1,
			size: '600x300',
			maptype: 'roadmap',
			key: process.env.GOOGLEMAP_TOKEN,
			format: 'png',
			visual_refresh: true,
			markers: `size:mid|color:0xfb724a|label:|${placeText}`,
		})}`;

		let cloudinaryData = await storage.getItem(imageUrl);

		if (!cloudinaryData) {
			const imageData = await download(imageUrl);
			cloudinaryData = await new Promise((resolve, reject) => {
				cloudinary.v2.uploader
					.upload_stream({resource_type: 'image'}, (error, data) => {
						if (error) {
							reject(error);
						} else {
							resolve(data);
						}
					})
					.end(imageData);
			});
			await storage.setItem(imageUrl, cloudinaryData);
		}

		const response = (() => {
			if (city.type === 'city') {
				const yearText = city.year === null ? '' : `(${city.year}年消滅)`;
				return `${city.prefecture}${city.name} ${yearText}`;
			}

			const descriptionText =
				city.description || city.year
					? `(${[...(city.description ? [city.description] : []), ...(city.year ? [city.year] : [])].join('、')})`
					: '';
			return `${city.name} ${descriptionText}`;
		})().trim();

		await slack.chat.postMessage({
			channel: process.env.CHANNEL_SANDBOX,
			text: response,
			username: 'tashibot',
			icon_emoji: ':japan:',
			attachments: [
				{
					image_url: cloudinaryData.secure_url,
					fallback: response,
				},
			],
		});
	});
};
<commit_msg>tashibot: Throttle<commit_after>const {promisify} = require('util');
const {tokenize} = require('kuromojin');
const {katakanize, hiraganize} = require('japanese');
const fs = require('fs');
const path = require('path');
const qs = require('querystring');
const storage = require('node-persist');
const download = require('download');
const cloudinary = require('cloudinary');
const {escapeRegExp, uniq} = require('lodash');
const toJapanese = require('jp-num/toJapanese');
const iconv = require('iconv-lite');
const {toZenKana} = require('jaconv');

const histories = [];

module.exports = async ({rtmClient: rtm, webClient: slack}) => {
	const cities = (await promisify(fs.readFile)(path.resolve(__dirname, 'cities.csv')))
		.toString()
		.split('\n')
		.filter((line) => line)
		.map((line) => line.split(','))
		.map(([prefecture, name, reading, year]) => ({
			type: 'city',
			prefecture,
			name,
			reading,
			year: year === '' ? null : parseInt(year),
		}));

	const stations = (await promisify(fs.readFile)(path.resolve(__dirname, 'stations.csv')))
		.toString()
		.split('\n')
		.filter((line) => line)
		.map((line) => line.split(','))
		.map(([name, reading, description, year]) => ({
			type: 'station',
			name,
			reading,
			description,
			year,
		}));

	const readings = uniq([
		...cities.map(({reading}) => reading),
		...stations.map(({reading}) => reading).filter((reading) => reading.length >= 4),
	]).sort((a, b) => b.length - a.length);

	const names = uniq([...cities.map(({name}) => name), ...stations.map(({name}) => name).filter((reading) => reading.length >= 3)]).sort(
		(a, b) => b.length - a.length
	);

	const yearSortedCities = cities.slice().sort((a, b) => (a.year || 10000) - (b.year || 10000));

	const yearSortedStations = stations.slice().sort((a, b) => (a.year ? 0 : 1) - (b.year ? 0 : 1));

	const citiesRegex = new RegExp(
		`(${[...names.map((name) => escapeRegExp(name)), ...readings.map((reading) => escapeRegExp(reading))].join('|')})$`
	);

	const citiesMap = new Map([
		...yearSortedStations.map((station) => [station.reading, station]),
		...yearSortedStations.map((station) => [station.name, station]),
		...yearSortedCities.map((city) => [city.reading, city]),
		...yearSortedCities.map((city) => [city.name, city]),
	]);

	await storage.init({
		dir: path.resolve(__dirname, '__cache__'),
	});

	const englishDictPath = path.resolve(__dirname, 'bep-ss-2.3', 'bep-eng.dic');

	const englishDictExists = await new Promise((resolve) => {
		fs.access(englishDictPath, fs.constants.F_OK, (error) => {
			resolve(!error);
		});
	});

	if (!englishDictExists) {
		await download('http://www.argv.org/bep/files/linux/beta/bep-ss-2.3.tar.gz', __dirname, {extract: true});
	}

	const englishDictBuffer = await promisify(fs.readFile)(englishDictPath);
	const englishDictText = iconv.decode(englishDictBuffer, 'sjis');
	const englishDict = new Map([
		...englishDictText
			.split('\n')
			.map((line) => {
				const [english, japanese] = line.split(' ');
				if (!japanese) {
					return null;
				}
				return [english.toLowerCase(), toZenKana(japanese)];
			})
			.filter((entry) => entry),
		['a', 'えー'],
		['b', 'びー'],
		['c', 'しー'],
		['d', 'でぃー'],
		['e', 'いー'],
		['f', 'えふ'],
		['g', 'じー'],
		['h', 'えいち'],
		['i', 'あい'],
		['j', 'じぇい'],
		['k', 'けい'],
		['l', 'える'],
		['m', 'えむ'],
		['n', 'えぬ'],
		['o', 'おー'],
		['p', 'ぴー'],
		['q', 'きゅー'],
		['r', 'あーる'],
		['s', 'えす'],
		['t', 'てぃー'],
		['u', 'ゆー'],
		['v', 'ぶい'],
		['w', 'だぶりゅー'],
		['x', 'えっくす'],
		['y', 'わい'],
		['z', 'ずぃー'],
	]);
	const englishDictRegex = new RegExp(
		`\\b(${Array.from(englishDict.keys())
			.map((word) => escapeRegExp(word))
			.join('|')})\\b`,
		'gi'
	);

	const getReading = async (text) => {
		const tokens = await tokenize(text.replace(/[\d,]+/g, (number) => toJapanese(number.replace(/,/g, ''))));
		const reading = Array.from(katakanize(tokens.map(({reading: read, surface_form}) => read || surface_form || '').join('')))
			.join('')
			.replace(/\P{Script_Extensions=Katakana}/gu, '');
		return toZenKana(reading);
	};

	rtm.on('message', async (message) => {
		if (message.channel !== process.env.CHANNEL_SANDBOX) {
			return;
		}

		if (!message.text) {
			return;
		}

		if (message.text && message.text.startsWith('@tashibot')) {
			const reading = hiraganize(
				await getReading(
					message.text.replace(/^@tashibot/, '').replace(englishDictRegex, (english) => englishDict.get(english.toLowerCase()) || english)
				)
			);
			await slack.chat.postMessage({
				channel: process.env.CHANNEL_SANDBOX,
				text: reading,
				username: 'tashibot',
				icon_emoji: ':japan:',
			});
			return;
		}

		if (message.text.slice(-20).match(/^[\x00-\x7F]+$/)) {
			return;
		}

		if (message.username === 'tashibot') {
			return;
		}

		const text = message.text.replace(englishDictRegex, (english) => englishDict.get(english.toLowerCase()) || english).slice(-20);
		const reading = await getReading(text);

		const matches = katakanize(text).match(citiesRegex) || reading.match(citiesRegex);

		if (matches === null) {
			return;
		}

		const city = citiesMap.get(matches[1]);

		if (histories.filter((history) => history.cityName === city.name && history.date >= Date.now() - 10 * 1000).length >= 3) {
			await slack.reactions.add({name: 'bomb', channel: message.channel, timestamp: message.timestamp});
			return;
		}

		histories.push({cityName: city.name, date: Date.now()});
		const placeText = city.type === 'city' ? `${city.name},${city.prefecture}` : `${city.name},${city.description}`;
		const imageUrl = `https://maps.googleapis.com/maps/api/staticmap?${qs.encode({
			center: placeText,
			zoom: city.type === 'city' ? 9 : 15,
			scale: 1,
			size: '600x300',
			maptype: 'roadmap',
			key: process.env.GOOGLEMAP_TOKEN,
			format: 'png',
			visual_refresh: true,
			markers: `size:mid|color:0xfb724a|label:|${placeText}`,
		})}`;

		let cloudinaryData = await storage.getItem(imageUrl);

		if (!cloudinaryData) {
			const imageData = await download(imageUrl);
			cloudinaryData = await new Promise((resolve, reject) => {
				cloudinary.v2.uploader
					.upload_stream({resource_type: 'image'}, (error, data) => {
						if (error) {
							reject(error);
						} else {
							resolve(data);
						}
					})
					.end(imageData);
			});
			await storage.setItem(imageUrl, cloudinaryData);
		}

		const response = (() => {
			if (city.type === 'city') {
				const yearText = city.year === null ? '' : `(${city.year}年消滅)`;
				return `${city.prefecture}${city.name} ${yearText}`;
			}

			const descriptionText =
				city.description || city.year
					? `(${[...(city.description ? [city.description] : []), ...(city.year ? [city.year] : [])].join('、')})`
					: '';
			return `${city.name} ${descriptionText}`;
		})().trim();

		await slack.chat.postMessage({
			channel: process.env.CHANNEL_SANDBOX,
			text: response,
			username: 'tashibot',
			icon_emoji: ':japan:',
			attachments: [
				{
					image_url: cloudinaryData.secure_url,
					fallback: response,
				},
			],
		});
	});
};
<|endoftext|>


<commit_before>'strict';

var app = angular.module('pemTask', ['ui.bootstrap','submission-manager','fioi-editor2']);

// 'cpp', 'cpp11', 'python', 'python2', 'python3', 'ocaml', 'javascool', 'c', 'java', 'pascal', 'shell'
app.service('Languages', function () {
   this.sourceLanguages = [
      {id: 'c', label: "C", ext: 'c', ace: {mode: 'c_cpp'}},
      {id: 'cpp', label: "C++", ext: 'cpp', ace: {mode: 'c_cpp'}},
      {id: 'pascal', label: "Pascal", ext: 'pas', ace: {mode: 'pascal'}},
      {id: 'ocaml', label: "OCaml", ext: 'ml', ace: {mode: 'ocaml'}},
      {id: 'java', label: "Java", ext: 'java', ace: {mode: 'java'}},
      {id: 'javascool', label: "JavaScool", ext: 'jvs', ace: {mode: 'java'}},
      {id: 'python2', label: "Python", ext: 'py', ace: {mode: 'python'}}
   ];
});

app.run(['FioiEditor2Tabsets', 'Languages', function (tabsets, Languages) {
   var sampleCode = "#include \"lib.h\"\nconst int LARGEUR_MAX = 1000000;\nint destinationBille[LARGEUR_MAX+1];\nint main()\n{\n  for(int iPos = nbMarches() - 2; iPos >= 0; --iPos)\n  {\n    if(hauteur(iPos) < hauteur(iPos+1))\n      destinationBille[iPos] = iPos;\n    else\n      destinationBille[iPos] = destinationBille[iPos+1];\n  }\n  for(int iBille = 0; iBille < nbLancers(); ++iBille)\n  {\n    int posBille = marcheLancer(iBille);\n    positionFinale(destinationBille[posBille]);\n  }\n  return 0;\n}";
   var sources = tabsets.add('sources', {mode: 'sources', languages: Languages.sourceLanguages, titlePrefix: 'Code'});
   var code1 = sources.addTab({title: 'Code1', language: 'cpp'});
   var buffer = code1.addBuffer(sampleCode);
}]);

app.controller('taskController', ['$scope', '$http', function($scope, $http) {
   ModelsManager.init(models);
   SyncQueue.init(ModelsManager);
   SyncQueue.params.action = 'getAll';
   SyncQueue.params.sToken = sToken;
   SyncQueue.params.sPlatform = decodeURIComponent(sPlatform);

   task.reloadAnswer = function(strAnswer, callback) {
      $scope.$apply(function() {
         if (!strAnswer) {
            // empty string is default answer in the API, so I guess this means
            // no submission...
            $scope.submission = null;
         } else {
            $scope.submission = ModelsManager.curData.tm_submissions[strAnswer];
         }
         $scope.curSubmission = strAnswer;
         callback();
      });
   }

   $scope.submitAnswer = function() {
      // TODO: collect sources files from the 'sources' tabset and send them to saveAnswer.php?
      this.submission = {ID: 0, bEvaluated: false, tests: [], submissionSubtasks: []};
      $http.post('saveAnswer.php', {sToken: sToken, sPlatform: SyncQueue.params.sPlatform}, {responseType: 'json'}).success(function(postRes) {
         if (!postRes || !postRes.bSuccess) {
            console.error('error calling saveAnswer.php'+(postRes ? ': '+postRes.sError : ''));
            return;
         }
         $scope.curSubmission = postRes.sAnswer;
         $http.post('grader/gradeTask.php', {sToken: sToken, sPlatform: SyncQueue.params.sPlatform, sAnswer: postRes.sAnswer}, {responseType: 'json'}).success(function(postRes) {
            if (!postRes || !postRes.bSuccess) {
               console.error('error calling grader/gradeTask.php'+(postRes ? ': '+postRes.sError : ''));
               return;
            }
         });
      });
   }

   updateSubmissionFromSync = function(submission) {
      if (submission.ID == $scope.curSubmission) {
         $scope.$apply(function() {
            $scope.submission = submission;
         });
      }
   }

   SyncQueue.sync();
   setInterval(SyncQueue.planToSend, 5000);

   function expandSourceCodeParams(sourceCode) {
      if (sourceCode.sParams && typeof sourceCode.sParams == 'string') {
         try {
            sourceCode.sParams = $.parseJSON(sourceCode.sParams);
         } catch(e) {
            console.error('couldn\'t parse '+sourceCode.sParams);
         }
      }
   }

   ModelsManager.addListener('tm_source_codes', "inserted", 'TaskController', expandSourceCodeParams);
   ModelsManager.addListener('tm_source_codes', "updated", 'TaskController', expandSourceCodeParams);
   ModelsManager.addListener('tm_submissions', "inserted", 'TaskController', updateSubmissionFromSync);
   ModelsManager.addListener('tm_submissions', "updated", 'TaskController', updateSubmissionFromSync);

}]);
<commit_msg>send code to saveAnswer.php<commit_after>'strict';

var app = angular.module('pemTask', ['ui.bootstrap','submission-manager','fioi-editor2']);

// 'cpp', 'cpp11', 'python', 'python2', 'python3', 'ocaml', 'javascool', 'c', 'java', 'pascal', 'shell'
app.service('Languages', function () {
   this.sourceLanguages = [
      {id: 'c', label: "C", ext: 'c', ace: {mode: 'c_cpp'}},
      {id: 'cpp', label: "C++", ext: 'cpp', ace: {mode: 'c_cpp'}},
      {id: 'pascal', label: "Pascal", ext: 'pas', ace: {mode: 'pascal'}},
      {id: 'ocaml', label: "OCaml", ext: 'ml', ace: {mode: 'ocaml'}},
      {id: 'java', label: "Java", ext: 'java', ace: {mode: 'java'}},
      {id: 'javascool', label: "JavaScool", ext: 'jvs', ace: {mode: 'java'}},
      {id: 'python2', label: "Python", ext: 'py', ace: {mode: 'python'}}
   ];
});

app.run(['FioiEditor2Tabsets', 'Languages', function (tabsets, Languages) {
   var sampleCode = "#include \"lib.h\"\nconst int LARGEUR_MAX = 1000000;\nint destinationBille[LARGEUR_MAX+1];\nint main()\n{\n  for(int iPos = nbMarches() - 2; iPos >= 0; --iPos)\n  {\n    if(hauteur(iPos) < hauteur(iPos+1))\n      destinationBille[iPos] = iPos;\n    else\n      destinationBille[iPos] = destinationBille[iPos+1];\n  }\n  for(int iBille = 0; iBille < nbLancers(); ++iBille)\n  {\n    int posBille = marcheLancer(iBille);\n    positionFinale(destinationBille[posBille]);\n  }\n  return 0;\n}";
   var sources = tabsets.add('sources', {mode: 'sources', languages: Languages.sourceLanguages, titlePrefix: 'Code'});
   var code1 = sources.addTab({title: 'Code1', language: 'cpp'});
   var buffer = code1.addBuffer(sampleCode);
}]);

app.controller('taskController', ['$scope', '$http', 'FioiEditor2Tabsets', function($scope, $http, tabsets) {
   ModelsManager.init(models);
   SyncQueue.init(ModelsManager);
   SyncQueue.params.action = 'getAll';
   SyncQueue.params.sToken = sToken;
   SyncQueue.params.sPlatform = decodeURIComponent(sPlatform);

   task.reloadAnswer = function(strAnswer, callback) {
      $scope.$apply(function() {
         if (!strAnswer) {
            // empty string is default answer in the API, so I guess this means
            // no submission...
            $scope.submission = null;
         } else {
            $scope.submission = ModelsManager.curData.tm_submissions[strAnswer];
         }
         $scope.curSubmission = strAnswer;
         callback();
      });
   }

   $scope.submitAnswer = function() {
      // TODO: collect sources files from the 'sources' tabset and send them to saveAnswer.php?
      this.submission = {ID: 0, bEvaluated: false, tests: [], submissionSubtasks: []};
      var buffer = tabsets.get('sources').getActiveTab().getBuffer();
      var params = {
         sToken: sToken,
         sPlatform: SyncQueue.params.sPlatform,
         oAnswer: {
            sSourceCode: buffer.text,
            sLangProg: buffer.language
         }
      }
      $http.post('saveAnswer.php', params, {responseType: 'json'}).success(function(postRes) {
         if (!postRes || !postRes.bSuccess) {
            console.error('error calling saveAnswer.php'+(postRes ? ': '+postRes.sError : ''));
            return;
         }
         $scope.curSubmission = postRes.sAnswer;
         $http.post('grader/gradeTask.php', {sToken: sToken, sPlatform: SyncQueue.params.sPlatform, sAnswer: postRes.sAnswer}, {responseType: 'json'}).success(function(postRes) {
            if (!postRes || !postRes.bSuccess) {
               console.error('error calling grader/gradeTask.php'+(postRes ? ': '+postRes.sError : ''));
               return;
            }
         });
      });
   }

   updateSubmissionFromSync = function(submission) {
      if (submission.ID == $scope.curSubmission) {
         $scope.$apply(function() {
            $scope.submission = submission;
         });
      }
   }

   SyncQueue.sync();
   setInterval(SyncQueue.planToSend, 5000);

   function expandSourceCodeParams(sourceCode) {
      if (sourceCode.sParams && typeof sourceCode.sParams == 'string') {
         try {
            sourceCode.sParams = $.parseJSON(sourceCode.sParams);
         } catch(e) {
            console.error('couldn\'t parse '+sourceCode.sParams);
         }
      }
   }

   ModelsManager.addListener('tm_source_codes', "inserted", 'TaskController', expandSourceCodeParams);
   ModelsManager.addListener('tm_source_codes', "updated", 'TaskController', expandSourceCodeParams);
   ModelsManager.addListener('tm_submissions', "inserted", 'TaskController', updateSubmissionFromSync);
   ModelsManager.addListener('tm_submissions', "updated", 'TaskController', updateSubmissionFromSync);

}]);
<|endoftext|>


<commit_before>(function (global) {
  System.config({
    paths: {
      'npm:': 'assets/lib/'
      'app':  'components/'
    },
    map: {
      app: 'assets',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      'rxjs':                       'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    packages: {
      app: {
        main: './boot.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
<commit_msg>Update systemjs.config.js<commit_after>(function (global) {
  System.config({
    paths: {
      'npm:': 'assets/lib/'
      'components':  'components/'
    },
    map: {
      app: 'assets',
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      'rxjs':                       'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
    },
    packages: {
      app: {
        main: './boot.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
<|endoftext|>


<commit_before>/**
 * The Audio Component
 *
 * @module aui-audio
 */

var AObject = A.Object,
	Lang = A.Lang,
	UA = A.UA,
	DOC = A.config.doc,

	NAME = 'audio',

	getClassName = A.getClassName,

	CSS_AUDIO = getClassName(NAME),
	CSS_AUDIO_NODE = getClassName(NAME, 'node'),

	DEFAULT_PLAYER_PATH = A.config.base + 'aui-audio/assets/player.swf',
	FIXED_ATTRIBUTES = 'fixedAttributes',
	FLASH_VARS = 'flashVars',
	MP3 = 'mp3',
	OGG_URL = 'oggUrl',
	SRC = 'src',
	SWF_URL = 'swfUrl',
	URL = 'url',

	REGEX_FILE_EXTENSION = /\.([^\.]+)$/;

/**
 * A base class for Audio.
 *
 * Check the [live demo](http://alloyui.com/examples/audio/).
 *
 * @class A.Audio
 * @extends A.Component
 * @param config {Object} Object literal specifying widget configuration properties.
 * @constructor
 */
var Audio = A.Component.create(
	{
		/**
		 * Static property provides a string to identify the class.
		 *
		 * @property Audio.NAME
		 * @type String
		 * @static
		 */
		NAME: NAME,

		/**
		 * Static property used to define the default attribute
		 * configuration for the Audio.
		 *
		 * @property Audio.ATTRS
		 * @type Object
		 * @static
		 */
		ATTRS: {

			/**
			 * URL used by Audio to play.
			 *
			 * @attribute url
			 * @default ''
			 * @type String
			 */
			url: {
				value: '',
				validator: Lang.isString
			},

			/**
			 * URL (on .ogg format) used by Audio to play.
			 *
			 * @attribute oggUrl
			 * @default ''
			 * @type String
			 */
			oggUrl: {
				value: '',
				validator: Lang.isString
			},

			/**
			 * The type of audio.
			 *
			 * @attribute type
			 * @default mp3
			 * @type String
			 */
			type: {
				value: MP3,
				validator: Lang.isString
			},

			/**
			 * The width of Audio's fallback using Flash.
			 *
			 * @attribute swfWidth
			 * @default 100%
			 * @type String
			 */
			swfWidth: {
				value: '100%',
				validator: Lang.isString
			},

			/**
			 * The height of Audio's fallback using Flash.
			 *
			 * @attribute swfHeight
			 * @default 30
			 * @type String
			 */
			swfHeight: {
				value: '30',
				validator: Lang.isString
			},

			/**
			 * URL (on .swf format) used by Audio to create
			 * a fallback player with Flash.
			 *
			 * @attribute swfUrl
			 * @default aui-audio/assets/player.swf
			 * @type String
			 */
			swfUrl: {
				value: DEFAULT_PLAYER_PATH,
				validator: Lang.isString
			},

			/**
			 * An additional list of attributes.
			 *
			 * @attribute fixedAttributes
			 * @default {}
			 * @type Object
			 */
			fixedAttributes: {
				value: {},
				validator: Lang.isObject
			},

			/**
			 * Variables used by Flash player.
			 *
			 * @attribute flashVars
			 * @default {}
			 * @type Object
			 */
			flashVars: {
				value: {},
				validator: Lang.isObject
			},

			/**
			 * If true the render phase will be automatically invoked
			 * preventing the .render() manual call.
			 *
			 * @attribute render
			 * @default true
			 * @type Boolean
			 */
			render: {
				value: true,
				validator: Lang.isBoolean
			}
		},

		/**
		 * Static property used to define the attributes
		 * for the bindUI lifecycle phase.
		 *
		 * @property Audio.BIND_UI_ATTRS
		 * @type Array
		 * @static
		 */
		BIND_UI_ATTRS: [URL, OGG_URL, SWF_URL, FIXED_ATTRIBUTES, FLASH_VARS],

		/**
		 * Static property used to define the attributes
		 * for the syncUI lifecycle phase.
		 *
		 * @property Audio.SYNC_UI_ATTRS
		 * @type Array
		 * @static
		 */
		SYNC_UI_ATTRS: [URL, OGG_URL],

		prototype: {

			/**
			 * Render the Audio component instance. Lifecycle.
			 *
			 * @method renderUI
			 * @protected
			 */
			renderUI: function () {
				var instance = this;

				instance._renderAudioTask = A.debounce(instance._renderAudio, 1, instance);
				instance._renderSwfTask = A.debounce(instance._renderSwf, 1, instance);

				instance._renderAudio(!instance.get(OGG_URL));
			},

			/**
			 * Bind the events on the Audio UI. Lifecycle.
			 *
			 * @method bindUI
			 * @protected
			 */
			bindUI: function () {
				var instance = this;

				instance.publish(
					'audioReady',
					{
						fireOnce: true
					}
				);
			},

			/**
			 * Load audio track.
			 *
			 * @method load
			 */
			load: function () {
				var instance = this;

                if (instance._audio.hasMethod('load')) {
                    instance._audio.load();
                }
			},

			/**
			 * Pause audio track.
			 *
			 * @method pause
			 */
			pause: function () {
				var instance = this;

                if (instance._audio.hasMethod('pause')) {
                    instance._audio.pause();
                }
			},

			/**
			 * Play audio track.
			 *
			 * @method play
			 */
			play: function () {
				var instance = this;

				if (instance._audio.hasMethod('play')) {
					instance._audio.play();
				}
			},

			/**
			 * Create source element
			 * using passed type attribute.
			 *
			 * @method _createSource
			 * @param type
			 * @protected
			 */
			_createSource: function(type) {
				var sourceNode = new A.Node(DOC.createElement('source'));

				sourceNode.attr('type', type);

				return sourceNode;
			},

			/**
			 * Render SWF in DOM.
			 *
			 * @method _renderSwf
			 * @protected
			 */
			_renderSwf: function () {
				var instance = this;

				var swfUrl = instance.get(SWF_URL);

				if (swfUrl) {
					var flashVars = instance.get(FLASH_VARS);

					instance._setMedia(flashVars);

					var flashVarString = A.QueryString.stringify(flashVars);

					if (instance._swfId) {
						instance._audio.removeChild(A.one('#' + instance._swfId));
					}
					else {
						instance._swfId = A.guid();
					}

					var applicationType = 'type="application/x-shockwave-flash" data="' + swfUrl + '"';

					var movie = '';

					if (UA.ie) {
						applicationType = 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';

						movie = '<param name="movie" value="' + swfUrl + '"/>';
					}

					var fixedAttributes = instance.get(FIXED_ATTRIBUTES);

					var fixedAttributesParam = [];

					for (var attributeName in fixedAttributes) {
						if (AObject.owns(fixedAttributes, attributeName)) {
							fixedAttributesParam.push('<param name="', attributeName, '" value="', fixedAttributes[attributeName], '" />');
						}
					}

					var flashVarsParam = '';

					if (flashVarString) {
						flashVarsParam = '<param name="flashVars" value="' + flashVarString + '" />';
					}

					var height = instance.get('swfHeight');

					var width = instance.get('swfWidth');

					var tplObj = Lang.sub(
						Audio.TPL_FLASH,
						{
							applicationType: applicationType,
							id: instance._swfId,
							fixedAttributes: fixedAttributesParam.join(''),
							flashVars: flashVarsParam,
							height: height,
							movie: movie,
							width: width
						}
					);

					instance._audio.append(tplObj);
				}
			},

			/**
			 * Render Audio in DOM.
			 *
			 * @method _renderAudio
			 * @param fallback
			 * @protected
			 */
			_renderAudio: function(fallback) {
				var instance = this;

				var tpl = Audio.TPL_AUDIO;

				if (UA.gecko && fallback) {
					tpl = Audio.TPL_AUDIO_FALLBACK;
				}

				var tplObj = Lang.sub(tpl, [A.guid()]);

				var audio = A.Node.create(tplObj);

				instance.get('contentBox').append(audio);

				instance._audio = audio;

				return audio;
			},

			/**
			 * Set media on flashVars.
			 *
			 * @method _setMedia
			 * @param flashVars
			 * @protected
			 */
			_setMedia: function(flashVars) {
				var instance = this;

				if (!AObject.owns(flashVars, MP3) && !AObject.owns(flashVars, 'mp4') && !AObject.owns(flashVars, 'flv')) {
					var audioUrl = instance.get(URL);

					var type = instance.get('type');

					if (!type) {
						var typeMatch = REGEX_FILE_EXTENSION.exec(audioUrl);

						if (typeMatch) {
							type = typeMatch[1];
						}
					}

					flashVars[type] = audioUrl;
				}
			},

			/**
			 * Set the fixedAttributes on the UI.
			 *
			 * @method _uiSetFixedAttributes
			 * @param val
			 * @protected
			 */
			_uiSetFixedAttributes: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the flashVars on the UI.
			 *
			 * @method _uiSetFlashVars
			 * @param val
			 * @protected
			 */
			_uiSetFlashVars: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the oggUrl on the UI.
			 *
			 * @method _uiSetOggUrl
			 * @param val
			 * @protected
			 */
			_uiSetOggUrl: function (val) {
				var instance = this;

				if (UA.gecko || UA.opera) {
					var audio = instance._audio;

					var usingAudio = instance._usingAudio();

					if ((!val && usingAudio) || (val && !usingAudio)) {
						audio.remove(true);

						audio = instance._renderAudio(!val);
					}

					if (!val) {
						instance._renderSwfTask();
					}
					else {
						var sourceOgg = instance._sourceOgg;

						if (!sourceOgg) {
							sourceOgg = instance._createSource('audio/ogg');

							audio.append(sourceOgg);

							instance._sourceOgg = sourceOgg;
						}

						sourceOgg.attr(SRC, val);
					}
				}
			},

			/**
			 * Set the swfUrl on the UI.
			 *
			 * @method _uiSetSwfUrl
			 * @param val
			 * @protected
			 */
			_uiSetSwfUrl: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the url on the UI.
			 *
			 * @method _uiSetUrl
			 * @param val
			 * @protected
			 */
			_uiSetUrl: function (val) {
				var instance = this;

				var oggUrl = instance.get(OGG_URL);
				var audio = instance._audio;

				var sourceMp3 = instance._sourceMp3;

				if (UA.gecko && !instance._usingAudio()) {
					if (sourceMp3 != null) {
						sourceMp3.remove(true);

						instance._sourceMp3 = null;
					}
				}
				else
				{
					if (audio || !oggUrl) {
						if (!sourceMp3) {
							sourceMp3 = instance._createSource('audio/mp3');

							audio.append(sourceMp3);

							instance._sourceMp3 = sourceMp3;
						}

						sourceMp3.attr(SRC, val);
					}
				}

				instance._renderSwfTask();
			},

			/**
			 * Check if it's a video node.
			 *
			 * @method _usingVideo
			 * @protected
			 */
			_usingAudio: function() {
				var instance = this;

				return (instance._audio.get('nodeName').toLowerCase() == 'audio');
			}
		}
	}
);

Audio.TPL_AUDIO = '<audio id="{0}" controls class="' + CSS_AUDIO_NODE + '"></audio>';

Audio.TPL_AUDIO_FALLBACK = '

';

Audio.TPL_FLASH = '<object id="{id}" {applicationType} height="{height}" width="{width}">{movie}{fixedAttributes}{flashVars}</object>';

A.Audio = Audio;<commit_msg>Linting<commit_after>/**
 * The Audio Component
 *
 * @module aui-audio
 */

var AObject = A.Object,
	Lang = A.Lang,
	UA = A.UA,
	DOC = A.config.doc,

	NAME = 'audio',

	getClassName = A.getClassName,

	CSS_AUDIO_NODE = getClassName(NAME, 'node'),

	DEFAULT_PLAYER_PATH = A.config.base + 'aui-audio/assets/player.swf',
	FIXED_ATTRIBUTES = 'fixedAttributes',
	FLASH_VARS = 'flashVars',
	MP3 = 'mp3',
	OGG_URL = 'oggUrl',
	SRC = 'src',
	SWF_URL = 'swfUrl',
	URL = 'url',

	REGEX_FILE_EXTENSION = /\.([^\.]+)$/;

/**
 * A base class for Audio.
 *
 * Check the [live demo](http://alloyui.com/examples/audio/).
 *
 * @class A.Audio
 * @extends A.Component
 * @param config {Object} Object literal specifying widget configuration properties.
 * @constructor
 */
var AudioImpl = A.Component.create(
	{
		/**
		 * Static property provides a string to identify the class.
		 *
		 * @property Audio.NAME
		 * @type String
		 * @static
		 */
		NAME: NAME,

		/**
		 * Static property used to define the default attribute
		 * configuration for the Audio.
		 *
		 * @property Audio.ATTRS
		 * @type Object
		 * @static
		 */
		ATTRS: {

			/**
			 * URL used by Audio to play.
			 *
			 * @attribute url
			 * @default ''
			 * @type String
			 */
			url: {
				value: '',
				validator: Lang.isString
			},

			/**
			 * URL (on .ogg format) used by Audio to play.
			 *
			 * @attribute oggUrl
			 * @default ''
			 * @type String
			 */
			oggUrl: {
				value: '',
				validator: Lang.isString
			},

			/**
			 * The type of audio.
			 *
			 * @attribute type
			 * @default mp3
			 * @type String
			 */
			type: {
				value: MP3,
				validator: Lang.isString
			},

			/**
			 * The width of Audio's fallback using Flash.
			 *
			 * @attribute swfWidth
			 * @default 100%
			 * @type String
			 */
			swfWidth: {
				value: '100%',
				validator: Lang.isString
			},

			/**
			 * The height of Audio's fallback using Flash.
			 *
			 * @attribute swfHeight
			 * @default 30
			 * @type String
			 */
			swfHeight: {
				value: '30',
				validator: Lang.isString
			},

			/**
			 * URL (on .swf format) used by Audio to create
			 * a fallback player with Flash.
			 *
			 * @attribute swfUrl
			 * @default aui-audio/assets/player.swf
			 * @type String
			 */
			swfUrl: {
				value: DEFAULT_PLAYER_PATH,
				validator: Lang.isString
			},

			/**
			 * An additional list of attributes.
			 *
			 * @attribute fixedAttributes
			 * @default {}
			 * @type Object
			 */
			fixedAttributes: {
				value: {},
				validator: Lang.isObject
			},

			/**
			 * Variables used by Flash player.
			 *
			 * @attribute flashVars
			 * @default {}
			 * @type Object
			 */
			flashVars: {
				value: {},
				validator: Lang.isObject
			},

			/**
			 * If true the render phase will be automatically invoked
			 * preventing the .render() manual call.
			 *
			 * @attribute render
			 * @default true
			 * @type Boolean
			 */
			render: {
				value: true,
				validator: Lang.isBoolean
			}
		},

		/**
		 * Static property used to define the attributes
		 * for the bindUI lifecycle phase.
		 *
		 * @property Audio.BIND_UI_ATTRS
		 * @type Array
		 * @static
		 */
		BIND_UI_ATTRS: [URL, OGG_URL, SWF_URL, FIXED_ATTRIBUTES, FLASH_VARS],

		/**
		 * Static property used to define the attributes
		 * for the syncUI lifecycle phase.
		 *
		 * @property Audio.SYNC_UI_ATTRS
		 * @type Array
		 * @static
		 */
		SYNC_UI_ATTRS: [URL, OGG_URL],

		prototype: {

			/**
			 * Render the Audio component instance. Lifecycle.
			 *
			 * @method renderUI
			 * @protected
			 */
			renderUI: function () {
				var instance = this;

				instance._renderAudioTask = A.debounce(instance._renderAudio, 1, instance);
				instance._renderSwfTask = A.debounce(instance._renderSwf, 1, instance);

				instance._renderAudio(!instance.get(OGG_URL));
			},

			/**
			 * Bind the events on the Audio UI. Lifecycle.
			 *
			 * @method bindUI
			 * @protected
			 */
			bindUI: function () {
				var instance = this;

				instance.publish(
					'audioReady',
					{
						fireOnce: true
					}
				);
			},

			/**
			 * Load audio track.
			 *
			 * @method load
			 */
			load: function () {
				var instance = this;

                if (instance._audio.hasMethod('load')) {
                    instance._audio.load();
                }
			},

			/**
			 * Pause audio track.
			 *
			 * @method pause
			 */
			pause: function () {
				var instance = this;

                if (instance._audio.hasMethod('pause')) {
                    instance._audio.pause();
                }
			},

			/**
			 * Play audio track.
			 *
			 * @method play
			 */
			play: function () {
				var instance = this;

				if (instance._audio.hasMethod('play')) {
					instance._audio.play();
				}
			},

			/**
			 * Create source element
			 * using passed type attribute.
			 *
			 * @method _createSource
			 * @param type
			 * @protected
			 */
			_createSource: function(type) {
				var sourceNode = new A.Node(DOC.createElement('source'));

				sourceNode.attr('type', type);

				return sourceNode;
			},

			/**
			 * Render SWF in DOM.
			 *
			 * @method _renderSwf
			 * @protected
			 */
			_renderSwf: function () {
				var instance = this;

				var swfUrl = instance.get(SWF_URL);

				if (swfUrl) {
					var flashVars = instance.get(FLASH_VARS);

					instance._setMedia(flashVars);

					var flashVarString = A.QueryString.stringify(flashVars);

					if (instance._swfId) {
						instance._audio.removeChild(A.one('#' + instance._swfId));
					}
					else {
						instance._swfId = A.guid();
					}

					var applicationType = 'type="application/x-shockwave-flash" data="' + swfUrl + '"';

					var movie = '';

					if (UA.ie) {
						applicationType = 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';

						movie = '<param name="movie" value="' + swfUrl + '"/>';
					}

					var fixedAttributes = instance.get(FIXED_ATTRIBUTES);

					var fixedAttributesParam = [];

					for (var attributeName in fixedAttributes) {
						if (AObject.owns(fixedAttributes, attributeName)) {
							fixedAttributesParam.push('<param name="', attributeName, '" value="', fixedAttributes[attributeName], '" />');
						}
					}

					var flashVarsParam = '';

					if (flashVarString) {
						flashVarsParam = '<param name="flashVars" value="' + flashVarString + '" />';
					}

					var height = instance.get('swfHeight');

					var width = instance.get('swfWidth');

					var tplObj = Lang.sub(
						AudioImpl.TPL_FLASH,
						{
							applicationType: applicationType,
							id: instance._swfId,
							fixedAttributes: fixedAttributesParam.join(''),
							flashVars: flashVarsParam,
							height: height,
							movie: movie,
							width: width
						}
					);

					instance._audio.append(tplObj);
				}
			},

			/**
			 * Render Audio in DOM.
			 *
			 * @method _renderAudio
			 * @param fallback
			 * @protected
			 */
			_renderAudio: function(fallback) {
				var instance = this;

				var tpl = Audio.TPL_AUDIO;

				if (UA.gecko && fallback) {
					tpl = Audio.TPL_AUDIO_FALLBACK;
				}

				var tplObj = Lang.sub(tpl, [A.guid()]);

				var audio = A.Node.create(tplObj);

				instance.get('contentBox').append(audio);

				instance._audio = audio;

				return audio;
			},

			/**
			 * Set media on flashVars.
			 *
			 * @method _setMedia
			 * @param flashVars
			 * @protected
			 */
			_setMedia: function(flashVars) {
				var instance = this;

				if (!AObject.owns(flashVars, MP3) && !AObject.owns(flashVars, 'mp4') && !AObject.owns(flashVars, 'flv')) {
					var audioUrl = instance.get(URL);

					var type = instance.get('type');

					if (!type) {
						var typeMatch = REGEX_FILE_EXTENSION.exec(audioUrl);

						if (typeMatch) {
							type = typeMatch[1];
						}
					}

					flashVars[type] = audioUrl;
				}
			},

			/**
			 * Set the fixedAttributes on the UI.
			 *
			 * @method _uiSetFixedAttributes
			 * @param val
			 * @protected
			 */
			_uiSetFixedAttributes: function() {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the flashVars on the UI.
			 *
			 * @method _uiSetFlashVars
			 * @param val
			 * @protected
			 */
			_uiSetFlashVars: function() {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the oggUrl on the UI.
			 *
			 * @method _uiSetOggUrl
			 * @param val
			 * @protected
			 */
			_uiSetOggUrl: function (val) {
				var instance = this;

				if (UA.gecko || UA.opera) {
					var audio = instance._audio;

					var usingAudio = instance._usingAudio();

					if ((!val && usingAudio) || (val && !usingAudio)) {
						audio.remove(true);

						audio = instance._renderAudio(!val);
					}

					if (!val) {
						instance._renderSwfTask();
					}
					else {
						var sourceOgg = instance._sourceOgg;

						if (!sourceOgg) {
							sourceOgg = instance._createSource('audio/ogg');

							audio.append(sourceOgg);

							instance._sourceOgg = sourceOgg;
						}

						sourceOgg.attr(SRC, val);
					}
				}
			},

			/**
			 * Set the swfUrl on the UI.
			 *
			 * @method _uiSetSwfUrl
			 * @param val
			 * @protected
			 */
			_uiSetSwfUrl: function() {
				var instance = this;

				instance._renderSwfTask();
			},

			/**
			 * Set the url on the UI.
			 *
			 * @method _uiSetUrl
			 * @param val
			 * @protected
			 */
			_uiSetUrl: function (val) {
				var instance = this;

				var oggUrl = instance.get(OGG_URL);
				var audio = instance._audio;

				var sourceMp3 = instance._sourceMp3;

				if (UA.gecko && !instance._usingAudio()) {
					if (sourceMp3 !== null) {
						sourceMp3.remove(true);

						instance._sourceMp3 = null;
					}
				}
				else
				{
					if (audio || !oggUrl) {
						if (!sourceMp3) {
							sourceMp3 = instance._createSource('audio/mp3');

							audio.append(sourceMp3);

							instance._sourceMp3 = sourceMp3;
						}

						sourceMp3.attr(SRC, val);
					}
				}

				instance._renderSwfTask();
			},

			/**
			 * Check if it's a video node.
			 *
			 * @method _usingVideo
			 * @protected
			 */
			_usingAudio: function() {
				var instance = this;

				return (instance._audio.get('nodeName').toLowerCase() === 'audio');
			}
		}
	}
);

AudioImpl.TPL_AUDIO = '<audio id="{0}" controls class="' + CSS_AUDIO_NODE + '"></audio>';

AudioImpl.TPL_AUDIO_FALLBACK = '

';

AudioImpl.TPL_FLASH = '<object id="{id}" {applicationType} height="{height}" width="{width}">{movie}{fixedAttributes}{flashVars}</object>';

A.Audio = AudioImpl;<|endoftext|>


<commit_before>import { combine, combineArray, merge } from 'most'
import makeDrawEnclosure from './drawCommands/drawEnclosure'
import drawStaticMesh from './drawCommands/drawStaticMesh2/index'

export function makeVisualState (regl, machine$, entities$, camState$) {
  const machineWithVisuals$ = machine$
    .map(function (machine) {
      if (machine !== undefined) {
        const draw = makeDrawEnclosure(regl, machine.params)
        return Object.assign({}, machine, {draw})
      }
    })

  const entitiesWithVisuals$ = entities$
    .map(function (entities) {
      return entities
        .map(function (data) {
          const geometry = data.geometry
          const draw = drawStaticMesh(regl, {geometry: geometry}) // one command per mesh, but is faster
          const visuals = Object.assign({}, data.visuals, {draw})
          const entity = Object.assign({}, data, {visuals}) // Object.assign({}, data, {visuals: {draw}})
          return entity
        })
    })

  const outOfBoundsColor = [0.15, 0.15, 0.15, 0.3]
  const background = [1, 1, 1, 1]
  return combineArray(
    function (entities, machine, camera) {
      const view = camera.view
      return {entities, machine, view, camera, background, outOfBoundsColor}
    }, [entitiesWithVisuals$, machineWithVisuals$, camState$])
}
<commit_msg>feat(visualstate): added other error color candidate<commit_after>import { combine, combineArray, merge } from 'most'
import makeDrawEnclosure from './drawCommands/drawEnclosure'
import drawStaticMesh from './drawCommands/drawStaticMesh2/index'

export function makeVisualState (regl, machine$, entities$, camState$) {
  const machineWithVisuals$ = machine$
    .map(function (machine) {
      if (machine !== undefined) {
        const draw = makeDrawEnclosure(regl, machine.params)
        return Object.assign({}, machine, {draw})
      }
    })

  const entitiesWithVisuals$ = entities$
    .map(function (entities) {
      return entities
        .map(function (data) {
          const geometry = data.geometry
          const draw = drawStaticMesh(regl, {geometry: geometry}) // one command per mesh, but is faster
          const visuals = Object.assign({}, data.visuals, {draw})
          const entity = Object.assign({}, data, {visuals}) // Object.assign({}, data, {visuals: {draw}})
          return entity
        })
    })

  //const outOfBoundsColor = [1., 0.6, 0.16, 1. ]//(red: 255, green: 140, blue: 16
  const outOfBoundsColor = [0.15, 0.15, 0.15, 0.3]
  const background = [1, 1, 1, 1]
  return combineArray(
    function (entities, machine, camera) {
      const view = camera.view
      return {entities, machine, view, camera, background, outOfBoundsColor}
    }, [entitiesWithVisuals$, machineWithVisuals$, camState$])
}
<|endoftext|>


<commit_before>// Encoding specification:
// http://www.barcodeisland.com/codabar.phtml

import Barcode from "../Barcode.js";

class codabar extends Barcode{
	constructor(data, options){
		if (data.search(/^[0-9\-\$\:\.\+\/]+$/) === 0) {
			data = "A" + data + "A";
		}

		super(data.toUpperCase(), options);

		this.text = this.options.text || this.text.replace(/[A-D]/g, '');
	}

	valid(){
		return this.data.search(/^[A-D][0-9\-\$\:\.\+\/]+[A-D]$/) !== -1;
	}

	encode(){
		var result = [];
		var encodings = this.getEncodings();
		for(var i = 0; i < this.data.length; i++){
			result.push(encodings[this.data.charAt(i)]);
			// for all characters except the last, append a narrow-space ("0")
			if (i !== this.data.length - 1) {
				result.push("0");
			}
		}
		return {
			text: this.text,
			data: result.join('')
		};
	}

	getEncodings(){
		return {
			"0": "101010011",
			"1": "101011001",
			"2": "101001011",
			"3": "110010101",
			"4": "101101001",
			"5": "110101001",
			"6": "100101011",
			"7": "100101101",
			"8": "100110101",
			"9": "110100101",
			"-": "101001101",
			"$": "101100101",
			":": "1101011011",
			"/": "1101101011",
			".": "1101101101",
			"+": "101100110011",
			"A": "1011001001",
			"B": "1001001011",
			"C": "1010010011",
			"D": "1010011001"
		};
	}
}

export {codabar};
<commit_msg>Bug fix:  '+' issue<commit_after>// Encoding specification:
// http://www.barcodeisland.com/codabar.phtml

import Barcode from "../Barcode.js";

class codabar extends Barcode{
	constructor(data, options){
		if (data.search(/^[0-9\-\$\:\.\+\/]+$/) === 0) {
			data = "A" + data + "A";
		}

		super(data.toUpperCase(), options);

		this.text = this.options.text || this.text.replace(/[A-D]/g, '');
	}

	valid(){
		return this.data.search(/^[A-D][0-9\-\$\:\.\+\/]+[A-D]$/) !== -1;
	}

	encode(){
		var result = [];
		var encodings = this.getEncodings();
		for(var i = 0; i < this.data.length; i++){
			result.push(encodings[this.data.charAt(i)]);
			// for all characters except the last, append a narrow-space ("0")
			if (i !== this.data.length - 1) {
				result.push("0");
			}
		}
		return {
			text: this.text,
			data: result.join('')
		};
	}

	getEncodings(){
		return {
			"0": "101010011",
			"1": "101011001",
			"2": "101001011",
			"3": "110010101",
			"4": "101101001",
			"5": "110101001",
			"6": "100101011",
			"7": "100101101",
			"8": "100110101",
			"9": "110100101",
			"-": "101001101",
			"$": "101100101",
			":": "1101011011",
			"/": "1101101011",
			".": "1101101101",
			"+": "1011011011",
			"A": "1011001001",
			"B": "1001001011",
			"C": "1010010011",
			"D": "1010011001"
		};
	}
}

export {codabar};
<|endoftext|>


<commit_before>document.getElementById("submit_button").addEventListener("click", ajax, false);

function ajax() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("qrcode_image").src = URL.createObjectURL(this.response);
        }
    };

    xhr.open("POST", "ajax");
    xhr.responseType = "blob";

    var text = document.getElementById("input_text").value;
    xhr.send(text);
    location.hash = text;
}
<commit_msg>upd separate ajax function<commit_after>document.getElementById("submit_button").addEventListener("click", submit, false);

function submit() {
    var text = document.getElementById("input_text").value;
    ajax(text);
    location.hash = text;
}

function ajax(text) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("qrcode_image").src = URL.createObjectURL(this.response);
        }
    };

    xhr.open("POST", "ajax");
    xhr.responseType = "blob";
    xhr.send(text);
}
<|endoftext|>


<commit_before>require.config({
	baseUrl: 'js/',
	paths: {
		jquery: 'libs/jquery/jquery',
		lodash: 'libs/lodash/lodash',
		backbone: 'libs/backbone/backbone',
		text: 'libs/require/text',
		joint: 'libs/jointjs/joint',
		material: 'libs/mdl/material',
		jqueryui: 'libs/jqueryui/jquery-ui',
		jstree: 'libs/jquery/jstree',
        'svg-pan-zoom': 'libs/svgpanzoom/svg-pan-zoom'
	},
	shim: {
		'material': {
			exports: 'componentHandler'
		}
	},
	map: {
		'*': {
			'underscore': 'lodash'
		}
	}
});

require([
	'backbone',
	'joint',
	'views/AppView',
	'models/newcellfactory',
	'models/ProjectModel',
	'models/Command'
], function (backbone, joint, AppView, NewCellFactory, ProjectModel, Command) {

	//  subroutines:
	//  ============

	var assert = function (condition, message) {
		if (!condition)
			throw 'Non vale che "' + message + '"';
	};

	var objectHasFields = function (obj, fields) {
		ks = Object.keys(obj);
		for (var el of fields) {
			if (!ks.includes(el))
				return false;
		}
		return true;
	};

	// test di unità:
	// ==============

	var app_view = new AppView; // AppView
	assert(app_view instanceof backbone.View, 'Una AppView è una backbone.View.');

	var views = app_view.views;
	assert(views != undefined, 'Una AppView possiede un oggetto views.');

	var pview = views.project; // ProjectView
	assert(pview instanceof backbone.View, 'Una ProjectView è una backbone.View.');

	pview.renderActivity(); assert(true, 'Una ProjectView è in grado di disegnare un diagramma di attività.');

	assert(pview.paper instanceof joint.dia.Paper, 'Una ProjectView possiede un joint.dia.Paper.');

	var dview = views.details; // DetailsView
	assert(dview instanceof backbone.View, 'Una DetailsView è una backbone.View.');

	dview.render(); assert(true, 'Una DetailsView è in grado di disegnare il riquadro dei dettagli.');

	var ncview = views.newCell; // NewCellView
	assert(ncview instanceof backbone.View, 'Una NewCellView è una backbone.View.');

	ncview.render(); assert(true, 'Una NewCellView è in grado di disegnare il riquadro di creazione.');

	var pmodel = ProjectModel; // ProjectModel
	assert(pmodel instanceof backbone.Model, 'Un ProjectModel è un backbone.Model.');

	pmodel.newProject(); assert(true, 'Un ProjectModel è in grado di creare un nuovo progetto.');

	var ncmodel = ncview.model; // NewCellModel
	assert(ncmodel instanceof backbone.Model, 'Un NewCellModel è un backbone.Model.');

	var ncfactory = NewCellFactory; // NewCellFactory

	assert(ncfactory.getCell('HxClass').defaults.type == 'class.HxClass', 'Una NewCellFactory è in grado di istanziare una HxClass.');
	assert(ncfactory.getCell('HxInterface').defaults.type == 'class.HxInterface', 'Una NewCellFactory è in grado di istanziare una HxInterface.');
	assert(ncfactory.getCell('HxComment').defaults.type == 'class.HxComment', 'Una NewCellFactory è in grado di istanziare un HxComment.');
	assert(ncfactory.getCell('HxGeneralization').defaults.type == 'class.HxGeneralization', 'Una NewCellFactory è in grado di istanziare una HxGeneralization.');
	assert(ncfactory.getCell('HxAssociation').defaults.type == 'class.HxAssociation', 'Una NewCellFactory è in grado di istanziare una HxAssociation.');
	assert(ncfactory.getCell('HxImplementation').defaults.type == 'class.HxImplementation', 'Una NewCellFactory è in grado di istanziare una HxImplementation.');
	assert(ncfactory.getCell('HxCustom').defaults.type == 'activity.HxCustom', 'Una NewCellFactory è in grado di istanziare un HxCustom.');
	assert(ncfactory.getCell('HxElse').defaults.type == 'activity.HxElse', 'Una NewCellFactory è in grado di istanziare un HxElse.');
	assert(ncfactory.getCell('HxFor').defaults.type == 'activity.HxFor', 'Una NewCellFactory è in grado di istanziare un HxFor.');
	assert(ncfactory.getCell('HxIf').defaults.type == 'activity.HxIf', 'Una NewCellFactory è in grado di istanziare un HxIf.');
	assert(ncfactory.getCell('HxVariable').defaults.type == 'activity.HxVariable', 'Una NewCellFactory è in grado di istanziare una HxVariable.');
	assert(ncfactory.getCell('HxReturn').defaults.type == 'activity.HxReturn', 'Una NewCellFactory è in grado di istanziare un HxReturn.');
	assert(ncfactory.getCell('HxWhile').defaults.type == 'activity.HxWhile', 'Una NewCellFactory è in grado di istanziare un HxWhile.');

	var cmd = Command; // Command

	cmd.newProject({}); assert(true, 'Un Command è in grado di creare un nuovo progetto.');

	// ClassDiagramElement

	assert(objectHasFields(ncfactory.getCell('HxClass').getValues(), ['name', 'abstract', 'static', 'attributes', 'methods']), 'Una HxClass possiede nome, attributi, metodi, astrazione e staticità.');
	assert(objectHasFields(ncfactory.getCell('HxInterface').getValues(), ['name', 'methods']), 'Una HxInterface possiede nome e metodi.');
	assert(objectHasFields(ncfactory.getCell('HxComment').getValues(), ['comment']), 'Un HxComment possiede un campo di testo.');

	// ClassDiagramLink

	assert(ncfactory.getCell('HxGeneralization').defaults.type != undefined, 'Un HxGeneralization possiede un meta-tipo.');
	assert(ncfactory.getCell('HxAssociation').defaults.type != undefined, 'Un HxAssociation possiede un meta-tipo.');
	assert(ncfactory.getCell('HxImplementation').defaults.type != undefined, 'Un HxImplementation possiede un meta-tipo.');

	// ActivityDiagramElement

	assert(objectHasFields(ncfactory.getCell('HxCustom').getValues(), ['xType', 'comment', 'code']), 'Un HxCustom possiede meta-tipo, commento e una stringa.');
	assert(objectHasFields(ncfactory.getCell('HxElse').getValues(), ['xType', 'comment']), 'Un HxElse possiede meta-tipo e commento.');
	assert(objectHasFields(ncfactory.getCell('HxFor').getValues(), ['xType', 'comment', 'initialization', 'termination', 'increment']), 'Un HxFor possiede meta-tipo, commento, inizializzazione, terminazione e incremento.');
	assert(objectHasFields(ncfactory.getCell('HxIf').getValues(), ['xType', 'comment', 'condition']), 'Un HxIf possiede meta-tipo, commento e condizione.');
	assert(objectHasFields(ncfactory.getCell('HxVariable').getValues(), ['xType', 'comment', 'name', 'type', 'operation', 'value']), 'Una HxVariable possiede meta-tipo, commento, nome, tipo, operazione e valore.');
	assert(objectHasFields(ncfactory.getCell('HxReturn').getValues(), ['xType', 'comment', 'value']), 'Un HxReturn possiede meta-tipo, commento e valore.');
	assert(objectHasFields(ncfactory.getCell('HxWhile').getValues(), ['xType', 'comment', 'condition']), 'Un HxWhile possiede meta-tipo, commento e condizione.');

	// test di integrazione:
	// =====================

	app_view.newProject();
	app_view.save();
	app_view.generate();

	assert(true, 'Le componenti dei package models e views di swedesigner::client interagiscono correttamente tra loro e con la libreria esterna JointJS.');
});
<commit_msg>test integr. client<commit_after>require.config({
	baseUrl: 'js/',
	paths: {
		jquery: 'libs/jquery/jquery',
		lodash: 'libs/lodash/lodash',
		backbone: 'libs/backbone/backbone',
		text: 'libs/require/text',
		joint: 'libs/jointjs/joint',
		material: 'libs/mdl/material',
		jqueryui: 'libs/jqueryui/jquery-ui',
		jstree: 'libs/jquery/jstree',
        'svg-pan-zoom': 'libs/svgpanzoom/svg-pan-zoom'
	},
	shim: {
		'material': {
			exports: 'componentHandler'
		}
	},
	map: {
		'*': {
			'underscore': 'lodash'
		}
	}
});

require([
	'backbone',
	'joint',
	'views/AppView',
	'models/newcellfactory',
	'models/ProjectModel',
	'models/Command'
], function (backbone, joint, AppView, NewCellFactory, ProjectModel, Command) {

	//  subroutines:
	//  ============

	var assert = function (condition, message) {
		if (!condition)
			throw 'Non vale che "' + message + '"';
	};

	var objectHasFields = function (obj, fields) {
		ks = Object.keys(obj);
		for (var el of fields) {
			if (!ks.includes(el))
				return false;
		}
		return true;
	};

	// test di unità:
	// ==============

	var app_view = new AppView; // AppView
	assert(app_view instanceof backbone.View, 'Una AppView è una backbone.View.');

	var views = app_view.views;
	assert(views != undefined, 'Una AppView possiede un oggetto views.');

	var pview = views.project; // ProjectView
	assert(pview instanceof backbone.View, 'Una ProjectView è una backbone.View.');

	pview.renderActivity(); assert(true, 'Una ProjectView è in grado di disegnare un diagramma di attività.');

	assert(pview.paper instanceof joint.dia.Paper, 'Una ProjectView possiede un joint.dia.Paper.');

	var dview = views.details; // DetailsView
	assert(dview instanceof backbone.View, 'Una DetailsView è una backbone.View.');

	dview.render(); assert(true, 'Una DetailsView è in grado di disegnare il riquadro dei dettagli.');

	var ncview = views.newCell; // NewCellView
	assert(ncview instanceof backbone.View, 'Una NewCellView è una backbone.View.');

	ncview.render(); assert(true, 'Una NewCellView è in grado di disegnare il riquadro di creazione.');

	var pmodel = ProjectModel; // ProjectModel
	assert(pmodel instanceof backbone.Model, 'Un ProjectModel è un backbone.Model.');

	pmodel.newProject(); assert(true, 'Un ProjectModel è in grado di creare un nuovo progetto.');

	var ncmodel = ncview.model; // NewCellModel
	assert(ncmodel instanceof backbone.Model, 'Un NewCellModel è un backbone.Model.');

	var ncfactory = NewCellFactory; // NewCellFactory

	assert(ncfactory.getCell('HxClass').defaults.type == 'class.HxClass', 'Una NewCellFactory è in grado di istanziare una HxClass.');
	assert(ncfactory.getCell('HxInterface').defaults.type == 'class.HxInterface', 'Una NewCellFactory è in grado di istanziare una HxInterface.');
	assert(ncfactory.getCell('HxComment').defaults.type == 'class.HxComment', 'Una NewCellFactory è in grado di istanziare un HxComment.');
	assert(ncfactory.getCell('HxGeneralization').defaults.type == 'class.HxGeneralization', 'Una NewCellFactory è in grado di istanziare una HxGeneralization.');
	assert(ncfactory.getCell('HxAssociation').defaults.type == 'class.HxAssociation', 'Una NewCellFactory è in grado di istanziare una HxAssociation.');
	assert(ncfactory.getCell('HxImplementation').defaults.type == 'class.HxImplementation', 'Una NewCellFactory è in grado di istanziare una HxImplementation.');
	assert(ncfactory.getCell('HxCustom').defaults.type == 'activity.HxCustom', 'Una NewCellFactory è in grado di istanziare un HxCustom.');
	assert(ncfactory.getCell('HxElse').defaults.type == 'activity.HxElse', 'Una NewCellFactory è in grado di istanziare un HxElse.');
	assert(ncfactory.getCell('HxFor').defaults.type == 'activity.HxFor', 'Una NewCellFactory è in grado di istanziare un HxFor.');
	assert(ncfactory.getCell('HxIf').defaults.type == 'activity.HxIf', 'Una NewCellFactory è in grado di istanziare un HxIf.');
	assert(ncfactory.getCell('HxVariable').defaults.type == 'activity.HxVariable', 'Una NewCellFactory è in grado di istanziare una HxVariable.');
	assert(ncfactory.getCell('HxReturn').defaults.type == 'activity.HxReturn', 'Una NewCellFactory è in grado di istanziare un HxReturn.');
	assert(ncfactory.getCell('HxWhile').defaults.type == 'activity.HxWhile', 'Una NewCellFactory è in grado di istanziare un HxWhile.');

	var cmd = Command; // Command

	cmd.newProject({}); assert(true, 'Un Command è in grado di creare un nuovo progetto.');

	// ClassDiagramElement

	assert(objectHasFields(ncfactory.getCell('HxClass').getValues(), ['name', 'abstract', 'static', 'attributes', 'methods']), 'Una HxClass possiede nome, attributi, metodi, astrazione e staticità.');
	assert(objectHasFields(ncfactory.getCell('HxInterface').getValues(), ['name', 'methods']), 'Una HxInterface possiede nome e metodi.');
	assert(objectHasFields(ncfactory.getCell('HxComment').getValues(), ['comment']), 'Un HxComment possiede un campo di testo.');

	// ClassDiagramLink

	assert(ncfactory.getCell('HxGeneralization').defaults.type != undefined, 'Un HxGeneralization possiede un meta-tipo.');
	assert(ncfactory.getCell('HxAssociation').defaults.type != undefined, 'Un HxAssociation possiede un meta-tipo.');
	assert(ncfactory.getCell('HxImplementation').defaults.type != undefined, 'Un HxImplementation possiede un meta-tipo.');

	// ActivityDiagramElement

	assert(objectHasFields(ncfactory.getCell('HxCustom').getValues(), ['xType', 'comment', 'code']), 'Un HxCustom possiede meta-tipo, commento e una stringa.');
	assert(objectHasFields(ncfactory.getCell('HxElse').getValues(), ['xType', 'comment']), 'Un HxElse possiede meta-tipo e commento.');
	assert(objectHasFields(ncfactory.getCell('HxFor').getValues(), ['xType', 'comment', 'initialization', 'termination', 'increment']), 'Un HxFor possiede meta-tipo, commento, inizializzazione, terminazione e incremento.');
	assert(objectHasFields(ncfactory.getCell('HxIf').getValues(), ['xType', 'comment', 'condition']), 'Un HxIf possiede meta-tipo, commento e condizione.');
	assert(objectHasFields(ncfactory.getCell('HxVariable').getValues(), ['xType', 'comment', 'name', 'type', 'operation', 'value']), 'Una HxVariable possiede meta-tipo, commento, nome, tipo, operazione e valore.');
	assert(objectHasFields(ncfactory.getCell('HxReturn').getValues(), ['xType', 'comment', 'value']), 'Un HxReturn possiede meta-tipo, commento e valore.');
	assert(objectHasFields(ncfactory.getCell('HxWhile').getValues(), ['xType', 'comment', 'condition']), 'Un HxWhile possiede meta-tipo, commento e condizione.');

	// test di integrazione:
	// =====================

	app_view.newProject();
	app_view.save();
	assert(true, 'Le componenti dei package models e views di swedesigner::client interagiscono correttamente tra loro e con la libreria esterna JointJS.');

	var factoryWorks = ['HxClass', 'HxInterface', 'HxComment', 'HxGeneralization', 'HxAssociation', 'HxImplementation', 'HxCustom', 'HxElse', 'HxFor', 'HxIf', 'HxVariable', 'HxReturn', 'HxWhile'].every(function (element) {
		return ncfactory.getCell(element) != undefined;
	});
	assert(factoryWorks, 'Il sistema gestisce correttamente le componenti relative al package models::celltypes; in particolare, gestisce correttamente l\'interazione con il package views di swedesigner::client e la libreria esterna JointJS.');

	// TODO!
	assert(true, 'Il sistema gestisce correttamente le componenti relative ai package models, views e views::celltypes, oltre che con la libreria esterna JointJS.');
});
<|endoftext|>


<commit_before>import toString from '../utils/string/to_string';
import nilDefault from '../utils/undefined/nil_default';
import getCharWithoutDiacritic from '../utils/string/clear_diacritic';
import { REGEXP_NOT_BASIC_LATIN } from '../utils/regexp';

/**
 * Removes the diacritics from `character`.
 * @param {string} character The character with diacritics.
 * @returns {string} Returns the character without diacritics.
 */
function removeDiacritics(character) {
  var characterWithoutDiacritic = getCharWithoutDiacritic(character);
  return characterWithoutDiacritic ? characterWithoutDiacritic : character;
}

/**
 * Latinises the `subject` by removing diacritic characters.
 *
 * @function latinise
 * @static
 * @memberOf Manipulate
 * @param {string} [subject=''] The string to latinise.
 * @return {string} Returns the latinised string.
 * @example
 * v.latinise('APPLE');
 * // => 'Apple'
 *
 * v.capitalize('mAC', false);
 * // => 'MAC'
 */
export default function(subject) {
  var subjectString = toString(nilDefault(subject, ''));
  if (subjectString === '') {
    return subjectString;
  }
  return subjectString.replace(REGEXP_NOT_BASIC_LATIN, removeDiacritics);
}<commit_msg>Update docs for latinise() function<commit_after>import toString from '../utils/string/to_string';
import nilDefault from '../utils/undefined/nil_default';
import getCharWithoutDiacritic from '../utils/string/clear_diacritic';
import { REGEXP_NOT_BASIC_LATIN } from '../utils/regexp';

/**
 * Removes the diacritics from `character`.
 * @param {string} character The character with diacritics.
 * @returns {string} Returns the character without diacritics.
 */
function removeDiacritics(character) {
  var characterWithoutDiacritic = getCharWithoutDiacritic(character);
  return characterWithoutDiacritic ? characterWithoutDiacritic : character;
}

/**
 * Latinises the `subject` by removing diacritic characters.
 *
 * @function latinise
 * @static
 * @memberOf Manipulate
 * @param {string} [subject=''] The string to latinise.
 * @return {string} Returns the latinised string.
 * @example
 * v.latinise('cafe\u0301'); // or 'café'
 * // => 'cafe'
 */
export default function(subject) {
  var subjectString = toString(nilDefault(subject, ''));
  if (subjectString === '') {
    return subjectString;
  }
  return subjectString.replace(REGEXP_NOT_BASIC_LATIN, removeDiacritics);
}<|endoftext|>