<commit_before>'use strict';

import Promise from 'bluebird'
import fs from 'fs'
import path from 'path'
import _ from 'underscore'
import multer from 'multer';

Promise.promisifyAll(fs)

import CSVParser from './CSVParser'
import ArcJSONParser from './ArcJSONParser'
import GeoJSONParser from './GeoJSONParser'

/**
 * Import file contents as arrays of objects
 *
 * ## Installation
 *
 *    > npm install @nxus/data-loader --save
 *
 * ## Options
 *
 * All responses accept an options argument, in addition to any parser-specific options
 * you can indicate:
 *  * `mapping`: object of {field: newField} name mappings
 *  * `identityFields`: for importing to models, array of fields to be used for createOrUpdate query
 *
 * ## Events
 *
 * You can modify the records during import with the following specific events:
 *  * `records.type`: e.g. `app.get('data-loader').after('records.csv', (results) => {})`
 *  * `record.type`: e.g. `app.get('data-loader).after('record.csv', (one) => {})`
 *  * `models.identity`: e.g. `app.get('data-loader').after('models.user', (results) => {})`
 *  * `model.identity`: e.g. `app.get('data-loader).after('model.user', (user) => {})`
 *
 * record* events occur after parsing and name mapping
 * model* events occur after record events and before models are created/updated.
 *
 * # API
 * -----
 */

export default class DataLoader {
  constructor(app) {
    this.app = app
    this._parsers = {}
    this._exporters = {}
    app.get('data-loader').use(this)
      .gather('parser')
      .gather('exporter')
      .gather('uploadPath')
      .respond('export')
      .respond('import')
      .respond('importFile')
      .respond('importToModel')
      .respond('importFileToModel')

    new CSVParser(app)
    new ArcJSONParser(app)
    new GeoJSONParser(app)

  }

  /**
   * Provide a parser for a particular type (file extension)
   * @param {string} type The type (e.g. 'html') this renderer should handle
   * @param {function} handler Function to receive (content, options) and return parsed array of result objects
   */
  parser(type, handler) {
    this.on('records.'+type, (args) => {return args})
    this.on('record.'+type, (args) => {return args})
    this._parsers[type] = handler
  }
  /**
   * Provide an exporter for a particular type (file extension)
   * @param {string} type The type (e.g. 'html') this exporter creates
   * @param {function} handler Function to receive (content, options) and return formatted output content
   */
  exporter(type, handler) {
    this._exporters[type] = handler
  }

  uploadPath(path, field, dest=process.cwd()+'/uploads/') {
    var upload = multer({dest: dest})
    this.app.get('router').middleware(path, upload.single(field))
  }

  /**
   * Request formattted output based on type
   * @param {string} type The type (e.g. 'html') of the output content
   * @param {[object]} records The records to export
   * @param {object} opts Options for the exporter context
   * @return {Promise} String of formatted output
   */
  export(type, records, opts) {
    if (opts === undefined) opts = {}
    if(!this._exporters[type]) throw new Error('No matching exporter found: '+ type);
    return this._exporters[type](records, opts);
  }

  /**
   * Request parsed results based on type
   * @param {string} type The type (e.g. 'html') of the content
   * @param {string} content The contents to parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of parsed result objects
   */
  import(type, content, opts) {
    if (opts === undefined) opts = {}
    if(!this._parsers[type]) throw new Error('No matching parser found: '+ type);
    let records = Promise.mapSeries(this._mappingNames(this._parsers[type](content, opts), opts), (record) => { return this.emit('record.'+type, record)})
    return this.emit('records.'+type, records)
  }

  /**
   * Request parsed results from a file path
   * @param {string} filename The filename to read and parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of parsed result objects
   */
  importFile(filename, opts) {
    return fs.readFileAsync(filename).then((content) => {
      content = content.toString()
      var type = path.extname(filename).replace(".", "");
      if (opts.type) {
        type = opts.type
      }
      return this.import(type, content, opts)
    })
  }

  /**
   * Import string contents to a model
   * @param {string} model The identity of the model to populate
   * @param {string} type The type (e.g. 'html') of the content
   * @param {string} content The contents to parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of instances
   */
  importToModel(model, type, content, opts) {
    return this.request('import', type, content, opts).then((results) => {
      return this._modelImport(model, results, opts)
    })
  }

  /**
   * Import file contents to a model
   * @param {string} model The identity of the model to populate
   * @param {string} filename The filename to read and parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of instances
   */
  importFileToModel(model, filename, opts) {
    return this.request('importFile', filename, opts).then((results) => {
      return this._modelImport(model, results, opts)
    })
  }

  // Internal

  _modelImport(model_id, results, opts) {
    this.on('models.'+model_id, (args) => {return args})
    this.on('model.'+model_id, (args) => {return args})
    if (opts === undefined) opts = {}
    var identityFields = opts.identityFields || ['id']
    return Promise.mapSeries(results, (record) => { return this.emit('model.'+model_id, record)}).then((records) => {
      return this.emit('models.'+model_id, records).then((results) => {
        return this.app.get('storage').getModel(model_id).then((model) => {
          var model_attrs = _.keys(model._attributes)
          return Promise.map(results, (r) => {
            var values = _.pick(r, ...model_attrs)
            var criteria = _.pick(values, ...identityFields)
            return model.createOrUpdate(criteria, values).catch((e) => {this.app.log.error("Error imporing "+model_id, e)})
          })
        })
      })
    })
  }

  _mappingNames(results, options) {
    var mapping = options.mapping
    if (mapping === undefined || _.isEmpty(mapping)) {
      return results
    }
    var oldNames = _.keys(mapping)
    return _.map(results, (r) => {
      _.mapObject(mapping, (k, v) => {
        r[k] = r[v]
      })
      return _.omit(r, ...oldNames)
    })
  }

}
<commit_msg>Truncate option for model import<commit_after>'use strict';

import Promise from 'bluebird'
import fs from 'fs'
import path from 'path'
import _ from 'underscore'
import multer from 'multer';

Promise.promisifyAll(fs)

import CSVParser from './CSVParser'
import ArcJSONParser from './ArcJSONParser'
import GeoJSONParser from './GeoJSONParser'

/**
 * Import file contents as arrays of objects
 *
 * ## Installation
 *
 *    > npm install @nxus/data-loader --save
 *
 * ## Options
 *
 * All responses accept an options argument, in addition to any parser-specific options
 * you can indicate:
 *  * `mapping`: object of {field: newField} name mappings
 *  * `identityFields`: for importing to models, array of fields to be used for createOrUpdate query
 *  * `truncate`: for importing to models, true/false for deleting existing collection data before import. Ignored if `identityFields` is provided.
 *
 * ## Events
 *
 * You can modify the records during import with the following specific events:
 *  * `records.type`: e.g. `app.get('data-loader').after('records.csv', (results) => {})`
 *  * `record.type`: e.g. `app.get('data-loader).after('record.csv', (one) => {})`
 *  * `models.identity`: e.g. `app.get('data-loader').after('models.user', (results) => {})`
 *  * `model.identity`: e.g. `app.get('data-loader).after('model.user', (user) => {})`
 *
 * record* events occur after parsing and name mapping
 * model* events occur after record events and before models are created/updated.
 *
 * # API
 * -----
 */

const _defaultImportOptions = {
  truncate: true,
  identityFields: []
}

export default class DataLoader {
  constructor(app) {
    this.app = app
    this._parsers = {}
    this._exporters = {}
    app.get('data-loader').use(this)
      .gather('parser')
      .gather('exporter')
      .gather('uploadPath')
      .respond('export')
      .respond('import')
      .respond('importFile')
      .respond('importToModel')
      .respond('importFileToModel')

    new CSVParser(app)
    new ArcJSONParser(app)
    new GeoJSONParser(app)

  }

  /**
   * Provide a parser for a particular type (file extension)
   * @param {string} type The type (e.g. 'html') this renderer should handle
   * @param {function} handler Function to receive (content, options) and return parsed array of result objects
   */
  parser(type, handler) {
    this.on('records.'+type, (args) => {return args})
    this.on('record.'+type, (args) => {return args})
    this._parsers[type] = handler
  }
  /**
   * Provide an exporter for a particular type (file extension)
   * @param {string} type The type (e.g. 'html') this exporter creates
   * @param {function} handler Function to receive (content, options) and return formatted output content
   */
  exporter(type, handler) {
    this._exporters[type] = handler
  }

  uploadPath(path, field, dest=process.cwd()+'/uploads/') {
    var upload = multer({dest: dest})
    this.app.get('router').middleware(path, upload.single(field))
  }

  /**
   * Request formattted output based on type
   * @param {string} type The type (e.g. 'html') of the output content
   * @param {[object]} records The records to export
   * @param {object} opts Options for the exporter context
   * @return {Promise} String of formatted output
   */
  export(type, records, opts) {
    if (opts === undefined) opts = {}
    if(!this._exporters[type]) throw new Error('No matching exporter found: '+ type);
    return this._exporters[type](records, opts);
  }

  /**
   * Request parsed results based on type
   * @param {string} type The type (e.g. 'html') of the content
   * @param {string} content The contents to parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of parsed result objects
   */
  import(type, content, opts) {
    if (opts === undefined) opts = {}
    if(!this._parsers[type]) throw new Error('No matching parser found: '+ type);
    let records = Promise.mapSeries(this._mappingNames(this._parsers[type](content, opts), opts), (record) => { return this.emit('record.'+type, record)})
    return this.emit('records.'+type, records)
  }

  /**
   * Request parsed results from a file path
   * @param {string} filename The filename to read and parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of parsed result objects
   */
  importFile(filename, opts) {
    return fs.readFileAsync(filename).then((content) => {
      content = content.toString()
      var type = path.extname(filename).replace(".", "");
      if (opts.type) {
        type = opts.type
      }
      return this.import(type, content, opts)
    })
  }

  /**
   * Import string contents to a model
   * @param {string} model The identity of the model to populate
   * @param {string} type The type (e.g. 'html') of the content
   * @param {string} content The contents to parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of instances
   */
  importToModel(model, type, content, opts) {
    return this.request('import', type, content, opts).then((results) => {
      return this._modelImport(model, results, opts)
    })
  }

  /**
   * Import file contents to a model
   * @param {string} model The identity of the model to populate
   * @param {string} filename The filename to read and parse
   * @param {object} opts Options for the parser context
   * @return {Promise} Array of instances
   */
  importFileToModel(model, filename, opts) {
    return this.request('importFile', filename, opts).then((results) => {
      return this._modelImport(model, results, opts)
    })
  }

  // Internal

  _modelImport(model_id, results, opts) {
    this.on('models.'+model_id, (args) => {return args})
    this.on('model.'+model_id, (args) => {return args})
    if (opts === undefined) opts = _defaultImportOptions
    var identityFields = opts.identityFields || ['id']
    return Promise.mapSeries(results, (record) => { return this.emit('model.'+model_id, record)}).then((records) => {
      return this.emit('models.'+model_id, records).then((results) => {
        return this.app.get('storage').getModel(model_id).then((model) => {
          var model_attrs = _.keys(model._attributes)
          let importResults = () => {
            return Promise.map(results, (r) => {
              var values = _.pick(r, ...model_attrs)
              var criteria = _.pick(values, ...identityFields)
              return model.createOrUpdate(criteria, values).catch((e) => {this.app.log.error("Error imporing "+model_id, e)})
                })
          }

          if (opts.truncate && _.isEmpty(opts.identityFields)) {
            return model.destroy({}).then(importResults)
          } else {
            return importResults()
          }
        })
      })
    })
  }

  _mappingNames(results, options) {
    var mapping = options.mapping
    if (mapping === undefined || _.isEmpty(mapping)) {
      return results
    }
    var oldNames = _.keys(mapping)
    return _.map(results, (r) => {
      _.mapObject(mapping, (k, v) => {
        r[k] = r[v]
      })
      return _.omit(r, ...oldNames)
    })
  }

}
<|endoftext|>


<commit_before>// Returns a rubber duck's motivating words - optimized for rubber duck debugging
// Made by CharmaineLee

var rubberDuckMe = function() {
    var duckQuotes = getDuckQuotes();
    var rand = Math.floor(Math.random()*duckQuotes.length);
    console.log(duckQuotes[rand]);
};

// rubber ducky's motivating words
function getDuckQuotes() {
    var debug = [
                 debug.push('Talk me through your code line by line.');
                 debug.push("I'm here for you.");
                 debug.push('Give it another thought.');
                 debug.push('I see a problem with that line over there.');
                ]
    return debug;
}

anything.prototype.rubberDuckMe = rubberDuckMe;
<commit_msg>add Console.log()<commit_after>// Returns a rubber duck's motivating words - optimized for rubber duck debugging
// Made by CharmaineLee

var rubberDuckMe = function() {
    var duckQuotes = getDuckQuotes();
    var rand = Math.floor(Math.random()*duckQuotes.length);
    console.log(duckQuotes[rand]);
};

// rubber ducky's motivating words
function getDuckQuotes() {
    var debug = [];
    debug.push('Talk me through your code line by line.');
    debug.push("I'm here for you.");
    debug.push('Give it another thought.');
    debug.push('I see a problem with that line over there.');
    return debug;
}

anything.prototype.rubberDuckMe = rubberDuckMe;
<|endoftext|>


<commit_before>'use strict';

function clear_all(){
    if(window.confirm('Clear?')){
        clear_bases();
    }
}

function clear_bases(except_id){
    except_id = except_id || -1;

    var id = 0;
    var loop_counter = 34;
    do{
        id = loop_counter + 2;

        if(id != except_id){
            document.getElementById(id).value = '';
        }
    }while(loop_counter--);
}

function save(){
    window.prompt(
      'URL:',
      window.location.protocol
        + '//' + window.location.host
        + window.location.pathname
        + '?' + document.getElementById(36).value
    );
}

function update_bases(base){
    var base_value = document.getElementById(base).value;
    if(base_value.length <= 0){
        clear_bases();
    }

    var id = 0;
    var loop_counter = 34;
    do{
        id = loop_counter + 2;
        var value = '';

        if(base != id){
            value = parseInt(
              base_value,
              base
            ).toString(id);

            if(value == 'NaN'){
                value = '';
            }

            document.getElementById(id).value = value;
        }
    }while(loop_counter--);
}
<commit_msg>switched to Number.parseInt()<commit_after>'use strict';

function clear_all(){
    if(window.confirm('Clear?')){
        clear_bases();
    }
}

function clear_bases(except_id){
    except_id = except_id || -1;

    var id = 0;
    var loop_counter = 34;
    do{
        id = loop_counter + 2;

        if(id != except_id){
            document.getElementById(id).value = '';
        }
    }while(loop_counter--);
}

function save(){
    window.prompt(
      'URL:',
      window.location.protocol
        + '//' + window.location.host
        + window.location.pathname
        + '?' + document.getElementById(36).value
    );
}

function update_bases(base){
    var base_value = document.getElementById(base).value;
    if(base_value.length <= 0){
        clear_bases();
    }

    var id = 0;
    var loop_counter = 34;
    do{
        id = loop_counter + 2;
        var value = '';

        if(base != id){
            value = Number.parseInt(
              base_value,
              base
            ).toString(id);

            if(value == 'NaN'){
                value = '';
            }

            document.getElementById(id).value = value;
        }
    }while(loop_counter--);
}
<|endoftext|>


<commit_before>import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './configureStore';
import Root from './Root';
import { okapi, config } from 'stripes-loader!'; // eslint-disable-line

const initialState = { okapi };
const store = configureStore(initialState, config);

render(
  <Root store={store} disableAuth={config.disableAuth || false} />,
  document.getElementById('root'),
);
<commit_msg>Guard against config being undefined. Fixes bug that Wayne found in STRIPES-168<commit_after>import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './configureStore';
import Root from './Root';
import { okapi, config } from 'stripes-loader!'; // eslint-disable-line

const initialState = { okapi };
const store = configureStore(initialState, config);

render(
  <Root store={store} disableAuth={(config && config.disableAuth) || false} />,
  document.getElementById('root'),
);
<|endoftext|>


<commit_before>'use strict';

function resetLS() {
  //reset local storage
  localStorage.clear();
  //send the user to the menu
  location.href = "./index.html";
}

var totalBeers = 0;
var totalWines = 0;
var totalLiquor = 0;

var allSelections = JSON.parse( localStorage.allButtonSelections);

var drinkBac = JSON.parse( localStorage.allDrinkBac);

var mealsConsumed = JSON.parse( localStorage.allMeals);

var drinksConsumed = JSON.parse( localStorage.allDrinks);

//Draw a table on the page
drawTable();
function drawTable() {
  var dataTable = document.getElementById('drinkHistoryTable');
  console.log(dataTable);
  var tableHeader = document.createElement('thead');
  var headerRow = document.createElement('tr');
  var tableBody = document.createElement('tbody');
  var headers = ['What you drank','How much it affected you (BAC)','What your stomach-status was before the drink.'];
  for(var h = 0; h < headers.length;h++) {
    var headerCell = document.createElement('th');
    headerCell.textContent = headers[h];
    headerRow.appendChild(headerCell);
  }
  tableHeader.appendChild(headerRow);
  dataTable.appendChild(tableHeader);
  for(var i = 0; i < drinksConsumed.length; i++) {
    var currentDrink = drinksConsumed[i];
    var currentDrinkBac = drinkBac[i];
    var currentMeal = mealsConsumed[i];
    var newRow = document.createElement('tr');
    var cellData = [currentDrink,currentDrinkBac.toFixed(4),currentMeal];
    for(var r = 0; r < cellData.length; r++) {
      var newCell = document.createElement('td');
      newCell.textContent = cellData[r];
      newRow.appendChild(newCell);
    }
    tableBody.appendChild(newRow);
  }
  dataTable.append(tableBody);
}

// functions for total BAC total drinks of each type and sub types
for (var i = 0; i < drinksConsumed.length; i++) {
  if(drinksConsumed[i] == 'pale' || drinksConsumed[i] == 'stout' || drinksConsumed[i] == 'ipa'){
    totalBeers++;
  }
  else if (drinksConsumed[i] == 'red' || drinksConsumed[i] == 'white' || drinksConsumed[i] == 'bubbles' ) {
    totalWines++;
  }
  else if (drinksConsumed[i] == 'neat' || drinksConsumed[i] == 'mixed' || drinksConsumed[i] == 'shot') {
    totalLiquor++;
  }

}

console.log(totalBeers + ' beer');
console.log(totalLiquor + ' liquor');
console.log(totalWines + ' wine');

if (drinksConsumed.length = 4) {
  $('#blurMe').foggy({
    blurRadius: 1,          // In pixels.
    opacity: 0.9,           // Falls back to a filter for IE.
    cssFilterSupport: true  // Use "-webkit-filter" where available.
  });
}

if (drinksConsumed.length = 5) {
  $('#blurMe').foggy({
    blurRadius: 1.5,          // In pixels.
    opacity: 0.8,           // Falls back to a filter for IE.
    cssFilterSupport: true  // Use "-webkit-filter" where available.
  });
}

if (drinksConsumed.length > 6) {
  $('#blurMe').foggy({
    blurRadius: 3,          // In pixels.
    opacity: 0.5,           // Falls back to a filter for IE.
    cssFilterSupport: true  // Use "-webkit-filter" where available.
  });
}
<commit_msg>fixed bug in blur caused by incorrect use of =<commit_after>'use strict';

function resetLS() {
  //reset local storage
  localStorage.clear();
  //send the user to the menu
  location.href = "./index.html";
}

var totalBeers = 0;
var totalWines = 0;
var totalLiquor = 0;

var allSelections = JSON.parse(localStorage.allButtonSelections);

var drinkBac = JSON.parse(localStorage.allDrinkBac);

var mealsConsumed = JSON.parse(localStorage.allMeals);

var drinksConsumed = JSON.parse(localStorage.allDrinks);
console.log(drinksConsumed);

//Draw a table on the page
drawTable();
function drawTable() {
  var dataTable = document.getElementById('drinkHistoryTable');
  console.log(dataTable);
  var tableHeader = document.createElement('thead');
  var headerRow = document.createElement('tr');
  var tableBody = document.createElement('tbody');
  var headers = ['What you drank','How much it affected you (BAC)','What your stomach-status was before the drink.'];
  for(var h = 0; h < headers.length;h++) {
    var headerCell = document.createElement('th');
    headerCell.textContent = headers[h];
    headerRow.appendChild(headerCell);
  }
  tableHeader.appendChild(headerRow);
  dataTable.appendChild(tableHeader);
  for(var i = 0; i < drinksConsumed.length; i++) {
    var currentDrink = drinksConsumed[i];
    var currentDrinkBac = drinkBac[i];
    var currentMeal = mealsConsumed[i];
    var newRow = document.createElement('tr');
    var cellData = [currentDrink,currentDrinkBac.toFixed(4),currentMeal];
    for(var r = 0; r < cellData.length; r++) {
      var newCell = document.createElement('td');
      newCell.textContent = cellData[r];
      newRow.appendChild(newCell);
    }
    tableBody.appendChild(newRow);
  }
  dataTable.append(tableBody);
}

// functions for total BAC total drinks of each type and sub types
for (var i = 0; i < drinksConsumed.length; i++) {
  if(drinksConsumed[i] == 'pale' || drinksConsumed[i] == 'stout' || drinksConsumed[i] == 'ipa'){
    totalBeers++;
  }
  else if (drinksConsumed[i] == 'red' || drinksConsumed[i] == 'white' || drinksConsumed[i] == 'bubbles' ) {
    totalWines++;
  }
  else if (drinksConsumed[i] == 'neat' || drinksConsumed[i] == 'mixed' || drinksConsumed[i] == 'shot') {
    totalLiquor++;
  }
}

console.log(totalBeers + ' beer');
console.log(totalLiquor + ' liquor');
console.log(totalWines + ' wine');

// Blur the screen as the user drinks more
if (drinksConsumed.length == 4) {
  $('#blurMe').foggy({
    blurRadius: 1,
    opacity: 0.9,
    cssFilterSupport: true
  });
}

if (drinksConsumed.length == 5) {
  $('#blurMe').foggy({
    blurRadius: 1.5,
    opacity: 0.8,
    cssFilterSupport: true
  });
}

if (drinksConsumed.length >= 6) {
  $('#blurMe').foggy({
    blurRadius: 3,
    opacity: 0.5,
    cssFilterSupport: true
  });
}
<|endoftext|>


<commit_before>var _CALLBACK_ = function() {
	$(document).ready(
		function() {
			function parse(v) {
				var t = v.replace(/(“|”)/ig, '"');
				return JSON.parse(t);
			}
			var v = $('.qaletplugin'), r={}, f=[];
			for (var i = 0; i < v.length; i++) {
				var data = $(v[i]).html();
				if (!data) data = $(v[i]).attr('data');
				console.log(data);
				var o = parse(data);
				if (o.module) {
					r[o.module] = true;
					o.id = o.module + '_plugin_' + i;
					f[f.length] = o;
					 $(v[i]).html('

');
				}
			}

			for (var i=0; i<f.length; i++) {
				_QALET_[f[i].module](f[i]);
				$(v[i]).fadeIn( "slow");
			}

			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//qalet.com/css/bootstrap.min.css' });
			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//docviewer.qalet.com/package/docviewer_wp.min.css' });
		//	$.getScript('http://docviewer.qalet.com/package/qalet_plugin_plus.jsx?plus='+Object.keys(r).join(',') + '&callback=_QACALLBACK_');
		}
	);
};
<commit_msg>Update qalet_plugin.js<commit_after>var _CALLBACK_ = function() {
	$(document).ready(
		function() {
			function parse(v) {
				var t = v.replace(/(“|”)/ig, '"');
				return JSON.parse(t);
			}
			var v = $('.qaletplugin'), r={}, f=[];
			for (var i = 0; i < v.length; i++) {
				var data = $(v[i]).html();
				if (!data) data = $(v[i]).attr('data');

				var o = parse(data);
				console.log(o);

				if (o.module) {
					r[o.module] = true;
					o.id = o.module + '_plugin_' + i;
					f[f.length] = o;
					 $(v[i]).html('

');
				}
			}

			for (var i=0; i<f.length; i++) {
				_QALET_[f[i].module](f[i]);
				$(v[i]).fadeIn( "slow");
			}

			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//qalet.com/css/bootstrap.min.css' });
			$('<link>').appendTo('head').attr({ type: 'text/css', rel: 'stylesheet', href: '//docviewer.qalet.com/package/docviewer_wp.min.css' });
		//	$.getScript('http://docviewer.qalet.com/package/qalet_plugin_plus.jsx?plus='+Object.keys(r).join(',') + '&callback=_QACALLBACK_');
		}
	);
};
<|endoftext|>


<commit_before><commit_msg>national code validation method<commit_after>function isValid(code) {
    if (!code || !code.length)
        return false;

    var c = parseInt(code.charAt(9));

    var n = parseInt(code.charAt(0)) * 10 +
            parseInt(code.charAt(1)) * 9 +
            parseInt(code.charAt(2)) * 8 +
            parseInt(code.charAt(3)) * 7 +
            parseInt(code.charAt(4)) * 6 +
            parseInt(code.charAt(5)) * 5 +
            parseInt(code.charAt(6)) * 4 +
            parseInt(code.charAt(7)) * 3 +
            parseInt(code.charAt(8)) * 2;

    var r = n - parseInt((n / 11).toString()) * 11;

    if ((r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r)) {
        return true;
    }
    return false;
}

module.exports = {
    isValid: isValid
}<|endoftext|>


<commit_before>'use strict';

// Optional args: color, frequency, id, length-half, x, y
function data_canvas_fence_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color': '#777',
        'frequency': 60,
        'id': core_uid(),
        'length-half': 25,
        'x': 0,
        'y': 0,
      },
    });

    scenery.push({
      'color': args['color'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -args['length-half'],
          'y': -20,
        },
        {
          'x': args['length-half'],
          'y': -20,
        },
        {
          'x': args['length-half'],
          'y': -15,
        },
        {
          'x': -args['length-half'],
          'y': -15,
        },
      ],
      'x': args['x'],
      'y': args['y'],
    });

    for(let i = 0; i < args['length-half'] * 2; i += args['frequency']){
        scenery.push({
          'color': args['color'],
          'vertices': [
            {
              'type': 'moveTo',
              'x': -5,
              'y': -25,
            },
            {
              'x': 5,
              'y': -25,
            },
            {
              'x': 5,
            },
            {
              'x': -5,
            },
          ],
          'y': args['y'],
          'x': args['x'] - args['length-half'] + i,
        });
    }
}

// Optional args: color-base, color-leaf, half-base, half-leaf, id, x, y
function data_canvas_tree_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color-base': '#be6400',
        'color-leaf': '#' + core_random_hex(),
        'height-base': 25,
        'height-leaf': 75,
        'id': core_uid(),
        'width-base': 25,
        'width-leaf': 75,
        'x': 0,
        'y': 0,
      },
    });

    let half_base = args['width-base'] / 2;
    let half_leaf = args['width-leaf'] / 2;

    scenery.push({
      'color': args['color-base'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -half_base,
          'y': -args['height-base'],
        },
        {
          'x': half_base,
          'y': -args['height-base'],
        },
        {
          'x': half_base,
        },
        {
          'x': -half_base,
        },
      ],
      'x': args['x'],
      'y': args['y'],
    },
    {
      'color': args['color-leaf'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -half_leaf,
          'y': -args['height-leaf'],
        },
        {
          'x': half_leaf,
          'y': -args['height-leaf'],
        },
        {
          'x': half_leaf,
        },
        {
          'x': -half_leaf,
        },
      ],
      'x': args['x'],
      'y': args['y'] - args['height-base'],
    });
}

// Optional args: color
function data_webgl_skybox(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color': webgl_vertexcolorarray(),
      },
    });

    core_entity_create({
      'id': 'skybox-back',
      'properties': {
        'rotate-x': 270,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-back',
      'offset-z': 5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-bottom',
      'properties': {
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-bottom',
      'offset-y': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-front',
      'properties': {
        'rotate-x': 90,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-front',
      'offset-z': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-left',
      'properties': {
        'rotate-z': 270,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-left',
      'offset-x': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-right',
      'properties': {
        'rotate-z': 90,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-right',
      'offset-x': 5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-top',
      'properties': {
        'rotate-x': 180,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-top',
      'offset-y': 5,
      'to': '_me',
      'type': 'character',
    });

    core_group_move({
      'entities': [
        'skybox-back',
        'skybox-bottom',
        'skybox-front',
        'skybox-left',
        'skybox-right',
        'skybox-top',
      ],
      'from': 'foreground',
      'to': 'skybox',
    });
}

// Optional args: color, id, length, length-step, width, width-step, x, y, z
function data_webgl_terrain_3d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color': .5,
        'id': core_uid(),
        'length': 10,
        'length-step': 1,
        'width': 10,
        'width-step': 1,
        'x': 0,
        'y': 0,
        'z': 0,
      },
    });

    let color = [];
    let start_x = (-args['length'] / 2) * args['width-step'];
    let start_z = (-args['width'] / 2) * args['length-step'];
    let textureData = [];
    let vertices = [];

    for(let i = 0; i < args['length']; i++){
        let step = i * args['length-step'];
        for(let j = 0; j < args['width']; j++){
            color.push(
              args['color'],
              args['color'],
              args['color'],
              1,
              args['color'],
              args['color'],
              args['color'],
              1
            );
            textureData.push(
              0,
              1,
              0,
              1
            );
            vertices.push(
              start_x + j * args['width-step'],
              args['y'],
              start_z + step,
              1,
              start_x + j * args['width-step'],
              args['y'],
              start_z + step + args['length-step'],
              1
            );
        }
    }

    core_entity_create({
      'id': args['id'],
      'properties': {
        'draw-type': 'TRIANGLE_STRIP',
        'textureData': textureData,
        'translate-x': args['x'],
        'translate-y': args['y'],
        'translate-z': args['z'],
        'vertex-colors': color,
        'vertices': vertices,
      },
    });
}

// Optional args: billboard, color-base, color-leaf, dx, dy, dz, id, x, y, z
function data_webgl_tree_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'billboard': false,
        'color-base': [
          .4, .2, 0, 1,
          .4, .2, 0, 1,
          .4, .2, 0, 1,
        ],
        'color-leaf': [
          .1, .3, .1, 1,
          .1, .3, .1, 1,
          .1, .3, .1, 1,
        ],
        'dx': 0,
        'dy': 0,
        'dz': 0,
        'id': core_uid(),
        'x': 0,
        'y': 0,
        'z': 0,
      },
    });

    core_entity_create({
      'id': 'webgl-tree_' + args['id'] + '_base',
      'properties': {
        'billboard': args['billboard'],
        'dx': args['dx'],
        'dy': args['dy'],
        'dz': args['dz'],
        'translate-x': args['x'],
        'translate-y': args['y'],
        'translate-z': args['z'],
        'vertex-colors': args['color-base'],
        'vertices': [
          1, 0, -.01, 1,
          0, 4, -.01, 1,
          -1, 0, -.01, 1,
        ],
      },
    });
    core_entity_create({
      'id': 'webgl-tree_' + args['id'] + '_leaf',
      'properties': {
        'billboard': args['billboard'],
        'draw-type': 'TRIANGLES',
        'dx': args['dx'],
        'dy': args['dy'],
        'dz': args['dz'],
        'translate-x': args['x'],
        'translate-y': args['y'],
        'translate-z': args['z'],
        'vertex-colors': args['color-leaf'],
        'vertices': [
          3, 1, 0, 1,
          0, 5, 0, 1,
          -3, 1, 0, 1,
        ],
      },
    });

    core_group_add({
      'entities': [
        'webgl-tree_' + args['id'] + '_base',
        'webgl-tree_' + args['id'] + '_leaf',
      ],
      'group': args['id'],
    });
}

// Optional args: collision, color-base, color-leaf, dx, dy, dz, id, x, y, z
function data_webgl_tree_3d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'collision': false,
        'color-base': [
          .4, .2, 0, 1,
          .4, .2, 0, 1,
          .4, .2, 0, 1,
          .4, .2, 0, 1,
        ],
        'color-leaf': [
          .1, .3, .1, 1,
          .1, .3, .1, 1,
          .1, .3, .1, 1,
          .1, .3, .1, 1,
        ],
        'dx': 0,
        'dy': 0,
        'dz': 0,
        'id': core_uid(),
        'x': 0,
        'y': 0,
        'z': 0,
      },
    });

    data_webgl_cube_3d({
      'collision': args['collision'],
      'color': args['color-base'],
      'dx': args['dx'],
      'dy': args['dy'],
      'dz': args['dz'],
      'exclude': [
        0,
        1,
      ],
      'id': 'webgl-tree_' + args['id'] + '_base',
      'side': 1,
      'x': args['x'],
      'y': args['y'] + 1,
      'z': args['z'],
    });
    data_webgl_cube_3d({
      'collision': args['collision'],
      'color': args['color-leaf'],
      'dx': args['dx'],
      'dy': args['dy'],
      'dz': args['dz'],
      'id': 'webgl-tree_' + args['id'] + '_leaf',
      'side': 3,
      'x': args['x'],
      'y': args['y'] + 5,
      'z': args['z'],
    });
}
<commit_msg>removed remaining old 3d functions<commit_after>'use strict';

// Optional args: color, frequency, id, length-half, x, y
function data_canvas_fence_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color': '#777',
        'frequency': 60,
        'id': core_uid(),
        'length-half': 25,
        'x': 0,
        'y': 0,
      },
    });

    scenery.push({
      'color': args['color'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -args['length-half'],
          'y': -20,
        },
        {
          'x': args['length-half'],
          'y': -20,
        },
        {
          'x': args['length-half'],
          'y': -15,
        },
        {
          'x': -args['length-half'],
          'y': -15,
        },
      ],
      'x': args['x'],
      'y': args['y'],
    });

    for(let i = 0; i < args['length-half'] * 2; i += args['frequency']){
        scenery.push({
          'color': args['color'],
          'vertices': [
            {
              'type': 'moveTo',
              'x': -5,
              'y': -25,
            },
            {
              'x': 5,
              'y': -25,
            },
            {
              'x': 5,
            },
            {
              'x': -5,
            },
          ],
          'y': args['y'],
          'x': args['x'] - args['length-half'] + i,
        });
    }
}

// Optional args: color-base, color-leaf, half-base, half-leaf, id, x, y
function data_canvas_tree_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color-base': '#be6400',
        'color-leaf': '#' + core_random_hex(),
        'height-base': 25,
        'height-leaf': 75,
        'id': core_uid(),
        'width-base': 25,
        'width-leaf': 75,
        'x': 0,
        'y': 0,
      },
    });

    let half_base = args['width-base'] / 2;
    let half_leaf = args['width-leaf'] / 2;

    scenery.push({
      'color': args['color-base'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -half_base,
          'y': -args['height-base'],
        },
        {
          'x': half_base,
          'y': -args['height-base'],
        },
        {
          'x': half_base,
        },
        {
          'x': -half_base,
        },
      ],
      'x': args['x'],
      'y': args['y'],
    },
    {
      'color': args['color-leaf'],
      'vertices': [
        {
          'type': 'moveTo',
          'x': -half_leaf,
          'y': -args['height-leaf'],
        },
        {
          'x': half_leaf,
          'y': -args['height-leaf'],
        },
        {
          'x': half_leaf,
        },
        {
          'x': -half_leaf,
        },
      ],
      'x': args['x'],
      'y': args['y'] - args['height-base'],
    });
}

// Optional args: color
function data_webgl_skybox(args){
    args = core_args({
      'args': args,
      'defaults': {
        'color': webgl_vertexcolorarray(),
      },
    });

    core_entity_create({
      'id': 'skybox-back',
      'properties': {
        'rotate-x': 270,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-back',
      'offset-z': 5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-bottom',
      'properties': {
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-bottom',
      'offset-y': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-front',
      'properties': {
        'rotate-x': 90,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-front',
      'offset-z': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-left',
      'properties': {
        'rotate-z': 270,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-left',
      'offset-x': -5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-right',
      'properties': {
        'rotate-z': 90,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-right',
      'offset-x': 5,
      'to': '_me',
      'type': 'character',
    });
    core_entity_create({
      'id': 'skybox-top',
      'properties': {
        'rotate-x': 180,
        'vertex-colors': args['color'],
        'vertices': [
          5, 0, -5, 1,
          -5, 0, -5, 1,
          -5, 0, 5, 1,
          5, 0, 5, 1,
        ],
      },
    });
    webgl_attach({
      'entity': 'skybox-top',
      'offset-y': 5,
      'to': '_me',
      'type': 'character',
    });

    core_group_move({
      'entities': [
        'skybox-back',
        'skybox-bottom',
        'skybox-front',
        'skybox-left',
        'skybox-right',
        'skybox-top',
      ],
      'from': 'foreground',
      'to': 'skybox',
    });
}

// Optional args: billboard, color-base, color-leaf, dx, dy, dz, id, x, y, z
function data_webgl_tree_2d(args){
    args = core_args({
      'args': args,
      'defaults': {
        'billboard': false,
        'color-base': [
          .4, .2, 0, 1,
          .4, .2, 0, 1,
          .4, .2, 0, 1,
        ],
        'color-leaf': [
          .1, .3, .1, 1,
          .1, .3, .1, 1,
          .1, .3, .1, 1,
        ],
        'dx': 0,
        'dy': 0,
        'dz': 0,
        'id': core_uid(),
        'x': 0,
        'y': 0,
        'z': 0,
      },
    });

    core_entity_create({
      'id': 'webgl-tree_' + args['id'] + '_base',
      'properties': {
        'billboard': args['billboard'],
        'dx': args['dx'],
        'dy': args['dy'],
        'dz': args['dz'],
        'translate-x': args['x'],
        'translate-y': args['y'],
        'translate-z': args['z'],
        'vertex-colors': args['color-base'],
        'vertices': [
          1, 0, -.01, 1,
          0, 4, -.01, 1,
          -1, 0, -.01, 1,
        ],
      },
    });
    core_entity_create({
      'id': 'webgl-tree_' + args['id'] + '_leaf',
      'properties': {
        'billboard': args['billboard'],
        'draw-type': 'TRIANGLES',
        'dx': args['dx'],
        'dy': args['dy'],
        'dz': args['dz'],
        'translate-x': args['x'],
        'translate-y': args['y'],
        'translate-z': args['z'],
        'vertex-colors': args['color-leaf'],
        'vertices': [
          3, 1, 0, 1,
          0, 5, 0, 1,
          -3, 1, 0, 1,
        ],
      },
    });

    core_group_add({
      'entities': [
        'webgl-tree_' + args['id'] + '_base',
        'webgl-tree_' + args['id'] + '_leaf',
      ],
      'group': args['id'],
    });
}
<|endoftext|>


<commit_before>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// reset the score
		game.data.score = 0;

		//telling it what to look at as far as maps
		me.levelDirector.loadLevel("level01");

		// set a value to the variable player.
		var player = me.pool.pull("player", 0, 420, {});
		//sets the height of where the player appears on the screen.
		me.game.world.addChild(player, 5);

		me.input.bindKey(me.input.KEY.RIGHT, "rigtht");
		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	}
});
<commit_msg>Fixed error on code from video 7<commit_after>game.PlayScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		// reset the score
		game.data.score = 0;

		//telling it what to look at as far as maps
		me.levelDirector.loadLevel("level01");

		// set a value to the variable player.
		var player = me.pool.pull("player", 0, 420, {});
		//sets the height of where the player appears on the screen.
		me.game.world.addChild(player, 5);

		me.input.bindKey(me.input.KEY.RIGHT, "right");
		// add our HUD to the game world
		this.HUD = new game.HUD.Container();
		me.game.world.addChild(this.HUD);
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
		// remove the HUD from the game world
		me.game.world.removeChild(this.HUD);
	}
});
<|endoftext|>


<commit_before>'use strict';

function decisecond(){
    time = core_round({
      'decimals': 1,
      'number': time - .1,
    });

    core_elements['time'].innerHTML = core_number_format({
      'decimals-min': 1,
      'number': time,
    });

    if(time <= 0){
        core_interval_pause_all();
        document.getElementById('text').readOnly = true;
    }
}

function enter(){
    if(core_intervals['interval']['paused']){
        start();
    }

    let targetelement = document.getElementById('target');
    let textelement = document.getElementById('text');
    if(textelement.value !== targetelement.innerHTML){
        return;
    }

    audio_start({
      'id': 'boop',
    });

    let element = document.getElementById('score');
    element.innerHTML = Number.parseInt(
      element.innerHTML,
      10
    ) + 1;
    targetelement.innerHTML = core_random_string({
      'characters': letters,
      'length': core_storage_data['length'],
    });
    textelement.value = '';

    set_time_remaining(time_remaining - core_storage_data['time-decrease']);
}

function set_time_remaining(new_time_remaining){
    time_remaining = new_time_remaining;
    time = time_remaining;
    core_elements['time'].innerHTML = core_round({
      'decimals': 1,
      'number': time_remaining,
    });
}

function start(){
    set_time_remaining(core_storage_data['time-max']);

    document.getElementById('score').innerHTML = 0;
    document.getElementById('target').innerHTML = core_random_string({
      'characters': letters,
      'length': core_storage_data['length'],
    });
    let element = document.getElementById('text');
    element.value = '';
    element.readOnly = false;
    element.focus();

    core_interval_modify({
      'id': 'interval',
      'interval': 100,
      'todo': decisecond,
    });
}
<commit_msg>replaced some innerHTML with textContent<commit_after>'use strict';

function decisecond(){
    time = core_round({
      'decimals': 1,
      'number': time - .1,
    });

    core_elements['time'].textContent = core_number_format({
      'decimals-min': 1,
      'number': time,
    });

    if(time <= 0){
        core_interval_pause_all();
        document.getElementById('text').readOnly = true;
    }
}

function enter(){
    if(core_intervals['interval']['paused']){
        start();
    }

    let targetelement = document.getElementById('target');
    let textelement = document.getElementById('text');
    if(textelement.value !== targetelement.textContent){
        return;
    }

    audio_start({
      'id': 'boop',
    });

    let element = document.getElementById('score');
    element.textContent = Number.parseInt(
      element.textContent,
      10
    ) + 1;
    targetelement.textContent = core_random_string({
      'characters': letters,
      'length': core_storage_data['length'],
    });
    textelement.value = '';

    set_time_remaining(time_remaining - core_storage_data['time-decrease']);
}

function set_time_remaining(new_time_remaining){
    time_remaining = new_time_remaining;
    time = time_remaining;
    core_elements['time'].textContent = core_round({
      'decimals': 1,
      'number': time_remaining,
    });
}

function start(){
    set_time_remaining(core_storage_data['time-max']);

    document.getElementById('score').textContent = 0;
    document.getElementById('target').textContent = core_random_string({
      'characters': letters,
      'length': core_storage_data['length'],
    });
    let element = document.getElementById('text');
    element.value = '';
    element.readOnly = false;
    element.focus();

    core_interval_modify({
      'id': 'interval',
      'interval': 100,
      'todo': decisecond,
    });
}
<|endoftext|>


<commit_before>'use strict';

import 'babel-polyfill';
import 'source-map-support/register';
import cheerio from 'cheerio';
import core from './core.js';
import debugLog from 'debug';
import url from 'url';
import web from './web.js';

const
	debug = debugLog('craigslist'),
	DEFAULT_BASE_HOST = 'craigslist.org',
	DEFAULT_CATEGORY = 'sss',
	DEFAULT_CATEGORY_DETAILS_INDEX = 1,
	DEFAULT_PATH = '/search/',
	DEFAULT_QUERYSTRING = '?sort=rel',
	DEFAULT_REQUEST_OPTIONS = {
		hostname : '',
		path : '',
		secure : true
	},
	QUERY_KEYS = [
		'category',
		'maxAsk',
		'minAsk',
		'query'
	],
	QUERY_PARAM_MAX = '&maxAsk=',
	QUERY_PARAM_MIN = '&minAsk=',
	QUERY_PARAM_QUERY = '&query=',
	RE_HTML = /\.htm(l)?/i,
	RE_QUALIFIED_URL = /^\/\/[a-z0-9\-]*\.craigslist\.[a-z]*/i,
	RE_TAGS_MAP = /map/i;

/**
 * Accepts strong of HTML and parses that string to find key details.
 *
 * @param {string} postingUrl - URL that details were loaded from
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {object} details - The processed details from the Craigslist posting
 **/
function _getPostingDetails (postingUrl, markup) {
	let
		$ = cheerio.load(markup),
		details = {};

	details.description = ($('#postingbody').text() || '').trim();
	details.mapUrl = $('div.mapbox p.mapaddress')
		.find('a')
		.attr('href');
	details.pid = postingUrl
		.substring(postingUrl.search(/[0-9]*\.html/))
		.replace(/\.html/, '');
	details.replyUrl = ($('#replylink').attr('href') || '').trim();
	details.title = ($('#titletextonly').text() || '').trim();
	details.url = postingUrl;

	// populate posting info
	$('div.postinginfos').find('.postinginfo').each((i, element) => {
		let infoType = $(element).text();

		// set pid (a backup to ripping it from the URL)
		if (/post\sid/i.test(infoType)) {
			details.pid = (infoType.split(/\:/)[1] || '').trim();
			return;
		}

		// set postedAt
		if (/posted/i.test(infoType) && $(element).find('time').attr('datetime')) {
			details.postedAt = new Date($(element).find('time').attr('datetime'));
			return;
		}

		// set updatedAt
		if (/updated/i.test(infoType) && $(element).find('time').attr('datetime')) {
			details.updatedAt = new Date($(element).find('time').attr('datetime'));
			return;
		}
	});

	// populate posting photos
	$('#thumbs').find('a').each((i, element) => {
		details.images = details.images || [];
		details.images.push(($(element).attr('href') || '').trim());
	});

	return details;
}

/**
 * Accepts string of HTML and parses that string to find all pertinent postings.
 *
 * @param {object} options - Request options used for the request to craigslist
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {Array} postings - The processed and normalized array of postings
 **/
function _getPostings (options, markup) {
	let
		$ = cheerio.load(markup),
		hostname = options.hostname,
		posting = {},
		postings = [],
		secure = options.secure;

	$('div.content')
		.find('.result-row')
		.each((i, element) => {
			let
				// introducing fix for #11 - Craigslist markup changed
				details = $(element)
					.find('.result-title')
					.attr('href')
					.split(/\//g)
					.filter((term) => term.length)
					.map((term) => term.split(RE_HTML)[0]),
				detailsUrl = $(element)
					.find('.result-title')
					.attr('href');

			// introducing fix for #6
			if (!RE_QUALIFIED_URL.test(detailsUrl)) {
				detailsUrl = [
					(secure ? 'https://' : 'http://'),
					hostname,
					detailsUrl].join('');
				// debug('adjusted URL for posting to (%s)', detailsUrl);
			} else {
				detailsUrl = [
					(secure ? 'https:' : 'http:'),
					detailsUrl].join('');
				// debug('adjusted URL for postings to (%s)', detailsUrl);
			}

			posting = {
				category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
				coordinates : {
					lat : $(element).attr('data-latitude'),
					lon : $(element).attr('data-longitude')
				},
				date : ($(element)
					.find('time')
					.attr('datetime') || '')
						.trim(),
				hasPic : RE_TAGS_MAP
					.test($(element)
						.find('.result-tags')
						.text() || ''),
				pid : ($(element)
					.attr('data-pid') || '')
						.trim(),
				price : ($(element)
					.find('.result-price')
					.text() || '')
						.replace(/^\&\#x0024\;/g, '')
						.trim(), // sanitize
				title : ($(element)
					.find('.result-title')
					.text() || '')
						.trim(),
				url : detailsUrl
			};

			// make sure lat / lon is valid
			if (typeof posting.coordinates.lat === 'undefined' ||
				typeof posting.coordinates.lon === 'undefined') {
				delete posting.coordinates;
			}

			postings.push(posting);
		});

	return postings;
}

/**
 * Accepts strong of HTML and parses that string to find key details.
 *
 * @param {object} details - a posting object to populate
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {null} - Returns empty
 **/
function _getReplyDetails (details, markup) {
	let $ = cheerio.load(markup);

	$('div.reply_options').find('b').each((i, element) => {
		let infoType = $(element).text().trim();

		// set contact name
		if (/contact\sname/i.test(infoType)) {
			$(element).next().find('li').each((i, li) => {
				details.contactName = $(li).text().trim();
			});

			return;
		}

		// set phone number and email
		if (/call/i.test(infoType)) {
			$(element).parent().find('li').each((i, li) => {
				let value = $(li).text().trim();

				// check for phone value (based on the emoji)
				if (/\u260E/.test(value)) {
					details.phoneNumber = value.substring(value.indexOf('('));
					return;
				}

				// check for email value (based on the @ symbol)
				if (/\@/.test(value)) {
					details.email = value;
				}
			});

			return;
		}
	});
}

/**
 * Accepts options, iterates through the known acceptable keys from defaultOptions
 * and if found in input options, uses that. If not found in input options to method,
 * falls back to the options specified when the module was initialized. If not found
 * in initialization options, uses the default options setting. All keys provided in
 * the input options variable are retained.
 *
 * @param {object} options - Input options for the web request
 * @param {string} query - A querystring
 * @returns {object} options - The coalesced result of options
 **/
function _getRequestOptions (options, query) {
	var
		requestOptions = JSON.parse(JSON.stringify(DEFAULT_REQUEST_OPTIONS)),
		/*eslint no-invalid-this:0*/
		self = this;

	// ensure default options are set, even if omitted from input options
	requestOptions.hostname = [
		core.Validation.coalesce(options.city, self.options.city, ''),
		// introducing fix for #7
		core.Validation.coalesce(
			options.baseHost,
			self.options.baseHost,
			DEFAULT_BASE_HOST)
	].join('.');

	// preserve any extraneous input option keys (may have addition instructions for underlying request object)
	Object
		.keys(options)
		.forEach((key) => {
			if (!QUERY_KEYS.indexOf(key) &&
				core.Validation.isEmpty(requestOptions[key]) &&
				core.Validation.isEmpty(DEFAULT_REQUEST_OPTIONS[key])) {
				requestOptions[key] = options[key];
			}
		});

	// setup path
	if (core.Validation.isEmpty(requestOptions.path)) {
		requestOptions.path = DEFAULT_PATH;
	}

	// setup category
	requestOptions.path = [
		requestOptions.path,
		core.Validation.coalesce(options.category, DEFAULT_CATEGORY)].join('');

	// setup querystring
	requestOptions.path = [requestOptions.path, DEFAULT_QUERYSTRING].join('');

	// add search query (if specified)
	if (!core.Validation.isEmpty(query)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_QUERY,
			encodeURIComponent(query)].join('');
	}

	// add min asking price (if specified)
	if (!core.Validation.isEmpty(options.minAsk)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_MIN,
			options.minAsk].join('');
	}

	// add max asking price (if specified)
	if (!core.Validation.isEmpty(options.maxAsk)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_MAX,
			options.maxAsk].join('');
	}

	debug('setting request options: %o', requestOptions);

	return requestOptions;
}

export class Client {
	constructor(options) {
		this.options = options || {};
		this.request = new web.Request(this.options);
	}

	details (posting, callback) {
		let
			exec,
			getDetails,
			postingUrl,
			requestOptions,
			self = this;

		// retrieves the posting details directly
		getDetails = new Promise((resolve, reject) => {
			if (core.Validation.isEmpty(posting)) {
				return reject(new Error('posting URL is required'));
			}

			if (typeof posting !== 'string' && core.Validation.isEmpty(posting.url)) {
				return reject(new Error('posting URL is required'));
			}

			postingUrl = typeof posting === 'string' ? posting : posting.url;
			requestOptions = url.parse(postingUrl);
			requestOptions.secure = /https/i.test(requestOptions.protocol);

			debug('request options set to: %o', requestOptions);

			return self.request
				.get(requestOptions)
				.then((markup) => {
					debug('retrieved posting %o', posting);
					let details = self::_getPostingDetails(postingUrl, markup);

					return resolve(details);
				})
				.catch(reject);
		});

		exec = new Promise((resolve, reject) => {
			return getDetails
				.then((details) => {
					if (!details.replyUrl) {
						return resolve(details);
					}

					// properly adjust reply URL
					if (!RE_QUALIFIED_URL.test(details.replyUrl)) {
						details.replyUrl = [
							'http://',
							requestOptions.hostname,
							details.replyUrl].join('');
					}

					// set request options to retrieve posting contact info
					requestOptions = url.parse(details.replyUrl);

					return self.request
						.get(requestOptions)
						.then((markup) => {
							self::_getReplyDetails(details, markup);

							return resolve(details);
						})
						.catch(reject);
				})
				.catch(reject);
		});

		// execute!
		return core.Validation.promiseOrCallback(exec, callback);
	}

	list (options, callback) {
		/*eslint no-undefined:0*/
		return this.search(options, undefined, callback);
	}

	search (options, query, callback) {
		if (typeof query === 'function' && core.Validation.isEmpty(callback)) {
			callback = query;
			query = typeof options === 'string' ? options : query;
			options = typeof options === 'string' ? {} : options;
		}

		if (core.Validation.isEmpty(query) && typeof options === 'string') {
			query = options;
			options = {};
		}

		if (typeof options === 'function') {
			callback = options;
			options = {};
			/*eslint no-undefined:0*/
			query = undefined;
		}

		// ensure options is at least a blank object before continuing
		options = options || {};

		let
			exec,
			self = this;

		// create a Promise to execute the request
		exec = new Promise((resolve, reject) => {
			// remap options for the request
			let requestOptions = this::_getRequestOptions(options, query);

			debug('request options set to: %o', requestOptions);

			if (core.Validation.isEmpty(requestOptions.hostname)) {
				return reject(
					new Error(
						'unable to set hostname (check to see if city is specified)'));
			}

			return self.request
				.get(requestOptions)
				.then((markup) => {
					let postings = _getPostings(requestOptions, markup);
					debug('found %d postings', postings.length);

					return resolve(postings);
				})
				.catch(reject);
		});

		// execute!
		return core.Validation.promiseOrCallback(exec, callback);
	}
}

export default { Client }
<commit_msg>adding support back in for location (though it is surrounded in paranthesis)<commit_after>'use strict';

import 'babel-polyfill';
import 'source-map-support/register';
import cheerio from 'cheerio';
import core from './core.js';
import debugLog from 'debug';
import url from 'url';
import web from './web.js';

const
	debug = debugLog('craigslist'),
	DEFAULT_BASE_HOST = 'craigslist.org',
	DEFAULT_CATEGORY = 'sss',
	DEFAULT_CATEGORY_DETAILS_INDEX = 1,
	DEFAULT_PATH = '/search/',
	DEFAULT_QUERYSTRING = '?sort=rel',
	DEFAULT_REQUEST_OPTIONS = {
		hostname : '',
		path : '',
		secure : true
	},
	QUERY_KEYS = [
		'category',
		'maxAsk',
		'minAsk',
		'query'
	],
	QUERY_PARAM_MAX = '&maxAsk=',
	QUERY_PARAM_MIN = '&minAsk=',
	QUERY_PARAM_QUERY = '&query=',
	RE_HTML = /\.htm(l)?/i,
	RE_QUALIFIED_URL = /^\/\/[a-z0-9\-]*\.craigslist\.[a-z]*/i,
	RE_TAGS_MAP = /map/i;

/**
 * Accepts strong of HTML and parses that string to find key details.
 *
 * @param {string} postingUrl - URL that details were loaded from
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {object} details - The processed details from the Craigslist posting
 **/
function _getPostingDetails (postingUrl, markup) {
	let
		$ = cheerio.load(markup),
		details = {};

	details.description = ($('#postingbody').text() || '').trim();
	details.mapUrl = $('div.mapbox p.mapaddress')
		.find('a')
		.attr('href');
	details.pid = postingUrl
		.substring(postingUrl.search(/[0-9]*\.html/))
		.replace(/\.html/, '');
	details.replyUrl = ($('#replylink').attr('href') || '').trim();
	details.title = ($('#titletextonly').text() || '').trim();
	details.url = postingUrl;

	// populate posting info
	$('div.postinginfos').find('.postinginfo').each((i, element) => {
		let infoType = $(element).text();

		// set pid (a backup to ripping it from the URL)
		if (/post\sid/i.test(infoType)) {
			details.pid = (infoType.split(/\:/)[1] || '').trim();
			return;
		}

		// set postedAt
		if (/posted/i.test(infoType) && $(element).find('time').attr('datetime')) {
			details.postedAt = new Date($(element).find('time').attr('datetime'));
			return;
		}

		// set updatedAt
		if (/updated/i.test(infoType) && $(element).find('time').attr('datetime')) {
			details.updatedAt = new Date($(element).find('time').attr('datetime'));
			return;
		}
	});

	// populate posting photos
	$('#thumbs').find('a').each((i, element) => {
		details.images = details.images || [];
		details.images.push(($(element).attr('href') || '').trim());
	});

	return details;
}

/**
 * Accepts string of HTML and parses that string to find all pertinent postings.
 *
 * @param {object} options - Request options used for the request to craigslist
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {Array} postings - The processed and normalized array of postings
 **/
function _getPostings (options, markup) {
	let
		$ = cheerio.load(markup),
		hostname = options.hostname,
		posting = {},
		postings = [],
		secure = options.secure;

	$('div.content')
		.find('.result-row')
		.each((i, element) => {
			let
				// introducing fix for #11 - Craigslist markup changed
				details = $(element)
					.find('.result-title')
					.attr('href')
					.split(/\//g)
					.filter((term) => term.length)
					.map((term) => term.split(RE_HTML)[0]),
				detailsUrl = $(element)
					.find('.result-title')
					.attr('href');

			// introducing fix for #6
			if (!RE_QUALIFIED_URL.test(detailsUrl)) {
				detailsUrl = [
					(secure ? 'https://' : 'http://'),
					hostname,
					detailsUrl].join('');
				// debug('adjusted URL for posting to (%s)', detailsUrl);
			} else {
				detailsUrl = [
					(secure ? 'https:' : 'http:'),
					detailsUrl].join('');
				// debug('adjusted URL for postings to (%s)', detailsUrl);
			}

			posting = {
				category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
				coordinates : {
					lat : $(element).attr('data-latitude'),
					lon : $(element).attr('data-longitude')
				},
				date : ($(element)
					.find('time')
					.attr('datetime') || '')
						.trim(),
				hasPic : RE_TAGS_MAP
					.test($(element)
						.find('.result-tags')
						.text() || ''),
				location : ($(element)
					.find('.result-hood')
					.text() || '')
					.trim(),
				pid : ($(element)
					.attr('data-pid') || '')
						.trim(),
				price : ($(element)
					.find('.result-price')
					.text() || '')
						.replace(/^\&\#x0024\;/g, '')
						.trim(), // sanitize
				title : ($(element)
					.find('.result-title')
					.text() || '')
						.trim(),
				url : detailsUrl
			};

			// make sure lat / lon is valid
			if (typeof posting.coordinates.lat === 'undefined' ||
				typeof posting.coordinates.lon === 'undefined') {
				delete posting.coordinates;
			}

			postings.push(posting);
		});

	return postings;
}

/**
 * Accepts strong of HTML and parses that string to find key details.
 *
 * @param {object} details - a posting object to populate
 * @param {string} markup - Markup from the request to Craigslist
 * @returns {null} - Returns empty
 **/
function _getReplyDetails (details, markup) {
	let $ = cheerio.load(markup);

	$('div.reply_options').find('b').each((i, element) => {
		let infoType = $(element).text().trim();

		// set contact name
		if (/contact\sname/i.test(infoType)) {
			$(element).next().find('li').each((i, li) => {
				details.contactName = $(li).text().trim();
			});

			return;
		}

		// set phone number and email
		if (/call/i.test(infoType)) {
			$(element).parent().find('li').each((i, li) => {
				let value = $(li).text().trim();

				// check for phone value (based on the emoji)
				if (/\u260E/.test(value)) {
					details.phoneNumber = value.substring(value.indexOf('('));
					return;
				}

				// check for email value (based on the @ symbol)
				if (/\@/.test(value)) {
					details.email = value;
				}
			});

			return;
		}
	});
}

/**
 * Accepts options, iterates through the known acceptable keys from defaultOptions
 * and if found in input options, uses that. If not found in input options to method,
 * falls back to the options specified when the module was initialized. If not found
 * in initialization options, uses the default options setting. All keys provided in
 * the input options variable are retained.
 *
 * @param {object} options - Input options for the web request
 * @param {string} query - A querystring
 * @returns {object} options - The coalesced result of options
 **/
function _getRequestOptions (options, query) {
	var
		requestOptions = JSON.parse(JSON.stringify(DEFAULT_REQUEST_OPTIONS)),
		/*eslint no-invalid-this:0*/
		self = this;

	// ensure default options are set, even if omitted from input options
	requestOptions.hostname = [
		core.Validation.coalesce(options.city, self.options.city, ''),
		// introducing fix for #7
		core.Validation.coalesce(
			options.baseHost,
			self.options.baseHost,
			DEFAULT_BASE_HOST)
	].join('.');

	// preserve any extraneous input option keys (may have addition instructions for underlying request object)
	Object
		.keys(options)
		.forEach((key) => {
			if (!QUERY_KEYS.indexOf(key) &&
				core.Validation.isEmpty(requestOptions[key]) &&
				core.Validation.isEmpty(DEFAULT_REQUEST_OPTIONS[key])) {
				requestOptions[key] = options[key];
			}
		});

	// setup path
	if (core.Validation.isEmpty(requestOptions.path)) {
		requestOptions.path = DEFAULT_PATH;
	}

	// setup category
	requestOptions.path = [
		requestOptions.path,
		core.Validation.coalesce(options.category, DEFAULT_CATEGORY)].join('');

	// setup querystring
	requestOptions.path = [requestOptions.path, DEFAULT_QUERYSTRING].join('');

	// add search query (if specified)
	if (!core.Validation.isEmpty(query)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_QUERY,
			encodeURIComponent(query)].join('');
	}

	// add min asking price (if specified)
	if (!core.Validation.isEmpty(options.minAsk)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_MIN,
			options.minAsk].join('');
	}

	// add max asking price (if specified)
	if (!core.Validation.isEmpty(options.maxAsk)) {
		requestOptions.path = [
			requestOptions.path,
			QUERY_PARAM_MAX,
			options.maxAsk].join('');
	}

	debug('setting request options: %o', requestOptions);

	return requestOptions;
}

export class Client {
	constructor(options) {
		this.options = options || {};
		this.request = new web.Request(this.options);
	}

	details (posting, callback) {
		let
			exec,
			getDetails,
			postingUrl,
			requestOptions,
			self = this;

		// retrieves the posting details directly
		getDetails = new Promise((resolve, reject) => {
			if (core.Validation.isEmpty(posting)) {
				return reject(new Error('posting URL is required'));
			}

			if (typeof posting !== 'string' && core.Validation.isEmpty(posting.url)) {
				return reject(new Error('posting URL is required'));
			}

			postingUrl = typeof posting === 'string' ? posting : posting.url;
			requestOptions = url.parse(postingUrl);
			requestOptions.secure = /https/i.test(requestOptions.protocol);

			debug('request options set to: %o', requestOptions);

			return self.request
				.get(requestOptions)
				.then((markup) => {
					debug('retrieved posting %o', posting);
					let details = self::_getPostingDetails(postingUrl, markup);

					return resolve(details);
				})
				.catch(reject);
		});

		exec = new Promise((resolve, reject) => {
			return getDetails
				.then((details) => {
					if (!details.replyUrl) {
						return resolve(details);
					}

					// properly adjust reply URL
					if (!RE_QUALIFIED_URL.test(details.replyUrl)) {
						details.replyUrl = [
							'http://',
							requestOptions.hostname,
							details.replyUrl].join('');
					}

					// set request options to retrieve posting contact info
					requestOptions = url.parse(details.replyUrl);

					return self.request
						.get(requestOptions)
						.then((markup) => {
							self::_getReplyDetails(details, markup);

							return resolve(details);
						})
						.catch(reject);
				})
				.catch(reject);
		});

		// execute!
		return core.Validation.promiseOrCallback(exec, callback);
	}

	list (options, callback) {
		/*eslint no-undefined:0*/
		return this.search(options, undefined, callback);
	}

	search (options, query, callback) {
		if (typeof query === 'function' && core.Validation.isEmpty(callback)) {
			callback = query;
			query = typeof options === 'string' ? options : query;
			options = typeof options === 'string' ? {} : options;
		}

		if (core.Validation.isEmpty(query) && typeof options === 'string') {
			query = options;
			options = {};
		}

		if (typeof options === 'function') {
			callback = options;
			options = {};
			/*eslint no-undefined:0*/
			query = undefined;
		}

		// ensure options is at least a blank object before continuing
		options = options || {};

		let
			exec,
			self = this;

		// create a Promise to execute the request
		exec = new Promise((resolve, reject) => {
			// remap options for the request
			let requestOptions = this::_getRequestOptions(options, query);

			debug('request options set to: %o', requestOptions);

			if (core.Validation.isEmpty(requestOptions.hostname)) {
				return reject(
					new Error(
						'unable to set hostname (check to see if city is specified)'));
			}

			return self.request
				.get(requestOptions)
				.then((markup) => {
					let postings = _getPostings(requestOptions, markup);
					debug('found %d postings', postings.length);

					return resolve(postings);
				})
				.catch(reject);
		});

		// execute!
		return core.Validation.promiseOrCallback(exec, callback);
	}
}

export default { Client }
<|endoftext|>


<commit_before>$(document).ready(function(){
	"use strict";

	//// Makes title have a blinking effect ////
	for (var i = 0; i < 1000; i++) {
		$("span").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 5
		}, 1000);
	}

	var usersColorSequence = [];
	var simonsColorSequence = [];
	var roundNumber = 0;
	var animateSpeedForSimon = 1000;

	//start game by pressing enter...
	$(document).keydown(function(key) {
		if(key.keyCode == 13){
			startGame();
			$("#startGameBtn").hide();
		}
	});
	//...or by clicking the 'Start Game' button
	$("#startGameBtn").click(startGame);

	function startGame(){
		$(this).hide();
		showNewRoundNumber();
		setTimeout(getSimonsSequence, 1000);
		$(".colorBox").click(UsersInput);
	};

	function showNewRoundNumber(){
		$("h1").html("Round "  + (roundNumber += 1) + "").css({"font-family": "'Patua One', cursive", "color":"white", "margin":"2%"});
		$("#fadeInNewRoundNumber").hide().fadeIn(800);
	};

	function getSimonsSequence(){
		var randomBoxNumber = Math.ceil(Math.random()*4);
		simonsColorSequence.push(randomBoxNumber);
		animateSimonsSequence(simonsColorSequence);
	};

	function animateSimonsSequence() {
		var i = 0;
		var interval = setInterval(function() {
			switch (simonsColorSequence[i]) {
				case 1:
					$("#greenBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 2:
					$("#redBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 3:
					$("#yellowBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 4:
					$("#blueBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
			};
			i++;
		}, animateSpeedForSimon);
	};

	function UsersInput(){
		$(this).animate({
			opacity: .4
		}, 100).animate({
			opacity: 1
		}, 100);
		usersColorSequence.push(parseInt(this.innerText));
		checkUsersInput();
	};

	function checkUsersInput(){
		if (usersColorSequence[usersColorSequence.length - 1] !== simonsColorSequence[usersColorSequence.length - 1]){
			setInterval(animateLostGameScreen, 500);
			tryAgain();
		} else if (usersColorSequence.toString().indexOf(simonsColorSequence) >= 0){
			$(".alert").show().fadeOut(2000).css({"font-size":"50px", "text-align":"center"}); //tell user they got the sequence correct...
			nextRound(); //...and advance them to the next round
		}
	};

	function nextRound(){
		if(roundNumber == 10){ //if it's round 10 and the user beats it, they win the game...
			setTimeout(userWonGame, 500);
		} else { //...else show the user the new level number they are on
			setTimeout(newRound, 2000);
		}
	};

	function newRound(){
		showNewRoundNumber();
		usersColorSequence = [];
		animateSpeedForSimon -= 100; //speeds up simons sequence each round
		setTimeout(getSimonsSequence, 1000);
	};

	function userWonGame(){
		setInterval(animateGameWonScreen, 500);
		playAgain();
	};

	function animateGameWonScreen(){
		$("h1").html("You Win!!").css({"margin":"0px"});
		$(".colorBox, h1").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 1
		}, 1000);
		$("#playAgainBtn").show().css({"display":"block"});
	};

	function playAgain(){
		$("#playAgainBtn").click(function(){
			location.reload(); //reload game if user clicks 'Play Again' button after winning the game
		});
	};

	function animateLostGameScreen(){
		$("h1").html("You Lose").css({"margin":"0px"});
		$(".colorBox, h1").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 1
		}, 1000);
		$("#tryAgainBtn").show().css({"display":"block"});
	};

	function tryAgain(){
		$("#tryAgainBtn").click(function(){
			location.reload();
		});
	};

});<commit_msg>sped up fadeout time for 'Success!' and sped up the time to show the user 'You Win!!' screen<commit_after>$(document).ready(function(){
	"use strict";

	//// Makes title have a blinking effect ////
	for (var i = 0; i < 1000; i++) {
		$("span").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 5
		}, 1000);
	}

	var usersColorSequence = [];
	var simonsColorSequence = [];
	var roundNumber = 0;
	var animateSpeedForSimon = 1000;

	//start game by pressing enter...
	$(document).keydown(function(key) {
		if(key.keyCode == 13){
			startGame();
			$("#startGameBtn").hide();
		}
	});
	//...or by clicking the 'Start Game' button
	$("#startGameBtn").click(startGame);

	function startGame(){
		$(this).hide();
		showNewRoundNumber();
		setTimeout(getSimonsSequence, 1000);
		$(".colorBox").click(UsersInput);
	};

	function showNewRoundNumber(){
		$("h1").html("Round "  + (roundNumber += 1) + "").css({"font-family": "'Patua One', cursive", "color":"white", "margin":"2%"});
		$("#fadeInNewRoundNumber").hide().fadeIn(800);
	};

	function getSimonsSequence(){
		var randomBoxNumber = Math.ceil(Math.random()*4);
		simonsColorSequence.push(randomBoxNumber);
		animateSimonsSequence(simonsColorSequence);
	};

	function animateSimonsSequence() {
		var i = 0;
		var interval = setInterval(function() {
			switch (simonsColorSequence[i]) {
				case 1:
					$("#greenBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 2:
					$("#redBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 3:
					$("#yellowBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
				case 4:
					$("#blueBox").animate({
						opacity: .2
					}, (animateSpeedForSimon/2)).animate({
						opacity: 1
					}, (animateSpeedForSimon/2));
				break;
			};
			i++;
		}, animateSpeedForSimon);
	};

	function UsersInput(){
		$(this).animate({
			opacity: .4
		}, 100).animate({
			opacity: 1
		}, 100);
		usersColorSequence.push(parseInt(this.innerText));
		checkUsersInput();
	};

	function checkUsersInput(){
		if (usersColorSequence[usersColorSequence.length - 1] !== simonsColorSequence[usersColorSequence.length - 1]){
			setInterval(animateLostGameScreen, 200);
			tryAgain();
		} else if (usersColorSequence.toString().indexOf(simonsColorSequence) >= 0){
			$(".alert").show().fadeOut(1000).css({"font-size":"50px", "text-align":"center"}); //tell user they got the sequence correct...
			nextRound(); //...and advance them to the next round
		}
	};

	function nextRound(){
		if(roundNumber == 10){ //if it's round 10 and the user beats it, they win the game...
			setTimeout(userWonGame, 200);
		} else { //...else show the user the new level number they are on
			setTimeout(newRound, 2000);
		}
	};

	function newRound(){
		showNewRoundNumber();
		usersColorSequence = [];
		animateSpeedForSimon -= 100; //speeds up simons sequence each round
		setTimeout(getSimonsSequence, 1000);
	};

	function userWonGame(){
		setInterval(animateGameWonScreen, 500);
		playAgain();
	};

	function animateGameWonScreen(){
		$("h1").html("You Win!!").css({"margin":"0px"});
		$(".colorBox, h1").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 1
		}, 1000);
		$("#playAgainBtn").show().css({"display":"block"});
	};

	function playAgain(){
		$("#playAgainBtn").click(function(){
			location.reload(); //reload game if user clicks 'Play Again' button after winning the game
		});
	};

	function animateLostGameScreen(){
		$("h1").html("You Lose").css({"margin":"0px"});
		$(".colorBox, h1").animate({
			opacity: .4
		}, 1000).animate({
			opacity: 1
		}, 1000);
		$("#tryAgainBtn").show().css({"display":"block"});
	};

	function tryAgain(){
		$("#tryAgainBtn").click(function(){
			location.reload();
		});
	};

});<|endoftext|>


<commit_before>'use strict';

function check(){
    // Check if every button has correct solution on it.
    let win = true;
    let loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    let loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(){
    core_storage_save();

    let first = 0;
    let second = 0;
    let which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    let loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = core_random_integer({
          'max': 9,
          'todo': 'ceil',
        });
        do{
            second = core_random_integer({
              'max': 9,
              'todo': 'ceil',
            });
        }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        let times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        let times = 8;
        do{
            let temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different columns to switch.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        let times = 8;
        do{
            let temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different rows.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        let times = 8;
        do{
            let temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.style.position = 'relative';
        element.value = ' ';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = core_storage_data['locked'] - 1;
    if(loop_counter >= 0){
        do{
            first = core_random_integer({
              'max': 81,
            });
            let element = document.getElementById(first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[first];

            element = document.getElementById(80 - first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : ' ';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function update_number_select(id){
    // Make sure the number select box doesn't go past the left/right edges.
    let xpos = document.getElementById(id).offsetLeft - 100 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    let number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top  =
      (document.getElementById(id).offsetTop  - 50 - window.pageYOffset)
      + 'px';
}
<commit_msg>reduced dom checks, improved formatting<commit_after>'use strict';

function check(){
    // Check if every button has correct solution on it.
    let win = true;
    let loop_counter = 80;
    do{
        if(document.getElementById(loop_counter).value != puzzle[loop_counter]){
            win = false;
            break;
        }
    }while(loop_counter--);

    window.alert(
      win
        ? 'Correct! You win!'
        : 'Incorrect, try again.'
    );
}

function display_number_select(id){
    // Reset button zIndex values.
    let loop_counter = 80;
    do{
        document.getElementById(loop_counter).style.zIndex = 0;
    }while(loop_counter--);

    if(selected_button === -1
      || selected_button != id){
        selected_button = id;

        // Increase zIndex of selected button.
        document.getElementById(selected_button).style.zIndex = 2;

        // Display number-select behind selected button.
        update_number_select(id);
        document.getElementById('number-select').style.display = 'block';

    }else{
        // Hide number select.
        selected_button = -1;
        document.getElementById('number-select').style.display = 'none';
    }
}

function generate_puzzle(){
    core_storage_save();

    let first = 0;
    let second = 0;
    let which = 0;

    // Base sudoku puzzle.
    puzzle = [
      8,7,6, 5,4,3, 2,1,9,
      5,4,3, 2,1,9, 8,7,6,
      2,1,9, 8,7,6, 5,4,3,

      7,6,5, 4,3,2, 1,9,8,
      4,3,2, 1,9,8, 7,6,5,
      1,9,8, 7,6,5, 4,3,2,

      6,5,4, 3,2,1, 9,8,7,
      3,2,1, 9,8,7, 6,5,4,
      9,8,7, 6,5,4, 3,2,1,
    ];

    // Switch all instances of two random numbers 100 times.
    let loop_counter = 99;
    do{
        // Pick two different numbers between 1 and 9.
        first = core_random_integer({
          'max': 9,
          'todo': 'ceil',
        });
        do{
            second = core_random_integer({
              'max': 9,
              'todo': 'ceil',
            });
        }while(first === second);

        // Iterate through all buttons and switch those two numbers.
        let times = 80;
        do{
            if(puzzle[times] === first){
                puzzle[times] = second;

            }else if(puzzle[times] === second){
                puzzle[times] = first;
            }
        }while(times--);
    }while(loop_counter--);

    // Switch columns between different blocks of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick a column number to switch.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different blocks of 3 columns to switch the selected column number between.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value in the selected column.
        // Swap them between the two selected blocks of 3 columns.
        let times = 8;
        do{
            let temp = puzzle[9 * times + 3 * first + which];
            puzzle[9 * times + 3 * first + which] = puzzle[9 * times + 3 * second + which];
            puzzle[9 * times + 3 * second + which] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch columns within a block of 3 columns 100 times.
    loop_counter = 99;
    do{
        // Pick the block of 3 columns in which to switch two columns.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different columns to switch.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected columns.
        let times = 8;
        do{
            let temp = puzzle[9 * times + 3 * which + first];
            puzzle[9 * times + 3 * which + first] = puzzle[9 * times + 3 * which + second];
            puzzle[9 * times + 3 * which + second] = temp;
        }while(times--);
    }while(loop_counter--);

    // Switch random rows within a block of 3 rows 100 times.
    loop_counter = 99;
    do{
        // Pick one of the 3 blocks of 3 rows.
        which = core_random_integer({
          'max': 3,
        });

        // Pick two different rows.
        first = core_random_integer({
          'max': 3,
        });
        do{
            second = core_random_integer({
              'max': 3,
            });
        }while(first === second);

        // Iterate through each value and swap the values between the two selected rows.
        let times = 8;
        do{
            let temp = puzzle[which * 27 + first * 9 + times];
            puzzle[which * 27 + first * 9 + times] = puzzle[which * 27 + second * 9 + times];
            puzzle[which * 27 + second * 9 + times] = temp;
        }while(times--);
    }while(loop_counter--);

    // Reset all buttons.
    loop_counter = 80;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = false;
        element.style.background = '#333';
        element.style.color = '#aaa';
        element.style.position = 'relative';
        element.value = ' ';
    }while(loop_counter--);

    // Add solutions to some random buttons.
    loop_counter = core_storage_data['locked'] - 1;
    if(loop_counter >= 0){
        do{
            first = core_random_integer({
              'max': 81,
            });
            let element = document.getElementById(first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[first];

            element = document.getElementById(80 - first);
            element.disabled = true;
            element.style.background = '#777';
            element.style.color = '#000';
            element.value = puzzle[80 - first];
        }while(loop_counter--);
    }
}

function select_number(number){
    document.getElementById(selected_button).value = number > 0
      ? number
      : ' ';
    selected_button = -1;
    document.getElementById('number-select').style.display = 'none';
}

function update_number_select(id){
    let element = document.getElementById(id);

    // Make sure the number select box doesn't go past the left/right edges.
    let xpos = element.offsetLeft - 100 - window.pageXOffset;
    if(xpos < 0){
        xpos = 0;

    }else if(xpos > window.innerWidth - 150){
        xpos = window.innerWidth - 150;
    }

    let number_select = document.getElementById('number-select');
    number_select.style.left = xpos + 'px';

    // There is no worry of the number select box going past the top/bottom edges.
    number_select.style.top = (element.offsetTop  - 50 - window.pageYOffset) + 'px';
}
<|endoftext|>