<commit_before>$(function () {
  'use strict';

  function updateDataLayer() {
  }

  function aggregateByLocation() {
    var dataGroupedByLocation, key, locationBin = {}, min = 0, max = 1;
    if (mdata) {
      mdata.forEach(function(item) {
        key = item.field7 + '|' + item.field6;
        if (key in locationBin) {
          locationBin[key].binCount = 1 + locationBin[key].binCount;
          if (locationBin[key].binCount > max) {
            max = locationBin[key].binCount
          }
        } else {
          item.binCount = 1;
          locationBin[key] = item;
          aggData.push(item);
        }
      });
    }

    scale = d3.scale.linear().domain([min, max])
              .range([2, 100]);
  }

  var map = geo.map({
    node: '#map',
    center: {
      x: -98.0,
      y: 39.5
    },
    zoom: 1
  }), locationBin = null, mdata = null, aggData = [], scale = null;

  map.createLayer(
    'osm',
    {
      baseUrl: 'http://c.tile.stamen.com/terrain-labels/'
    }
  );

  $.ajax( "/api/v1/data?limit=1000" )
  .done(function(data) {
    // Cache the data for later
    mdata = data;
    aggregateByLocation();
    console.log(aggData.length);
    map
      .createLayer('feature')
        .createFeature('point')
          .data(aggData)
          .position(function (d) { return { x:d.field7, y:d.field6 } })
          .style('radius', function (d) { return scale(d.binCount); })
          .style('stroke', false)
          .style('fillOpacity', 0.4)
          .style('fillColor', "orange");
    map.draw();
  })
  .fail(function() {
    alert( "error" );
  });

  $("#slider").dateRangeSlider();
});<commit_msg>Set date range accordingly<commit_after>$(function () {
  'use strict';

  function updateDataLayer() {
  }

  function aggregateByLocation() {
    var dataGroupedByLocation, key, locationBin = {}, min = 0, max = 1;
    if (mdata) {
      mdata.forEach(function(item) {
        key = item.field7 + '|' + item.field6;
        if (key in locationBin) {
          locationBin[key].binCount = 1 + locationBin[key].binCount;
          if (locationBin[key].binCount > max) {
            max = locationBin[key].binCount
          }
        } else {
          item.binCount = 1;
          locationBin[key] = item;
          aggData.push(item);
        }
      });
    }

    scale = d3.scale.linear().domain([min, max])
              .range([2, 100]);
  }

  var map = geo.map({
    node: '#map',
    center: {
      x: -98.0,
      y: 39.5
    },
    zoom: 1
  }), locationBin = null, mdata = null, aggData = [], scale = null;

  map.createLayer(
    'osm',
    {
      baseUrl: 'http://c.tile.stamen.com/terrain-labels/'
    }
  );

  $.ajax( "/api/v1/data?limit=1000" )
  .done(function(data) {
    // Cache the data for later
    mdata = data;
    aggregateByLocation();
    console.log(aggData);

    // Compute min and max for time
    var format = d3.time.format("%Y-%m-%d %H:%M:%S");
    var minMax = [d3.min(aggData, function(d) {
        var date = format.parse(d.field4);
        if (date) {
          return date.getTime() / 1000
        }
      }), d3.max(aggData, function(d) {
        var date = format.parse(d.field4);
        if (date) {
          return date.getTime() / 1000
        }
      })];

    // Convert to date object
    console.log(new Date(minMax[0] * 1000).toString());
    console.log(new Date(minMax[1] * 1000).toString());

    // Set the date range
    $("#slider").dateRangeSlider(
      "option",
      "bounds",
      {
        min: new Date(minMax[0] * 1000),
        max: new Date(minMax[1] * 1000)
    });

    map
      .createLayer('feature')
        .createFeature('point')
          .data(aggData)
          .position(function (d) { return { x:d.field7, y:d.field6 } })
          .style('radius', function (d) { return scale(d.binCount); })
          .style('stroke', false)
          .style('fillOpacity', 0.4)
          .style('fillColor', "orange");
    map.draw();
  })
  .fail(function() {
    alert( "error" );
  });

  $("#slider").dateRangeSlider();
});<|endoftext|>


<commit_before>'use strict';

let config;
let Yam = require('yam');
let Project = require('../models/project');

function generateConfig() {
  return new Yam('ember-cli', {
    primary: Project.getProjectRoot(),
  });
}

module.exports = function getConfig(configOverride) {
  if (configOverride) {
    return configOverride;
  }

  if (config === undefined) {
    config = generateConfig();
  }

  return config;
};
<commit_msg>remove config caching<commit_after>'use strict';

let Yam = require('yam');
let Project = require('../models/project');

function generateConfig() {
  return new Yam('ember-cli', {
    primary: Project.getProjectRoot(),
  });
}

module.exports = function getConfig(override) {
  if (override) {
    return override;
  }

  return generateConfig();
};
<|endoftext|>


<commit_before>'use strict';

const CONFIG_VERSION = 2;

// Settings manager docs: https://github.com/airdcpp-web/airdcpp-extension-settings-js
const SettingsManager = require('airdcpp-extension-settings');

const fs = require('fs');
const child_process = require('child_process');
const domain = require('domain');
import triggers from './triggers';

var registered = [];

const parameter = [
	'execution'
];

const scriptSettings = [{
	key: 'script',
	title: 'Script',
	type: 'file_path',
	optional: false,
	default_value: ""
}];

const settingsDef = triggers.map(function (type) {
	return {
		key: type.id,
		title: type.name,
		description: type.description,
		type: 'list',
		item_type: 'struct',
		optional: true,
		default_value: null,
		definitions: type.settings.concat(scriptSettings)
	};
});

function clearRegistered(socket) {
	var item;
	for (item of registered) {
		item.domain.exit();
		item.unregister();
		item.execution.socket.logger.info(`Unregistered: ${item.execution.config.script}`);
	}
	registered = [];
}

const updateRegistered = async function (socket, extension, settings) {
	clearRegistered(socket);
	triggers.map(async function (trigger) {
		var triggerConfigs = settings[trigger.id];
		if (triggerConfigs) {
			var config;
			for (config of triggerConfigs) {
				var functionParameter = parameter.concat(trigger.parameter);
				var script = fs.readFileSync(config.script);
				var scriptFunction = new Function(functionParameter.join(), script);
				var execution = {
					socket,
					config,
					child_process,
					fs,
					trigger
				};
				var d = domain.create();
				d.on('error', handleError.bind(this, execution));
				var callback = d.bind(scriptFunction.bind(this, execution));
				try {
					var item = {
						execution: execution,
						unregister: await trigger.register(socket, config, callback),
						domain: d
					};
					registered.push(item);
				} catch (error) {
					handleError(execution, error);
				}
			}
		}
	});
};

const handleError = function (execution, error) {
	var prefix = `[runscript:${execution.config.script}]`;
	execution.socket.logger.error(`${prefix}${error}`);
	execution.socket.post('events', {
		text: `${prefix}${error.stack}`,
		severity: 'error'
	});
};

// Entry point docs: https://github.com/airdcpp-web/airdcpp-extension-js#extension-entry-structure
module.exports = function (socket, extension) {
	const settingsManager = SettingsManager(socket, {
		extensionName: extension.name,
		configFile: extension.configPath + 'config.json',
		configVersion: CONFIG_VERSION,
		definitions: settingsDef
	});

	settingsManager.onValuesUpdated = updateRegistered.bind(this, socket, extension);

	const migrateConfig = (loadedConfigVersion, loadedData) =>{
		if(loadedConfigVersion < 2){
			var config = {
				"event": [],
				"hook":[]
			};
			var exec;
			for(exec of loadedData.executions){
				var array;
				if(exec.event.indexOf('hooks') > 0){
					config.hook.push({
						"path": exec.event,
						"script": exec.script
					});;
				}else{
					config.event.push({
						"path": exec.event,
						"script": exec.script
					});;
				}
				array
			}
			return config;
		}
	};

	extension.onStart = async (sessionInfo) => {
		await settingsManager.load(migrateConfig);
	};

	extension.onStop = () => {
		clearRegistered(socket);
	};

};<commit_msg>Improve error handling on config change, implement config migration<commit_after>'use strict';

const CONFIG_VERSION = 3;

// Settings manager docs: https://github.com/airdcpp-web/airdcpp-extension-settings-js
const SettingsManager = require('airdcpp-extension-settings');

const fs = require('fs');
const child_process = require('child_process');
const domain = require('domain');
import triggers from './triggers';

var registered = [];

const parameter = [
	'execution'
];

const scriptSettings = [{
	key: 'script',
	title: 'Script',
	type: 'file_path',
	optional: false,
	default_value: ""
}];

const settingsDef = triggers.map(function (type) {
	return {
		key: type.id,
		title: type.name,
		description: type.description,
		type: 'list',
		item_type: 'struct',
		optional: true,
		default_value: null,
		definitions: type.settings.concat(scriptSettings)
	};
});

function clearRegistered(socket) {
	var item;
	for (item of registered) {
		item.domain.exit();
		item.unregister();
		item.execution.socket.logger.info(`Unregistered: ${item.execution.config.script}`);
	}
	registered = [];
}

const updateRegistered = async function (socket, extension, settings) {
	clearRegistered(socket);
	triggers.map(async function (trigger) {
		var triggerConfigs = settings[trigger.id];
		if (triggerConfigs) {
			var config;
			for (config of triggerConfigs) {
				var functionParameter = parameter.concat(trigger.parameter);
				var execution = {
					socket,
					config,
					child_process,
					fs,
					trigger
				};
				var script;
				try{
					script = fs.readFileSync(config.script,"UTF-8");
					var scriptFunction = new Function(functionParameter.join(), script);
					var d = domain.create();
					d.on('error', handleError.bind(this, execution));
					var callback = d.bind(scriptFunction.bind(this, execution));
					var item = {
						execution: execution,
						unregister: await trigger.register(socket, config, callback),
						domain: d
					};
					registered.push(item);
				} catch (error) {
					handleError(execution, error);
				}
			}
		}
	});
};

const handleError = function (execution, error) {
	var prefix = `[runscript:${execution.config.script}]`;
	execution.socket.logger.error(`${prefix}${error}`);
	execution.socket.post('events', {
		text: `${prefix}${error.stack}`,
		severity: 'error'
	});
};

// Entry point docs: https://github.com/airdcpp-web/airdcpp-extension-js#extension-entry-structure
module.exports = function (socket, extension) {
	const settingsManager = SettingsManager(socket, {
		extensionName: extension.name,
		configFile: extension.configPath + 'config.json',
		configVersion: CONFIG_VERSION,
		definitions: settingsDef
	});

	settingsManager.onValuesUpdated = updateRegistered.bind(this, socket, extension);

	const migrateConfig = (loadedConfigVersion, loadedData) =>{
		if(loadedConfigVersion < 2){
			var config = {
				"event": [],
				"hook":[]
			};
			var exec;
			for(exec of loadedData.executions){
				var array;
				if(exec.event.indexOf('hooks') > 0){
					config.hook.push({
						"path": exec.event,
						"script": exec.script
					});;
				}else{
					config.event.push({
						"path": exec.event,
						"script": exec.script
					});;
				}
				array
			}
			return config;
		}else if(loadedConfigVersion < 3){
			triggers.map((trigger) => {
				var index = 0;
				var triggerConfigs = loadedData[trigger.id];
				if (triggerConfigs) {
					var item;
					for (item of triggerConfigs) {
						var scriptFile = `${extension.configPath}${trigger.id}-${index}.js`;
						fs.writeFileSync(scriptFile, item.script);
						item.script = scriptFile;
						socket.post('events', {
							text: `Script ${trigger.id}-${index} saved to ${scriptFile}`,
							severity: 'info'
						});
						index++;
					}
				}
			});
			return loadedData;
		}
	};

	extension.onStart = async (sessionInfo) => {
		await settingsManager.load(migrateConfig);
	};

	extension.onStop = () => {
		clearRegistered(socket);
	};

};<|endoftext|>


<commit_before>import $ from 'jquery'
import ClientSideValidations from './ClientSideValidations'

import { absenceLocalValidator, presenceLocalValidator } from './validators/local/absence_presence'
import { acceptanceLocalValidator } from './validators/local/acceptance'
import { formatLocalValidator } from './validators/local/format'
import { numericalityLocalValidator } from './validators/local/numericality'
import { lengthLocalValidator } from './validators/local/length'
import { exclusionLocalValidator, inclusionLocalValidator } from './validators/local/exclusion_inclusion'
import { confirmationLocalValidator } from './validators/local/confirmation'
import { uniquenessLocalValidator } from './validators/local/uniqueness'

// Validators will run in the following order
ClientSideValidations.validators.local = {
  absence: absenceLocalValidator,
  presence: presenceLocalValidator,
  acceptance: acceptanceLocalValidator,
  format: formatLocalValidator,
  numericality: numericalityLocalValidator,
  length: lengthLocalValidator,
  inclusion: inclusionLocalValidator,
  exclusion: exclusionLocalValidator,
  confirmation: confirmationLocalValidator,
  uniqueness: uniquenessLocalValidator
}

$.fn.disableClientSideValidations = function () {
  ClientSideValidations.disable(this)

  return this
}

$.fn.enableClientSideValidations = function () {
  const selectors = { forms: 'form', inputs: 'input' }

  for (var selector in selectors) {
    const enablers = selectors[selector]

    this.filter(ClientSideValidations.selectors[selector]).each(function () {
      return ClientSideValidations.enablers[enablers](this)
    })
  }

  return this
}

$.fn.resetClientSideValidations = function () {
  this.filter(ClientSideValidations.selectors.forms).each(function () {
    return ClientSideValidations.reset(this)
  })

  return this
}

$.fn.validate = function () {
  this.filter(ClientSideValidations.selectors.forms).each(function () {
    return $(this).enableClientSideValidations()
  })

  return this
}

$.fn.isValid = function (validators) {
  const obj = $(this[0])

  if (obj.is('form')) {
    return validateForm(obj, validators)
  } else {
    return validateElement(obj, validatorsFor(this[0].name, validators))
  }
}

const cleanNestedElementName = (elementName, nestedMatches, validators) => {
  for (const validatorName in validators) {
    if (validatorName.match('\\[' + nestedMatches[1] + '\\].*\\[\\]\\[' + nestedMatches[2] + '\\]$')) {
      elementName = elementName.replace(/\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]')
    }
  }

  return elementName
}

const cleanElementName = (elementName, validators) => {
  elementName = elementName.replace(/\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g, '[$1][]')

  const nestedMatches = elementName.match(/\[(\w+_attributes)\].*\[(\w+)\]$/)

  if (nestedMatches) {
    elementName = cleanNestedElementName(elementName, nestedMatches, validators)
  }

  return elementName
}

const validatorsFor = (elementName, validators) => {
  if (Object.prototype.isPrototypeOf.call(validators, elementName)) {
    return validators[elementName]
  }

  return validators[cleanElementName(elementName, validators)] || {}
}

const validateForm = (form, validators) => {
  let valid = true

  form.trigger('form:validate:before.ClientSideValidations')

  form.find(ClientSideValidations.selectors.validate_inputs).each(function () {
    if (!$(this).isValid(validators)) {
      valid = false
    }

    return true
  })

  if (valid) {
    form.trigger('form:validate:pass.ClientSideValidations')
  } else {
    form.trigger('form:validate:fail.ClientSideValidations')
  }

  form.trigger('form:validate:after.ClientSideValidations')

  return valid
}

const passElement = (element) => {
  element.trigger('element:validate:pass.ClientSideValidations').data('valid', null)
}

const failElement = (element, message) => {
  element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false)
}

const afterValidate = (element) => {
  return element.trigger('element:validate:after.ClientSideValidations').data('valid') !== false
}

const executeValidator = (validatorFunctions, validatorFunction, validatorOptions, element) => {
  for (const validatorOption in validatorOptions) {
    if (!validatorOptions[validatorOption]) {
      continue
    }

    const message = validatorFunction.call(validatorFunctions, element, validatorOptions[validatorOption])

    if (message) {
      failElement(element, message)
      return false
    }
  }

  return true
}

const executeValidators = (validatorFunctions, element, validators) => {
  for (const validator in validators) {
    const validatorFunction = validatorFunctions[validator]

    if (!validatorFunction) {
      continue
    }

    if (!executeValidator(validatorFunctions, validatorFunction, validators[validator], element)) {
      return false
    }
  }

  return true
}

const isMarkedForDestroy = (element) => {
  if (element.attr('name').search(/\[([^\]]*?)\]$/) >= 0) {
    const destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]')

    if ($("input[name='" + destroyInputName + "']").val() === '1') {
      return true
    }
  }

  return false
}

const executeAllValidators = (element, validators) => {
  if (element.data('changed') === false) {
    return
  }

  element.data('changed', false)

  if (executeValidators(ClientSideValidations.validators.all(), element, validators)) {
    passElement(element)
  }
}

const validateElement = (element, validators) => {
  element.trigger('element:validate:before.ClientSideValidations')

  if (isMarkedForDestroy(element)) {
    passElement(element)
  } else {
    executeAllValidators(element, validators)
  }

  return afterValidate(element)
}

if (!window.ClientSideValidations) {
  window.ClientSideValidations = ClientSideValidations

  if (!isAMD() && !isCommonJS()) {
    ClientSideValidations.start()
  }
}

function isAMD () {
  return typeof define === 'function' && define.amd // eslint-disable-line no-undef
}

function isCommonJS () {
  return typeof exports === 'object' && typeof module !== 'undefined' // eslint-disable-line no-undef
}

export default ClientSideValidations
<commit_msg>Refactor executeValidators<commit_after>import $ from 'jquery'
import ClientSideValidations from './ClientSideValidations'

import { absenceLocalValidator, presenceLocalValidator } from './validators/local/absence_presence'
import { acceptanceLocalValidator } from './validators/local/acceptance'
import { formatLocalValidator } from './validators/local/format'
import { numericalityLocalValidator } from './validators/local/numericality'
import { lengthLocalValidator } from './validators/local/length'
import { exclusionLocalValidator, inclusionLocalValidator } from './validators/local/exclusion_inclusion'
import { confirmationLocalValidator } from './validators/local/confirmation'
import { uniquenessLocalValidator } from './validators/local/uniqueness'

// Validators will run in the following order
ClientSideValidations.validators.local = {
  absence: absenceLocalValidator,
  presence: presenceLocalValidator,
  acceptance: acceptanceLocalValidator,
  format: formatLocalValidator,
  numericality: numericalityLocalValidator,
  length: lengthLocalValidator,
  inclusion: inclusionLocalValidator,
  exclusion: exclusionLocalValidator,
  confirmation: confirmationLocalValidator,
  uniqueness: uniquenessLocalValidator
}

$.fn.disableClientSideValidations = function () {
  ClientSideValidations.disable(this)

  return this
}

$.fn.enableClientSideValidations = function () {
  const selectors = { forms: 'form', inputs: 'input' }

  for (var selector in selectors) {
    const enablers = selectors[selector]

    this.filter(ClientSideValidations.selectors[selector]).each(function () {
      return ClientSideValidations.enablers[enablers](this)
    })
  }

  return this
}

$.fn.resetClientSideValidations = function () {
  this.filter(ClientSideValidations.selectors.forms).each(function () {
    return ClientSideValidations.reset(this)
  })

  return this
}

$.fn.validate = function () {
  this.filter(ClientSideValidations.selectors.forms).each(function () {
    return $(this).enableClientSideValidations()
  })

  return this
}

$.fn.isValid = function (validators) {
  const obj = $(this[0])

  if (obj.is('form')) {
    return validateForm(obj, validators)
  } else {
    return validateElement(obj, validatorsFor(this[0].name, validators))
  }
}

const cleanNestedElementName = (elementName, nestedMatches, validators) => {
  for (const validatorName in validators) {
    if (validatorName.match('\\[' + nestedMatches[1] + '\\].*\\[\\]\\[' + nestedMatches[2] + '\\]$')) {
      elementName = elementName.replace(/\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]')
    }
  }

  return elementName
}

const cleanElementName = (elementName, validators) => {
  elementName = elementName.replace(/\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g, '[$1][]')

  const nestedMatches = elementName.match(/\[(\w+_attributes)\].*\[(\w+)\]$/)

  if (nestedMatches) {
    elementName = cleanNestedElementName(elementName, nestedMatches, validators)
  }

  return elementName
}

const validatorsFor = (elementName, validators) => {
  if (Object.prototype.isPrototypeOf.call(validators, elementName)) {
    return validators[elementName]
  }

  return validators[cleanElementName(elementName, validators)] || {}
}

const validateForm = (form, validators) => {
  let valid = true

  form.trigger('form:validate:before.ClientSideValidations')

  form.find(ClientSideValidations.selectors.validate_inputs).each(function () {
    if (!$(this).isValid(validators)) {
      valid = false
    }

    return true
  })

  if (valid) {
    form.trigger('form:validate:pass.ClientSideValidations')
  } else {
    form.trigger('form:validate:fail.ClientSideValidations')
  }

  form.trigger('form:validate:after.ClientSideValidations')

  return valid
}

const passElement = (element) => {
  element.trigger('element:validate:pass.ClientSideValidations').data('valid', null)
}

const failElement = (element, message) => {
  element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false)
}

const afterValidate = (element) => {
  return element.trigger('element:validate:after.ClientSideValidations').data('valid') !== false
}

const executeValidator = (validatorFunctions, validatorFunction, validatorOptions, element) => {
  for (const validatorOption in validatorOptions) {
    if (!validatorOptions[validatorOption]) {
      continue
    }

    const message = validatorFunction.call(validatorFunctions, element, validatorOptions[validatorOption])

    if (message) {
      failElement(element, message)
      return false
    }
  }

  return true
}

const executeValidators = (validatorFunctions, element, validators) => {
  for (const validator in validators) {
    if (!validatorFunctions[validator]) {
      continue
    }

    if (!executeValidator(validatorFunctions, validatorFunctions[validator], validators[validator], element)) {
      return false
    }
  }

  return true
}

const isMarkedForDestroy = (element) => {
  if (element.attr('name').search(/\[([^\]]*?)\]$/) >= 0) {
    const destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]')

    if ($("input[name='" + destroyInputName + "']").val() === '1') {
      return true
    }
  }

  return false
}

const executeAllValidators = (element, validators) => {
  if (element.data('changed') === false) {
    return
  }

  element.data('changed', false)

  if (executeValidators(ClientSideValidations.validators.all(), element, validators)) {
    passElement(element)
  }
}

const validateElement = (element, validators) => {
  element.trigger('element:validate:before.ClientSideValidations')

  if (isMarkedForDestroy(element)) {
    passElement(element)
  } else {
    executeAllValidators(element, validators)
  }

  return afterValidate(element)
}

if (!window.ClientSideValidations) {
  window.ClientSideValidations = ClientSideValidations

  if (!isAMD() && !isCommonJS()) {
    ClientSideValidations.start()
  }
}

function isAMD () {
  return typeof define === 'function' && define.amd // eslint-disable-line no-undef
}

function isCommonJS () {
  return typeof exports === 'object' && typeof module !== 'undefined' // eslint-disable-line no-undef
}

export default ClientSideValidations
<|endoftext|>


<commit_before>/*
 *  main.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//乱数発生器
mt = new MersenneTwister();

//定数
//デバッグフラグ
DEBUG = true;
PHONEGAP = false;

//スクリーンサイズ
SC_W = 640;
SC_H = 960;

//カードサイズ
CARD_W = 200;
CARD_H = 300;
CARD_SCALE = 0.5;

//スート
SUIT_SPADE = 0;
SUIT_CLOVER = 1;
SUIT_DIAMOND = 2;
SUIT_HEART = 3;
SUIT_JOKER = 4;

//シャッフルが発生する残りカード枚数
SHUFFLE_LIMIT = 25;

//ジョーカー使用フラグ
USE_JOKER = true;
RETURN_JOKER = false;   //使用したジョーカーを場に戻すか

//役一覧
MISS = -30;
NOHAND = -20;
ONEPAIR = 10;
TWOPAIR = 20;
FLASH = 30;
THREECARD = 50;
FULLHOUSE = 100;
STRAIGHT = 150;
FOURCARD = 300;
FIVECARD = 400;
STRAIGHTFLASH = 500;
ROYALSTRAIGHTFLASH = 1000;

//フレームレート
fps = 30;

//使用フォント
FONT1 = "'KS-Kohichi-FeltPen'";
FONT2 = "'azuki'";

var toRad = 3.14159/180;    //弧度法toラジアン変換
var toDeg = 180/3.14159;    //ラジアンto弧度法変換
var sec = function(s) { return ~~(fps * s);}    //秒からフレーム数へ変換
var rand = function(min, max) { return mt.nextInt(min, max); };    //乱数発生

//距離計算
var distance = function(from, to) {
    var x = from.x-to.x;
    var y = from.y-to.y;
    return Math.sqrt(x*x+y*y);
}

//距離計算（ルート無し版）
var distanceSq = function(from, to) {
    var x = from.x-to.x;
    var y = from.y - to.y;
    return x*x+y*y;
}

//数値の制限
var clamp = function(x, min, max) {
    return (x<min)?min:((x>max)?max:x);
};

//インスタンス
appMain = {};

//アプリケーションメイン
tm.main(function() {
    appMain = shotgun.CanvasApp("#world");
    appMain.run();
});

document.addEventListener('load', function () {
//    alert('loadイベントが発火しました');
}, false);
document.addEventListener('deviceready', function () {
//    alert('devicereadyイベントが発火しました');
}, false);
document.addEventListener('pause', function() {
//    alert('pauseイベントが発火しました');
//    var scene = appMain.currentScene;
//    if (scene instanceof 'shotgun.MainScene') {
        appMain.pushScene(shotgun.pauseScene());
//    }
}, false);
document.addEventListener('resume', function() {
}, false);

/*
document.addEventListener(‘online’, PENQs.online, false);
document.addEventListener(‘offline’, PENQs.offline, false);
*/<commit_msg>device event<commit_after>/*
 *  main.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//乱数発生器
mt = new MersenneTwister();

//定数
//デバッグフラグ
DEBUG = true;
PHONEGAP = false;

//スクリーンサイズ
SC_W = 640;
SC_H = 960;

//カードサイズ
CARD_W = 200;
CARD_H = 300;
CARD_SCALE = 0.5;

//スート
SUIT_SPADE = 0;
SUIT_CLOVER = 1;
SUIT_DIAMOND = 2;
SUIT_HEART = 3;
SUIT_JOKER = 4;

//シャッフルが発生する残りカード枚数
SHUFFLE_LIMIT = 25;

//ジョーカー使用フラグ
USE_JOKER = true;
RETURN_JOKER = false;   //使用したジョーカーを場に戻すか

//役一覧
MISS = -30;
NOHAND = -20;
ONEPAIR = 10;
TWOPAIR = 20;
FLASH = 30;
THREECARD = 50;
FULLHOUSE = 100;
STRAIGHT = 150;
FOURCARD = 300;
FIVECARD = 400;
STRAIGHTFLASH = 500;
ROYALSTRAIGHTFLASH = 1000;

//フレームレート
fps = 30;

//使用フォント
FONT1 = "'KS-Kohichi-FeltPen'";
FONT2 = "'azuki'";

var toRad = 3.14159/180;    //弧度法toラジアン変換
var toDeg = 180/3.14159;    //ラジアンto弧度法変換
var sec = function(s) { return ~~(fps * s);}    //秒からフレーム数へ変換
var rand = function(min, max) { return mt.nextInt(min, max); };    //乱数発生

//距離計算
var distance = function(from, to) {
    var x = from.x-to.x;
    var y = from.y-to.y;
    return Math.sqrt(x*x+y*y);
}

//距離計算（ルート無し版）
var distanceSq = function(from, to) {
    var x = from.x-to.x;
    var y = from.y - to.y;
    return x*x+y*y;
}

//数値の制限
var clamp = function(x, min, max) {
    return (x<min)?min:((x>max)?max:x);
};

//インスタンス
appMain = {};

//アプリケーションメイン
tm.main(function() {
    appMain = shotgun.CanvasApp("#world");
    appMain.run();
});

//iPhonr device event message
document.addEventListener('load', function () {
//    alert('loadイベントが発火しました');
}, false);
document.addEventListener('deviceready', function () {
//    alert('devicereadyイベントが発火しました');
}, false);
document.addEventListener('pause', function() {
}, false);
document.addEventListener('resume', function() {
    var scene = appMain.currentScene;
    if (scene instanceof shotgun.MainScene) {
//        alert('resumeイベントが発火しました');
        appMain.pushScene(shotgun.PauseScene(scene));
    }
}, false);

/*
document.addEventListener(‘online’, PENQs.online, false);
document.addEventListener(‘offline’, PENQs.offline, false);
*/<|endoftext|>


<commit_before>var passport = require ('passport')
  , isLoggedIn = require ('../middleware/isLoggedIn')
  ;

module.exports = exports = {
    '/dashboard' : {
        use: isLoggedIn,
        get  : { view   : 'dashboard.pug'},
        post : { action : 'DashboardController@init' }
    },

    '/dashboard/messages' : {
        use: isLoggedIn,
        get: { action : 'DashboardController@messages' }
    },

    '/dashboard/compose/send' : {
        use: isLoggedIn,
        get  : { view   : 'dashboard.pug' },
        post : { action : 'DashboardController@send' }
    },

    '/dashboard/contacts' : {
        use: isLoggedIn,
        get: { action : 'DashboardController@contacts' }
    }
};<commit_msg>added userInfo router<commit_after>var passport = require ('passport')
  , isLoggedIn = require ('../middleware/isLoggedIn')
  ;

module.exports = exports = {
    '/dashboard' : {
        use: isLoggedIn,
        get  : { view   : 'dashboard.pug'},
        post : { action : 'DashboardController@init' }
    },

    '/dashboard/messages' : {
        use: isLoggedIn,
        get: { action : 'DashboardController@messages' }
    },

    '/dashboard/compose/send' : {
        use: isLoggedIn,
        get  : { view   : 'dashboard.pug' },
        post : { action : 'DashboardController@send' }
    },

    '/dashboard/contacts' : {
        use: isLoggedIn,
        get: { action : 'DashboardController@contacts' }
    },

    '/dashboard/userInfo' : {
		use: isLoggedIn,
		get: {action : 'DashboardController@userInfo' }
	}
};
<|endoftext|>


<commit_before>(function(DOM, VK_SPACE, VK_TAB, VK_ENTER, VK_ESCAPE, VK_BACKSPACE, VK_DELETE, VK_CONTROL) {
    "use strict";

    var emmet = DOM.emmetLiteral,
        HTML = DOM.get("documentElement"),
        BASE_CLASS = "btr-dateinput-calendar",
        ampm = (pos, neg) => HTML.lang === "en-US" ? pos : neg,
        formatISODate = (value) => value.toISOString().split("T")[0],
        PICKER_TEMPLATE = DOM.create(emmet `div.${BASE_CLASS}>(p.${BASE_CLASS}-header>a[unselectable=on]*2+time[is=local-time data-format='MMMM yyyy' aria-hidden=true unselectable=on].${BASE_CLASS}-caption)`),
        DAYS_TEMPLATE = DOM.create(emmet `table[aria-hidden=true].${BASE_CLASS}-days>(thead>(tr>th[unselectable=on]*7>time[is=local-time data-format=E]))+(tbody.${BASE_CLASS}-body>tr*6>td*7)`),
        MONTHS_TEMPLATE = DOM.create(emmet `table[aria-hidden=true].${BASE_CLASS}-months>tbody>tr*3>td*4>time[is=local-time data-format=MMM])`),
        LABEL_TEMPLATE = DOM.create(emmet `time[is=local-time aria-hidden=true].btr-dateinput-value`),
        readDateRange = (el) => ["min", "max"].map((x) => new Date(el.get(x) || ""));

    MONTHS_TEMPLATE.findAll("time").forEach((time, index) => {
        time.set("datetime", new Date(2001, index, 9).toISOString());
    });

    DAYS_TEMPLATE.findAll("time").forEach((time, index) => {
        time.set("datetime", new Date(ampm(2001, 2002), 0, index).toISOString());
    });

    PICKER_TEMPLATE.append(DAYS_TEMPLATE).append(MONTHS_TEMPLATE);

    DOM.extend("input[type=date]", {
        constructor() {
            if (this._isNative()) return false;

            var defaultValue = this.get("defaultValue"),
                picker = PICKER_TEMPLATE.clone(true),
                label = LABEL_TEMPLATE.clone(true),
                calenderDays = picker.find(`.${BASE_CLASS}-body`),
                calendarMonths = picker.find(`.${BASE_CLASS}-months`),
                calendarCaption = picker.find(`.${BASE_CLASS}-caption`),
                invalidatePicker = this._invalidatePicker.bind(this, calendarCaption, calendarMonths, calenderDays, picker);

            this// hide original input text
                // IE8 doesn't suport color:transparent - use background-color instead
                .css("color", document.addEventListener ? "transparent" : this.css("background-color"))
                // sync picker visibility on focus/blur
                .on(["focus", "click"], this._focusPicker.bind(this, picker))
                .on("blur", this._blurPicker.bind(this, picker))
                .on("change", this._syncValue.bind(this, "value", label))
                .on("keydown", ["which"], this._keydownPicker.bind(this, picker))
                .value(defaultValue); // restore initial value

            label
                .set("data-format", this.get("data-format") || "E, dd MMM yyyy")
                .css(this.css(["width", "font", "padding", "text-align", "border-width", "box-sizing"]))
                .css("line-height", "") // IE10 returns invalid line-height for hidden elements
                .on("click", this._clickLabel.bind(this))
                .watch("datetime", invalidatePicker)
                .set("datetime", defaultValue);

            this
                .before(picker.hide(), label)
                .closest("form").on("reset", this._syncValue.bind(this, "defaultValue", label));

            picker
                .watch("aria-expanded", invalidatePicker)
                .on("mousedown", ["target"], this._clickPicker.bind(this, picker, calendarMonths))
                .css("z-index", 1 + (this.css("z-index") | 0));

            calendarCaption
                .on("click", this._clickPickerCaption.bind(this, picker));

            // display calendar for autofocused elements
            if (this.matches(":focus")) picker.show();
        },
        _isNative() {
            var polyfillType = this.get("data-polyfill"),
                deviceType = "orientation" in window ? "mobile" : "desktop";

            if (polyfillType === "none") return true;

            if (!polyfillType || polyfillType === deviceType && polyfillType !== "all") {
                // use a stronger type support detection that handles old WebKit browsers:
                // http://www.quirksmode.org/blog/archives/2015/03/better_modern_i.html
                if (this[0].type === "date") return true;
                // persist current value to restore it later
                this.set("defaultValue", this.value());
                // if browser allows invalid value then it doesn't support the feature
                return this.value("_").value() !== "_";
            } else {
                // remove native control
                this.set("type", "text");
                // force applying the polyfill
                return false;
            }
        },
        _invalidatePicker(caption, calendarMonths, calenderDays, picker) {
            var expanded = picker.get("aria-expanded") === "true";
            var value = new Date(this.value());
            var year, month, date;

            if (!value.getTime()) {
                value = new Date();
            }

            month = value.getUTCMonth();
            date = value.getUTCDate();
            year = value.getUTCFullYear();

            var range = readDateRange(this);
            var iterDate = new Date(Date.UTC(year, month, 0));

            if (expanded) {
                calendarMonths.findAll("td").forEach((day, index) => {
                    iterDate.setUTCMonth(index);

                    var mDiff = month - iterDate.getUTCMonth(),
                        className = BASE_CLASS;

                    if (iterDate < range[0] || iterDate > range[1]) {
                        className += "-out";
                    } else if (!mDiff) {
                        className += "-today";
                    } else {
                        className = "";
                    }

                    day.set("class", className);
                });
            } else {
                // move to beginning of the first week in current month
                iterDate.setUTCDate(iterDate.getUTCDate() - iterDate.getUTCDay() - ampm(1, 0));
                // update days picker
                calenderDays.findAll("td").forEach((day) => {
                    iterDate.setUTCDate(iterDate.getUTCDate() + 1);

                    var mDiff = month - iterDate.getUTCMonth(),
                        className = BASE_CLASS;

                    if (year !== iterDate.getUTCFullYear()) mDiff *= -1;

                    if (iterDate < range[0] || iterDate > range[1]) {
                        className += "-out";
                    } else if (mDiff > 0) {
                        className += "-past";
                    } else if (mDiff < 0) {
                        className += "-future";
                    } else if (date === iterDate.getUTCDate()) {
                        className += "-today";
                    } else {
                        className = "";
                    }

                    day
                        .set("class", className)
                        .data("ts", iterDate.getTime())
                        .value(iterDate.getUTCDate());
                });
            }

            // update calendar caption
            caption
                .set("data-format", expanded ? "yyyy" : "MMMM yyyy")
                .set("datetime", new Date(year, month).toISOString());
        },
        _syncValue(propName, label) {
            var value = this.get(propName);

            this.value(value);
            label.set("datetime", value);
        },
        _clickPicker(picker, calendarMonths, target) {
            var targetDate;

            if (target.matches("a")) {
                targetDate = new Date(this.value());

                if (!targetDate.getTime()) targetDate = new Date();

                var sign = target.next("a")[0] ? -1 : 1;

                if (picker.get("aria-expanded") === "true") {
                    targetDate.setUTCFullYear(targetDate.getUTCFullYear() + sign);
                } else {
                    targetDate.setUTCMonth(targetDate.getUTCMonth() + sign);
                }
            } else if (calendarMonths.contains(target)) {
                target = target.closest("time");

                targetDate = new Date(this.value());
                targetDate.setUTCMonth(new Date(target.get("datetime")).getUTCMonth());

                picker.hide();
            } else if (target.matches("td")) {
                targetDate = target.data("ts");

                if (targetDate) {
                    targetDate = new Date(targetDate);
                    picker.hide();
                }
            }

            if (targetDate != null) {
                var range = readDateRange(this);

                if (targetDate < range[0]) {
                    targetDate = range[0];
                } else if (targetDate > range[1]) {
                    targetDate = range[1];
                }

                this.value(formatISODate(targetDate)).fire("change");
            }
            // prevent input from loosing focus
            return false;
        },
        _keydownPicker(picker, which) {
            var delta, currentDate;
            // ENTER key should submit form if calendar is hidden
            if (picker.matches(":hidden") && which === VK_ENTER) return true;

            if (which === VK_SPACE) {
                // SPACE key toggles calendar visibility
                picker.set("aria-expanded", "false").toggle();
            } else if (which === VK_ESCAPE || which === VK_TAB || which === VK_ENTER) {
                picker.hide(); // ESC, TAB or ENTER keys hide calendar
            } else if (which === VK_BACKSPACE || which === VK_DELETE) {
                this.value("").fire("change"); // BACKSPACE, DELETE clear value
            } else if (which === VK_CONTROL) {
                // CONTROL toggles calendar mode
                picker.set("aria-expanded",
                    String(picker.get("aria-expanded") !== "true"));
            } else {
                currentDate = new Date(this.value());

                if (!currentDate.getTime()) currentDate = new Date();

                if (which === 74 || which === 40) { delta = 7; }
                else if (which === 75 || which === 38) { delta = -7; }
                else if (which === 76 || which === 39) { delta = 1; }
                else if (which === 72 || which === 37) { delta = -1; }

                if (delta) {
                    var expanded = picker.get("aria-expanded") === "true";

                    if (expanded && (which === 40 || which === 38)) {
                        currentDate.setUTCMonth(currentDate.getUTCMonth() + (delta > 0 ? 4 : -4));
                    } else if (expanded && (which === 37 || which === 39)) {
                        currentDate.setUTCMonth(currentDate.getUTCMonth() + (delta > 0 ? 1 : -1));
                    } else {
                        currentDate.setUTCDate(currentDate.getUTCDate() + delta);
                    }

                    var range = readDateRange(this);

                    if (!(currentDate < range[0] || currentDate > range[1])) {
                        this.value(formatISODate(currentDate)).fire("change");
                    }
                }
            }
            // prevent default action except if it was TAB so
            // do not allow to change the value manually
            return which === VK_TAB;
        },
        _blurPicker(picker) {
            picker.hide();
        },
        _focusPicker(picker) {
            if (this.get("readonly")) return false;

            var offset = this.offset();
            var pickerOffset = picker.offset();
            var marginTop = offset.height;

            // #3: move calendar to the top when passing cross browser window bounds
            if (HTML.clientHeight < offset.bottom + pickerOffset.height) {
                marginTop = -pickerOffset.height;
            }

            picker
                // always recalculate picker top position
                .css("margin-top", marginTop)
                // always reset picker mode to default
                .set("aria-expanded", "false")
                // display the date picker
                .show();

            // use the trick below to reset text selection on focus
            /* istanbul ignore next */
            setTimeout(() => {
                var node = this[0];

                if ("selectionStart" in node) {
                    node.selectionStart = 0;
                    node.selectionEnd = 0;
                } else {
                    var inputRange = node.createTextRange();

                    inputRange.moveStart("character", 0);
                    inputRange.collapse();
                    inputRange.moveEnd("character", 0);
                    inputRange.select();
                }
            }, 0);
        },
        _clickPickerCaption(picker) {
            picker.set("aria-expanded",
                String(picker.get("aria-expanded") !== "true"));
        },
        _clickLabel() {
            this.fire("focus");
        }
    });
}(window.DOM, 32, 9, 13, 27, 8, 46, 17));
<commit_msg>simplify templates<commit_after>(function(DOM, VK_SPACE, VK_TAB, VK_ENTER, VK_ESCAPE, VK_BACKSPACE, VK_DELETE, VK_CONTROL) {
    "use strict";

    var emmet = DOM.emmetLiteral,
        HTML = DOM.get("documentElement"),
        BASE_CLASS = "btr-dateinput-calendar",
        ampm = (pos, neg) => HTML.lang === "en-US" ? pos : neg,
        formatISODate = (value) => value.toISOString().split("T")[0],
        PICKER_TEMPLATE = DOM.create(emmet `div.${BASE_CLASS}>(p.${BASE_CLASS}-header>a[unselectable=on]*2+time[is=local-time data-format='MMMM yyyy' aria-hidden=true unselectable=on].${BASE_CLASS}-caption)`),
        DAYS_TEMPLATE = DOM.create(emmet `table[aria-hidden=true].${BASE_CLASS}-days>(thead>(tr>(th[unselectable=on]>time[is=local-time datetime='${ampm(2001,2002)}-01-$$@6T21:00:00.000Z' data-format=E])*7)+(tbody.${BASE_CLASS}-body>tr*6>td*7))`),
        MONTHS_TEMPLATE = DOM.create(emmet `table[aria-hidden=true].${BASE_CLASS}-months>tbody>tr*3>td*4>time[is=local-time data-format=MMM])`),
        LABEL_TEMPLATE = DOM.create(emmet `time[is=local-time aria-hidden=true].btr-dateinput-value`),
        readDateRange = (el) => ["min", "max"].map((x) => new Date(el.get(x) || ""));

    MONTHS_TEMPLATE.findAll("time").forEach((time, index) => {
        time.set("datetime", new Date(2001, index, 1, 12).toISOString());
    });

    PICKER_TEMPLATE.append(DAYS_TEMPLATE).append(MONTHS_TEMPLATE);

    DOM.extend("input[type=date]", {
        constructor() {
            if (this._isNative()) return false;

            var defaultValue = this.get("defaultValue"),
                picker = PICKER_TEMPLATE.clone(true),
                label = LABEL_TEMPLATE.clone(true),
                calenderDays = picker.find(`.${BASE_CLASS}-body`),
                calendarMonths = picker.find(`.${BASE_CLASS}-months`),
                calendarCaption = picker.find(`.${BASE_CLASS}-caption`),
                invalidatePicker = this._invalidatePicker.bind(this, calendarCaption, calendarMonths, calenderDays, picker);

            this// hide original input text
                // IE8 doesn't suport color:transparent - use background-color instead
                .css("color", document.addEventListener ? "transparent" : this.css("background-color"))
                // sync picker visibility on focus/blur
                .on(["focus", "click"], this._focusPicker.bind(this, picker))
                .on("blur", this._blurPicker.bind(this, picker))
                .on("change", this._syncValue.bind(this, "value", label))
                .on("keydown", ["which"], this._keydownPicker.bind(this, picker))
                .value(defaultValue); // restore initial value

            label
                .set("data-format", this.get("data-format") || "E, dd MMM yyyy")
                .css(this.css(["width", "font", "padding", "text-align", "border-width", "box-sizing"]))
                .css("line-height", "") // IE10 returns invalid line-height for hidden elements
                .on("click", this._clickLabel.bind(this))
                .watch("datetime", invalidatePicker)
                .set("datetime", defaultValue);

            this
                .before(picker.hide(), label)
                .closest("form").on("reset", this._syncValue.bind(this, "defaultValue", label));

            picker
                .watch("aria-expanded", invalidatePicker)
                .on("mousedown", ["target"], this._clickPicker.bind(this, picker, calendarMonths))
                .css("z-index", 1 + (this.css("z-index") | 0));

            calendarCaption
                .on("click", this._clickPickerCaption.bind(this, picker));

            // display calendar for autofocused elements
            if (this.matches(":focus")) picker.show();
        },
        _isNative() {
            var polyfillType = this.get("data-polyfill"),
                deviceType = "orientation" in window ? "mobile" : "desktop";

            if (polyfillType === "none") return true;

            if (!polyfillType || polyfillType === deviceType && polyfillType !== "all") {
                // use a stronger type support detection that handles old WebKit browsers:
                // http://www.quirksmode.org/blog/archives/2015/03/better_modern_i.html
                if (this[0].type === "date") return true;
                // persist current value to restore it later
                this.set("defaultValue", this.value());
                // if browser allows invalid value then it doesn't support the feature
                return this.value("_").value() !== "_";
            } else {
                // remove native control
                this.set("type", "text");
                // force applying the polyfill
                return false;
            }
        },
        _invalidatePicker(caption, calendarMonths, calenderDays, picker) {
            var expanded = picker.get("aria-expanded") === "true";
            var value = new Date(this.value());
            var year, month, date;

            if (!value.getTime()) {
                value = new Date();
            }

            month = value.getUTCMonth();
            date = value.getUTCDate();
            year = value.getUTCFullYear();

            var range = readDateRange(this);
            var iterDate = new Date(Date.UTC(year, month, 0));

            if (expanded) {
                calendarMonths.findAll("td").forEach((day, index) => {
                    iterDate.setUTCMonth(index);

                    var mDiff = month - iterDate.getUTCMonth(),
                        className = BASE_CLASS;

                    if (iterDate < range[0] || iterDate > range[1]) {
                        className += "-out";
                    } else if (!mDiff) {
                        className += "-today";
                    } else {
                        className = "";
                    }

                    day.set("class", className);
                });
            } else {
                // move to beginning of the first week in current month
                iterDate.setUTCDate(iterDate.getUTCDate() - iterDate.getUTCDay() - ampm(1, 0));
                // update days picker
                calenderDays.findAll("td").forEach((day) => {
                    iterDate.setUTCDate(iterDate.getUTCDate() + 1);

                    var mDiff = month - iterDate.getUTCMonth(),
                        className = BASE_CLASS;

                    if (year !== iterDate.getUTCFullYear()) mDiff *= -1;

                    if (iterDate < range[0] || iterDate > range[1]) {
                        className += "-out";
                    } else if (mDiff > 0) {
                        className += "-past";
                    } else if (mDiff < 0) {
                        className += "-future";
                    } else if (date === iterDate.getUTCDate()) {
                        className += "-today";
                    } else {
                        className = "";
                    }

                    day
                        .set("class", className)
                        .data("ts", iterDate.getTime())
                        .value(iterDate.getUTCDate());
                });
            }

            // update calendar caption
            caption
                .set("data-format", expanded ? "yyyy" : "MMMM yyyy")
                .set("datetime", new Date(year, month).toISOString());
        },
        _syncValue(propName, label) {
            var value = this.get(propName);

            this.value(value);
            label.set("datetime", value);
        },
        _clickPicker(picker, calendarMonths, target) {
            var targetDate;

            if (target.matches("a")) {
                targetDate = new Date(this.value());

                if (!targetDate.getTime()) targetDate = new Date();

                var sign = target.next("a")[0] ? -1 : 1;

                if (picker.get("aria-expanded") === "true") {
                    targetDate.setUTCFullYear(targetDate.getUTCFullYear() + sign);
                } else {
                    targetDate.setUTCMonth(targetDate.getUTCMonth() + sign);
                }
            } else if (calendarMonths.contains(target)) {
                target = target.closest("time");

                targetDate = new Date(this.value());
                targetDate.setUTCMonth(new Date(target.get("datetime")).getUTCMonth());

                picker.hide();
            } else if (target.matches("td")) {
                targetDate = target.data("ts");

                if (targetDate) {
                    targetDate = new Date(targetDate);
                    picker.hide();
                }
            }

            if (targetDate != null) {
                var range = readDateRange(this);

                if (targetDate < range[0]) {
                    targetDate = range[0];
                } else if (targetDate > range[1]) {
                    targetDate = range[1];
                }

                this.value(formatISODate(targetDate)).fire("change");
            }
            // prevent input from loosing focus
            return false;
        },
        _keydownPicker(picker, which) {
            var delta, currentDate;
            // ENTER key should submit form if calendar is hidden
            if (picker.matches(":hidden") && which === VK_ENTER) return true;

            if (which === VK_SPACE) {
                // SPACE key toggles calendar visibility
                picker.set("aria-expanded", "false").toggle();
            } else if (which === VK_ESCAPE || which === VK_TAB || which === VK_ENTER) {
                picker.hide(); // ESC, TAB or ENTER keys hide calendar
            } else if (which === VK_BACKSPACE || which === VK_DELETE) {
                this.value("").fire("change"); // BACKSPACE, DELETE clear value
            } else if (which === VK_CONTROL) {
                // CONTROL toggles calendar mode
                picker.set("aria-expanded",
                    String(picker.get("aria-expanded") !== "true"));
            } else {
                currentDate = new Date(this.value());

                if (!currentDate.getTime()) currentDate = new Date();

                if (which === 74 || which === 40) { delta = 7; }
                else if (which === 75 || which === 38) { delta = -7; }
                else if (which === 76 || which === 39) { delta = 1; }
                else if (which === 72 || which === 37) { delta = -1; }

                if (delta) {
                    var expanded = picker.get("aria-expanded") === "true";

                    if (expanded && (which === 40 || which === 38)) {
                        currentDate.setUTCMonth(currentDate.getUTCMonth() + (delta > 0 ? 4 : -4));
                    } else if (expanded && (which === 37 || which === 39)) {
                        currentDate.setUTCMonth(currentDate.getUTCMonth() + (delta > 0 ? 1 : -1));
                    } else {
                        currentDate.setUTCDate(currentDate.getUTCDate() + delta);
                    }

                    var range = readDateRange(this);

                    if (!(currentDate < range[0] || currentDate > range[1])) {
                        this.value(formatISODate(currentDate)).fire("change");
                    }
                }
            }
            // prevent default action except if it was TAB so
            // do not allow to change the value manually
            return which === VK_TAB;
        },
        _blurPicker(picker) {
            picker.hide();
        },
        _focusPicker(picker) {
            if (this.get("readonly")) return false;

            var offset = this.offset();
            var pickerOffset = picker.offset();
            var marginTop = offset.height;

            // #3: move calendar to the top when passing cross browser window bounds
            if (HTML.clientHeight < offset.bottom + pickerOffset.height) {
                marginTop = -pickerOffset.height;
            }

            picker
                // always recalculate picker top position
                .css("margin-top", marginTop)
                // always reset picker mode to default
                .set("aria-expanded", "false")
                // display the date picker
                .show();

            // use the trick below to reset text selection on focus
            /* istanbul ignore next */
            setTimeout(() => {
                var node = this[0];

                if ("selectionStart" in node) {
                    node.selectionStart = 0;
                    node.selectionEnd = 0;
                } else {
                    var inputRange = node.createTextRange();

                    inputRange.moveStart("character", 0);
                    inputRange.collapse();
                    inputRange.moveEnd("character", 0);
                    inputRange.select();
                }
            }, 0);
        },
        _clickPickerCaption(picker) {
            picker.set("aria-expanded",
                String(picker.get("aria-expanded") !== "true"));
        },
        _clickLabel() {
            this.fire("focus");
        }
    });
}(window.DOM, 32, 9, 13, 27, 8, 46, 17));
<|endoftext|>


<commit_before>"use strict";

let Play = require('models/play');

module.exports = function(router) {

    router.get('/edit/:playKey', function(req, res, next) {
        if (!req.play) return next();
        res.render('admin/plays/edit', {
            title: 'Спектакли — ' + req.play.title,
            play: getFormData(req.play, req),
            theatres: req.options.theatres,
            scenes: req.options.scenes,
            plays: req.options.plays,
            backUrl: req.session.playsBackUrl
        });
    });

    router.post('/edit/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.edit(buildEditRequest(req.body), function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль сохранен.');
            res.redirect(req.session.playsBackUrl || '/admin/plays');
        });
    });

    router.delete('/remove/:playKey', function(req, res, next) {
        if (!req.play) return next();
        if (req.play.id !== req.body.id) return next();
        req.play.remove(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» удален.');
            res.end();
        });
    });

    router.post('/hide/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.hide(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» скрыт из всех расписаний.');
            res.end();
        });
    });

    router.post('/unhide/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.unhide(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» больше не скрыт.');
            res.end();
        });
    });

    router.get('/create', function(req, res) {
        res.render('admin/plays/edit', {
            title: 'Спектакли — Новый',
            play: getFormData(new Play, req),
            theatres: req.options.theatres,
            scenes: req.options.scenes,
            backUrl: req.session.playsBackUrl
        });
    });

    router.post('/create', function(req, res, next) {
        let play = new Play();
        play.edit(buildEditRequest(req.body), function(err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль сохранен.');
            res.redirect(req.session.playsBackUrl || '/admin/plays');
        });
    });

    function getFormData(play, req) {
        return req.flash('body')[0] || play.toObject({depopulate: true});
    }
    function buildEditRequest(requestBody) {
        return {
            key: requestBody.key,
            title: requestBody.title,
            theatre: requestBody.theatre,
            scene: requestBody.scene,
            url: requestBody.url,
            director: requestBody.director,
            author: requestBody.author,
            genre: requestBody.genre,
            duration: requestBody.duration,
            description: requestBody.description,
            image: requestBody.image,
            premiere: !!requestBody.premiere,
            musical: !!requestBody.musical,
            dancing: !!requestBody.dancing,
            forKids: !!requestBody['for-kids'],
            opera: !!requestBody.opera,
            ballet: !!requestBody.ballet,
            tags: requestBody.tags.replace(/\r\n/g, "\n").split("\n"),
            mapAs: requestBody['map-as'] || null
        };
    }
};<commit_msg>Add plays options for original play to play create route<commit_after>"use strict";

let Play = require('models/play');

module.exports = function(router) {

    router.get('/edit/:playKey', function(req, res, next) {
        if (!req.play) return next();
        res.render('admin/plays/edit', {
            title: 'Спектакли — ' + req.play.title,
            play: getFormData(req.play, req),
            theatres: req.options.theatres,
            scenes: req.options.scenes,
            plays: req.options.plays,
            backUrl: req.session.playsBackUrl
        });
    });

    router.post('/edit/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.edit(buildEditRequest(req.body), function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль сохранен.');
            res.redirect(req.session.playsBackUrl || '/admin/plays');
        });
    });

    router.get('/create', function(req, res) {
        res.render('admin/plays/edit', {
            title: 'Спектакли — Новый',
            play: getFormData(new Play, req),
            theatres: req.options.theatres,
            scenes: req.options.scenes,
            plays: req.options.plays,
            backUrl: req.session.playsBackUrl
        });
    });

    router.post('/create', function(req, res, next) {
        let play = new Play();
        play.edit(buildEditRequest(req.body), function(err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль сохранен.');
            res.redirect(req.session.playsBackUrl || '/admin/plays');
        });
    });

    router.delete('/remove/:playKey', function(req, res, next) {
        if (!req.play) return next();
        if (req.play.id !== req.body.id) return next();
        req.play.remove(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» удален.');
            res.end();
        });
    });

    router.post('/hide/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.hide(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» скрыт из всех расписаний.');
            res.end();
        });
    });

    router.post('/unhide/:playKey', function(req, res, next) {
        if (!req.play) return next();
        req.play.unhide(function (err) {
            if (err) return next(err);
            req.flash('success', 'Спектакль «' + req.play.title + '» больше не скрыт.');
            res.end();
        });
    });

    function getFormData(play, req) {
        return req.flash('body')[0] || play.toObject({depopulate: true});
    }
    function buildEditRequest(requestBody) {
        return {
            key: requestBody.key,
            title: requestBody.title,
            theatre: requestBody.theatre,
            scene: requestBody.scene,
            url: requestBody.url,
            director: requestBody.director,
            author: requestBody.author,
            genre: requestBody.genre,
            duration: requestBody.duration,
            description: requestBody.description,
            image: requestBody.image,
            premiere: !!requestBody.premiere,
            musical: !!requestBody.musical,
            dancing: !!requestBody.dancing,
            forKids: !!requestBody['for-kids'],
            opera: !!requestBody.opera,
            ballet: !!requestBody.ballet,
            tags: requestBody.tags.replace(/\r\n/g, "\n").split("\n"),
            mapAs: requestBody['map-as'] || null
        };
    }
};<|endoftext|>


<commit_before>const setStyles = (el, styles) => {
  Object.keys(styles).forEach((key) => {
    el.style[key] = styles[key];
  });
};

const setAttrs = (el, attrs) => {
  Object.keys(attrs).forEach((key) => {
    el.setAttribute(key, attrs[key]);
  });
};

const getAttr = (el, attr) => el.getAttribute(attr);

const siiimpleToast = {
  defaultOptions: {
    // container: 'body',
    class: 'siiimpleToast',
    position: 'top|center',
    margin: 15,
    delay: 0,
    duration: 3000,
  },

  setOptions(options = {}) {
    return {
      ...siiimpleToast,
      defaultOptions: {
        ...this.defaultOptions,
        ...options,
      },
    };
  },

  render(state, message, options = {}) {
    const mergedOptions = {
      ...this.defaultOptions,
      ...options,
    };

    const {
      class: className,
      position,
      delay,
      duration,
    } = mergedOptions;

    const newToast = document.createElement('div');

    // logging via attrs
    newToast.className = className;
    newToast.innerHTML = message;

    setAttrs(newToast, {
      'data-position': position,
      'data-state': state,
    });

    // use .setTimeout() instead of $.queue()
    let time = 0;
    setTimeout(() => {
      this.show(newToast, mergedOptions);
    }, time += delay);
    setTimeout(() => {
      this.hide(newToast, mergedOptions);
    }, time += duration);

    // support method chaining
    return siiimpleToast;
  },

  show(el, { class: className, margin }) {
    const hasPos = (v, pos) => getAttr(v, 'data-position').includes(pos);

    const container = document.querySelector('body');
    container.insertBefore(el, container.firstChild);

    // set initial position
    setStyles(el, {
      [hasPos(el, 'top') ? 'top' : 'bottom']: '-100px',
      [hasPos(el, 'left') && 'left']: '15px',
      [hasPos(el, 'center') && 'left']: `${(container.clientWidth / 2) - (el.clientWidth / 2)}px`,
      [hasPos(el, 'right') && 'right']: '15px',
    });

    setStyles(el, {
      transform: 'scale(1)',
      opacity: 1,
    });

    // push effect
    let pushStack = margin;

    Array
      .from(document.querySelectorAll(`.${className}[data-position="${getAttr(el, 'data-position')}"]`))
      .forEach((toast) => {
        setStyles(toast, {
          [hasPos(toast, 'top') ? 'top' : 'bottom']: `${pushStack}px`,
        });

        pushStack += toast.offsetHeight + margin;
      });
  },

  hide(el) {
    const hasPos = (v, pos) => getAttr(v, 'data-position').includes(pos);
    const { left, width } = el.getBoundingClientRect();

    setStyles(el, {
      [hasPos(el, 'left') && 'left']: `${width}px`,
      [hasPos(el, 'center') && 'left']: `${left + width}px`,
      [hasPos(el, 'right') && 'right']: `-${width}px`,
      opacity: 0,
    });

    const whenTransitionEnd = () => {
      this.removeDOM(el);
      el.removeEventListener('transitionend', whenTransitionEnd);
    };

    el.addEventListener('transitionend', whenTransitionEnd);
  },

  removeDOM(el) {// eslint-disable-line
    const parent = el.parentNode;
    parent.removeChild(el);
  },

  message(message, options) {
    return this.render('default', message, options);
  },
  success(message, options) {
    return this.render('success', message, options);
  },
  alert(message, options) {
    return this.render('alert', message, options);
  },
};

export default siiimpleToast;
<commit_msg>Add option 'container' for users who want to add toast in container<commit_after>const setStyles = (el, styles) => {
  Object.keys(styles).forEach((key) => {
    el.style[key] = styles[key];
  });
};

const setAttrs = (el, attrs) => {
  Object.keys(attrs).forEach((key) => {
    el.setAttribute(key, attrs[key]);
  });
};

const getAttr = (el, attr) => el.getAttribute(attr);

const siiimpleToast = {
  defaultOptions: {
    container: 'body',
    class: 'siiimpleToast',
    position: 'top|center',
    margin: 15,
    delay: 0,
    duration: 3000,
  },

  setOptions(options = {}) {
    return {
      ...siiimpleToast,
      defaultOptions: {
        ...this.defaultOptions,
        ...options,
      },
    };
  },

  render(state, message, options = {}) {
    const mergedOptions = {
      ...this.defaultOptions,
      ...options,
    };

    const {
      class: className,
      position,
      delay,
      duration,
    } = mergedOptions;

    const newToast = document.createElement('div');

    // logging via attrs
    newToast.className = className;
    newToast.innerHTML = message;

    setAttrs(newToast, {
      'data-position': position,
      'data-state': state,
    });

    // use .setTimeout() instead of $.queue()
    let time = 0;
    setTimeout(() => {
      this.show(newToast, mergedOptions);
    }, time += delay);
    setTimeout(() => {
      this.hide(newToast, mergedOptions);
    }, time += duration);

    // support method chaining
    return siiimpleToast;
  },

  show(el, { container, class: className, margin }) {
    const hasPos = (v, pos) => getAttr(v, 'data-position').includes(pos);

    const root = document.querySelector(container);
    root.insertBefore(el, root.firstChild);

    // set initial position
    setStyles(el, {
      [hasPos(el, 'top') ? 'top' : 'bottom']: '-100px',
      [hasPos(el, 'left') && 'left']: '15px',
      [hasPos(el, 'center') && 'left']: `${(root.clientWidth / 2) - (el.clientWidth / 2)}px`,
      [hasPos(el, 'right') && 'right']: '15px',
    });

    setStyles(el, {
      transform: 'scale(1)',
      opacity: 1,
    });

    // push effect
    let pushStack = margin;

    Array
      .from(document.querySelectorAll(`.${className}[data-position="${getAttr(el, 'data-position')}"]`))
      .filter(toast => toast.parentElement === el.parentElement)// matching container
      .forEach((toast) => {
        setStyles(toast, {
          [hasPos(toast, 'top') ? 'top' : 'bottom']: `${pushStack}px`,
        });

        pushStack += toast.offsetHeight + margin;
      });
  },

  hide(el) {
    const hasPos = (v, pos) => getAttr(v, 'data-position').includes(pos);
    const { left, width } = el.getBoundingClientRect();

    setStyles(el, {
      [hasPos(el, 'left') && 'left']: `${width}px`,
      [hasPos(el, 'center') && 'left']: `${left + width}px`,
      [hasPos(el, 'right') && 'right']: `-${width}px`,
      opacity: 0,
    });

    const whenTransitionEnd = () => {
      this.removeDOM(el);
      el.removeEventListener('transitionend', whenTransitionEnd);
    };

    el.addEventListener('transitionend', whenTransitionEnd);
  },

  removeDOM(el) {// eslint-disable-line
    const parent = el.parentElement;
    parent.removeChild(el);
  },

  message(message, options) {
    return this.render('default', message, options);
  },
  success(message, options) {
    return this.render('success', message, options);
  },
  alert(message, options) {
    return this.render('alert', message, options);
  },
};

export default siiimpleToast;
<|endoftext|>


<commit_before>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = false;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<commit_msg>this mild weekend the // codex hackathon happened // and we made a thing<commit_after>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = false;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<|endoftext|>