<commit_before>/**
 * Yii GridView widget.
 *
 * This is the JavaScript widget used by the yii\grid\GridView widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	$.fn.yiiGridView = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
			return false;
		}
	};

	var defaults = {
		filterUrl: undefined,
		filterSelector: undefined
	};

	var gridData = {};

	var methods = {
		init: function (options) {
			return this.each(function () {
				var $e = $(this);
				var settings = $.extend({}, defaults, options || {});
				gridData[$e.prop('id')] = {settings: settings};

				var enterPressed = false;
				$(document).off('change.yiiGridView keydown.yiiGridView', settings.filterSelector)
					.on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) {
					if (event.type === 'keydown') {
						if (event.keyCode !== 13) {
							return; // only react to enter key
						} else {
							enterPressed = true;
						}
					} else {
						// prevent processing for both keydown and change events
						if (enterPressed) {
							enterPressed = false;
							return;
						}
					}

					methods.applyFilter.apply($e);

					return false;
				});
			});
		},

		applyFilter: function () {
			var $grid = $(this);
			var settings = gridData[$grid.prop('id')].settings;
			var data = {};
			$.each($(settings.filterSelector).serializeArray(), function () {
				data[this.name] = this.value;
			});

			$.each(yii.getQueryParams(settings.filterUrl), function (name, value) {
				if (data[name] === undefined) {
					data[name] = value;
				}
			});

			var pos = settings.filterUrl.indexOf('?');
			var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos);

			$grid.find('form.gridview-filter-form').remove();
			var $form = $('<form action="' + url + '" method="get" class="gridview-filter-form" style="display:none" data-pjax></form>').appendTo($grid);
			$.each(data, function (name, value) {
				$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
			});
			$form.submit();
		},

		setSelectionColumn: function (options) {
			var $grid = $(this);
			var id = $(this).prop('id');
			gridData[id].selectionColumn = options.name;
			if (!options.multiple) {
				return;
			}
			var inputs = "#" + id + " input[name='" + options.checkAll + "']";
			$(document).off('click.yiiGridView', inputs).on('click.yiiGridView', inputs, function () {
				$grid.find("input[name='" + options.name + "']:enabled").prop('checked', this.checked);
			});
			$(document).off('click.yiiGridView', inputs + ":enabled").on('click.yiiGridView', inputs + ":enabled", function () {
				var all = $grid.find("input[name='" + options.name + "']").length == $grid.find("input[name='" + options.name + "']:checked").length;
				$grid.find("input[name='" + options.checkAll + "']").prop('checked', all);
			});
		},

		getSelectedRows: function () {
			var $grid = $(this);
			var data = gridData[$grid.prop('id')];
			var keys = [];
			if (data.selectionColumn) {
				$grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () {
					keys.push($(this).parent().closest('tr').data('key'));
				});
			}
			return keys;
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiGridView');
				$(this).removeData('yiiGridView');
			});
		},

		data: function () {
			return this.data('yiiGridView');
		}
	};
})(window.jQuery);

<commit_msg>return data from module scope variable<commit_after>/**
 * Yii GridView widget.
 *
 * This is the JavaScript widget used by the yii\grid\GridView widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	$.fn.yiiGridView = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
			return false;
		}
	};

	var defaults = {
		filterUrl: undefined,
		filterSelector: undefined
	};

	var gridData = {};

	var methods = {
		init: function (options) {
			return this.each(function () {
				var $e = $(this);
				var settings = $.extend({}, defaults, options || {});
				gridData[$e.prop('id')] = {settings: settings};

				var enterPressed = false;
				$(document).off('change.yiiGridView keydown.yiiGridView', settings.filterSelector)
					.on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) {
					if (event.type === 'keydown') {
						if (event.keyCode !== 13) {
							return; // only react to enter key
						} else {
							enterPressed = true;
						}
					} else {
						// prevent processing for both keydown and change events
						if (enterPressed) {
							enterPressed = false;
							return;
						}
					}

					methods.applyFilter.apply($e);

					return false;
				});
			});
		},

		applyFilter: function () {
			var $grid = $(this);
			var settings = gridData[$grid.prop('id')].settings;
			var data = {};
			$.each($(settings.filterSelector).serializeArray(), function () {
				data[this.name] = this.value;
			});

			$.each(yii.getQueryParams(settings.filterUrl), function (name, value) {
				if (data[name] === undefined) {
					data[name] = value;
				}
			});

			var pos = settings.filterUrl.indexOf('?');
			var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos);

			$grid.find('form.gridview-filter-form').remove();
			var $form = $('<form action="' + url + '" method="get" class="gridview-filter-form" style="display:none" data-pjax></form>').appendTo($grid);
			$.each(data, function (name, value) {
				$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
			});
			$form.submit();
		},

		setSelectionColumn: function (options) {
			var $grid = $(this);
			var id = $(this).prop('id');
			gridData[id].selectionColumn = options.name;
			if (!options.multiple) {
				return;
			}
			var inputs = "#" + id + " input[name='" + options.checkAll + "']";
			$(document).off('click.yiiGridView', inputs).on('click.yiiGridView', inputs, function () {
				$grid.find("input[name='" + options.name + "']:enabled").prop('checked', this.checked);
			});
			$(document).off('click.yiiGridView', inputs + ":enabled").on('click.yiiGridView', inputs + ":enabled", function () {
				var all = $grid.find("input[name='" + options.name + "']").length == $grid.find("input[name='" + options.name + "']:checked").length;
				$grid.find("input[name='" + options.checkAll + "']").prop('checked', all);
			});
		},

		getSelectedRows: function () {
			var $grid = $(this);
			var data = gridData[$grid.prop('id')];
			var keys = [];
			if (data.selectionColumn) {
				$grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () {
					keys.push($(this).parent().closest('tr').data('key'));
				});
			}
			return keys;
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiGridView');
				$(this).removeData('yiiGridView');
			});
		},

		data: function () {
			var id = $(this).prop('id');
			return gridData[id];
		}
	};
})(window.jQuery);

<|endoftext|>


<commit_before>'use strict';

const nock = require('nock');
const swagger = require('./apiserver-swagger.json');
const apiserver = require('../../eventmesh').server;
const apiServerHost = 'https://127.0.0.1:9443';
const lib = require('../../broker/lib');
const logger = lib.logger;

const sampleLockResource = {
  kind: 'DeploymentLock',
  apiVersion: 'lock.servicefabrik.io/v1alpha1',
  metadata: {
    name: 'l1',
    namespace: 'default',
    selfLink: '/apis/lock.servicefabrik.io/v1alpha1/namespaces/default/deploymentlocks/l1',
    uid: '54e02d6c-72b6-11e8-80fe-9801a7b45ddd',
    resourceVersion: '1076',
    generation: 1,
    creationTimestamp: '2018-06-18T05:13:26Z'
  },
  spec: {
    options: 'sample_options'
  },
  status: {}
}

const sampleDeploymentResource = {
  kind: 'Director',
  apiVersion: 'deployment.servicefabrik.io/v1alpha1',
  metadata: {
    name: 'd1',
    namespace: 'default',
    selfLink: '/apis/deployment.servicefabrik.io/v1alpha1/namespaces/default/directors/d1',
    uid: '54e02d6c-72b6-11e8-80fe-9801a7b45ddd',
    resourceVersion: '1076',
    generation: 1,
    creationTimestamp: '2018-06-18T05:13:26Z'
  },
  spec: {
    options: 'sample_options'
  },
  status: {}
}

function verify() {
  /* jshint expr:true */
  if (!nock.isDone()) {
    console.log('pending mocks: %j', nock.pendingMocks());
    logger.error('pending mocks: %j', nock.pendingMocks());
  }
  expect(nock.isDone()).to.be.true;
}

function nockGetResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .get(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

function nockPatchResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .patch(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

function nockCreateResource(resourceGroup, resourceType, response) {
  nock(apiServerHost)
    .post(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s`)
    .reply(201, response);
}

function nockDeleteResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .delete(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

describe('eventmesh', () => {
  describe('ApiServerEventMesh', () => {
    beforeEach(() => {
      nock(apiServerHost)
        .get('/swagger.json')
        .reply(200, swagger);
    });

    afterEach(() => {
      nock.cleanAll();
    })

    describe('registerWatcher', () => {
      it('returns the specified resource', () => {

      });
    });

    describe('createLockResource', () => {
      it('calls the post rest api to create lock type resource', done => {
        nockCreateResource('lock', 'deploymentlock', sampleLockResource);
        apiserver.createLockResource('lock', 'deploymentlock', sampleLockResource)
          .then(res => {
            expect(res.statusCode).to.eql(201);
            expect(res.body).to.eql(sampleLockResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('deleteLockResource', () => {
      it('calls the delete rest api to delete lock type resource', done => {
        const deleteLockResponse = {
          kind: 'Status',
          apiVersion: 'v1',
          metadata: {},
          status: 'Success',
          details: {
            name: 'l1',
            group: 'lock.servicefabrik.io',
            kind: 'deploymentlocks',
            uid: '3576eca0-72b7-11e8-80fe-9801a7b45ddd'
          }
        }
        nockDeleteResource('lock', 'deploymentlock', 'l1', deleteLockResponse);
        apiserver.deleteLockResource('lock', 'deploymentlock', 'l1')
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(deleteLockResponse);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('updateLockResource', () => {
      it('calls the patch rest api to edit lock type resource', done => {
        nockPatchResource('lock', 'deploymentlock', 'l1', sampleLockResource);
        apiserver.updateLockResource('lock', 'deploymentlock', 'l1', {
            spec: {
              options: sampleLockResource.spec.options
            }
          })
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(sampleLockResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('getLockResourceOptions', () => {
      it('returns options of the lock resource', done => {
        nockGetResource('lock', 'deploymentlock', 'l1', sampleLockResource);
        apiserver.getLockResourceOptions('lock', 'deploymentlock', 'l1')
          .then(res => {
            expect(res).to.eql(sampleLockResource.spec.options);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('getResource', () => {
      it('returns the specified resource', done => {
        nockGetResource('deployment', 'director', 'd1', sampleDeploymentResource);
        apiserver.getResource('deployment', 'director', 'd1')
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(sampleDeploymentResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('createResource', () => {

    });

    describe('updateResourceState', () => {

    });

    describe('getResourceState', () => {

    });

    describe('annotateResource', () => {

    });

    describe('updateAnnotationResult', () => {

    });

    describe('updateAnnotationState', () => {

    });

    describe('updateLastAnnotation', () => {

    });

    describe('getLastAnnotation', () => {

    });

    describe('getAnnotationOptions', () => {

    });

    describe('getAnnotationState', () => {

    });

    describe('getAnnotationResult', () => {

    });

  });
});<commit_msg>Adding new testcases<commit_after>'use strict';

const nock = require('nock');
const swagger = require('./apiserver-swagger.json');
const apiserver = require('../../eventmesh').server;
const apiServerHost = 'https://10.0.2.2:9443';
const lib = require('../../broker/lib');
const logger = lib.logger;

const sampleLockResource = {
  kind: 'DeploymentLock',
  apiVersion: 'lock.servicefabrik.io/v1alpha1',
  metadata: {
    name: 'l1',
    namespace: 'default',
    selfLink: '/apis/lock.servicefabrik.io/v1alpha1/namespaces/default/deploymentlocks/l1',
    uid: '54e02d6c-72b6-11e8-80fe-9801a7b45ddd',
    resourceVersion: '1076',
    generation: 1,
    creationTimestamp: '2018-06-18T05:13:26Z'
  },
  spec: {
    options: 'sample_options'
  },
  status: {}
}

const sampleDeploymentResource = {
  kind: 'Director',
  apiVersion: 'deployment.servicefabrik.io/v1alpha1',
  metadata: {
    name: 'd1',
    namespace: 'default',
    selfLink: '/apis/deployment.servicefabrik.io/v1alpha1/namespaces/default/directors/d1',
    uid: '54e02d6c-72b6-11e8-80fe-9801a7b45ddd',
    resourceVersion: '1076',
    generation: 1,
    creationTimestamp: '2018-06-18T05:13:26Z'
  },
  spec: {
    options: 'sample_options'
  },
  status: {
    state: 'in_progress'
  }
}

function verify() {
  /* jshint expr:true */
  if (!nock.isDone()) {
    console.log('pending mocks: %j', nock.pendingMocks());
    logger.error('pending mocks: %j', nock.pendingMocks());
  }
  expect(nock.isDone()).to.be.true;
}

function nockGetResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .get(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

function nockPatchResourceStatus(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .patch(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}/status`)
    .reply(200, response);
}

function nockPatchResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .patch(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

function nockCreateResource(resourceGroup, resourceType, response) {
  nock(apiServerHost)
    .post(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s`)
    .reply(201, response);
}

function nockDeleteResource(resourceGroup, resourceType, id, response) {
  nock(apiServerHost)
    .delete(`/apis/${resourceGroup}.servicefabrik.io/v1alpha1/namespaces/default/${resourceType}s/${id}`)
    .reply(200, response);
}

describe('eventmesh', () => {
  describe('ApiServerEventMesh', () => {
    beforeEach(() => {
      nock(apiServerHost)
        .get('/swagger.json')
        .reply(200, swagger);
    });

    afterEach(() => {
      nock.cleanAll();
    })

    describe('registerWatcher', () => {
      it('returns the specified resource', () => {

      });
    });

    describe('createLockResource', () => {
      it('calls the post rest api to create lock type resource', done => {
        nockCreateResource('lock', 'deploymentlock', sampleLockResource);
        apiserver.createLockResource('lock', 'deploymentlock', sampleLockResource)
          .then(res => {
            expect(res.statusCode).to.eql(201);
            expect(res.body).to.eql(sampleLockResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('deleteLockResource', () => {
      it('calls the delete rest api to delete lock type resource', done => {
        const deleteLockResponse = {
          kind: 'Status',
          apiVersion: 'v1',
          metadata: {},
          status: 'Success',
          details: {
            name: 'l1',
            group: 'lock.servicefabrik.io',
            kind: 'deploymentlocks',
            uid: '3576eca0-72b7-11e8-80fe-9801a7b45ddd'
          }
        }
        nockDeleteResource('lock', 'deploymentlock', 'l1', deleteLockResponse);
        apiserver.deleteLockResource('lock', 'deploymentlock', 'l1')
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(deleteLockResponse);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('updateLockResource', () => {
      it('calls the patch rest api to edit lock type resource', done => {
        nockPatchResource('lock', 'deploymentlock', 'l1', sampleLockResource);
        apiserver.updateLockResource('lock', 'deploymentlock', 'l1', {
            spec: {
              options: sampleLockResource.spec.options
            }
          })
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(sampleLockResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('getLockResourceOptions', () => {
      it('returns options of the lock resource', done => {
        nockGetResource('lock', 'deploymentlock', 'l1', sampleLockResource);
        apiserver.getLockResourceOptions('lock', 'deploymentlock', 'l1')
          .then(res => {
            expect(res).to.eql(sampleLockResource.spec.options);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('getResource', () => {
      it('returns the specified resource', done => {
        nockGetResource('deployment', 'director', 'd1', sampleDeploymentResource);
        apiserver.getResource('deployment', 'director', 'd1')
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(sampleDeploymentResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('createResource', () => {

    });

    describe('updateResourceState', () => {
      it.only('updates the specified resource state', done => {
        nockPatchResourceStatus('deployment', 'director', 'd1', sampleDeploymentResource);
        apiserver.updateResourceState('director', 'd1', sampleDeploymentResource.status.state)
          .then(res => {
            expect(res.statusCode).to.eql(200);
            expect(res.body).to.eql(sampleDeploymentResource);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('getResourceState', () => {
      it('gets the specified resource state', done => {
        nockGetResource('deployment', 'director', 'd1', sampleDeploymentResource);
        apiserver.getResourceState('director', 'd1')
          .then(res => {
            expect(res).to.eql(sampleDeploymentResource.status.state);
            done();
            verify();
          })
          .catch(done);
      });
    });

    describe('annotateResource', () => {

    });

    describe('updateAnnotationResult', () => {

    });

    describe('updateAnnotationState', () => {

    });

    describe('updateLastAnnotation', () => {

    });

    describe('getLastAnnotation', () => {

    });

    describe('getAnnotationOptions', () => {

    });

    describe('getAnnotationState', () => {

    });

    describe('getAnnotationResult', () => {

    });

  });
});<|endoftext|>


<commit_before>(function(module) {
  var sortedByDistancePermits = [];
  // Permit constructor
  function Permit (opts) {
    for (keys in opts) {
      this[keys] = opts[keys];
    }
    this.URL = opts.permit_and_complaint_status_url.url;
  }

  Permit.all = [];

  Permit.getData = function(next) {
    webDB.execute('SELECT * FROM permitdata', function(rows) {
      if (rows.length) {
        map.fetchLocations('SELECT * FROM permitdata',next);
      } else {
        $.get('https://data.seattle.gov/resource/94s7-sxg7.json?$$app_token=gdkMQ6LU9xq4ZonjF6aDFun5l&$limit=1000&permit_type=Construction&action_type=NEW&$where=NOT%20status=%27Permit%20Closed%27', function(data) {
          Permit.all = data;
          if (!rows.length) {
            Permit.all.forEach(function(singlePermit) {
              var permit = new Permit(singlePermit);
              permit.insertPermit();
            });
          }
          map.fetchLocations('SELECT * FROM permitdata',next);
        });
      }
    });
  };

  Permit.createTable = function() {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS permitdata (' +
        'id INTEGER PRIMARY KEY, ' +
        'address VARCHAR(255) NOT NULL, ' +
        'applicant_name VARCHAR(255) NOT NULL, ' +
        'application_date DATE, ' +
        'application_permit_number INTEGER, ' +
        'category VARCHAR(20), ' +
        'contractor VARCHAR(100), ' +
        'description TEXT NOT NULL,' +
        'latitude FLOAT,' +
        'longitude FLOAT,' +
        'permit_and_complaint_status_url VARCHAR(512),' +
        'permit_type VARCHAR(100),' +
        'status VARCHAR(20),' +
        'value INTEGER);'

      // callback
    );
  };

  Permit.prototype.insertPermit = function () {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO permitdata(address, applicant_name, application_date, application_permit_number, category, contractor, description, latitude, longitude, permit_and_complaint_status_url, permit_type, status, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
          'data': [this.address, this.applicant_name, this.application_date, this.application_permit_number, this.category, this.contractor, this.description, this.latitude, this.longitude, this.URL, this.permit_type, this.status, this.value],
        }
      ]
    );
  };

  // Permit.createTable();
  // Permit.getData();

  module.Permit = Permit;
})(window);
<commit_msg>a bit of debugging I dont know if anything is fixed or broken more, pushing up so others can pull<commit_after>(function(module) {
  var sortedByDistancePermits = [];
  // Permit constructor
  function Permit (opts) {
    for (keys in opts) {
      this[keys] = opts[keys];
    }
    this.URL = opts.permit_and_complaint_status_url.url;
  }

  Permit.all = [];

  Permit.getData = function(next) {
    webDB.execute('SELECT * FROM permitdata', function(rows) {
      if (rows.length) {
        console.log('Permit.getData: inside if');
        map.fetchLocations('SELECT * FROM permitdata',next);
      } else {
        console.log('Permit.getData: inside else');
        //debugger;
        $.get('https://data.seattle.gov/resource/94s7-sxg7.json?$$app_token=gdkMQ6LU9xq4ZonjF6aDFun5l&$limit=3000&permit_type=Construction&action_type=NEW&$where=NOT%20status=%27Permit%20Closed%27', function(data) {
          Permit.all = data;
          if (!rows.length) {
            Permit.all.forEach(function(singlePermit) {
              var permit = new Permit(singlePermit);
              permit.insertPermit();
            });
          }
         map.fetchLocations('SELECT * FROM permitdata',next);
        });
      }
    });
  };

  Permit.createTable = function() {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS permitdata (' +
        'id INTEGER PRIMARY KEY, ' +
        'address VARCHAR(255) NOT NULL, ' +
        'applicant_name VARCHAR(255) NOT NULL, ' +
        'application_date DATE, ' +
        'application_permit_number INTEGER, ' +
        'category VARCHAR(20), ' +
        'contractor VARCHAR(100), ' +
        'description TEXT NOT NULL,' +
        'latitude FLOAT,' +
        'longitude FLOAT,' +
        'permit_and_complaint_status_url VARCHAR(512),' +
        'permit_type VARCHAR(100),' +
        'status VARCHAR(20),' +
        'value INTEGER);'

      // callback
    );
  };

  Permit.prototype.insertPermit = function () {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO permitdata(address, applicant_name, application_date, application_permit_number, category, contractor, description, latitude, longitude, permit_and_complaint_status_url, permit_type, status, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
          'data': [this.address, this.applicant_name, this.application_date, this.application_permit_number, this.category, this.contractor, this.description, this.latitude, this.longitude, this.URL, this.permit_type, this.status, this.value],
        }
      ]
    );
  };

  // Permit.createTable();
  // Permit.getData();

  module.Permit = Permit;
})(window);
<|endoftext|>


<commit_before>var Kaltura = require('./<%- Lucy.answer("libraryDirectory") || "lib/" %>KalturaClient.js');
var config = new Kaltura.KalturaConfiguration(<%- Lucy.answer('partnerId') %>);
config.serviceUrl = <%- Lucy.code.variable('answers.serviceURL') %>;
var client = new Kaltura.KalturaClient(config);
var sessionID = null;
client.session.start(function(ks) {
  if (ks.code && ks.message) {
    console.log('Error starting session', success, ks);
  } else {
    sessionID = ks;
    client.setKs(ks);
  }
}, <%- Lucy.variable("answers.secret") %>,
<%- Lucy.variable("answers.userId") %>,
<%- Lucy.answer('sessionType') === 0 ? 'Kaltura.enums.KalturaSessionType.USER' : 'Kaltura.enums.KalturaSessionType.ADMIN' %>,
<%- Lucy.variable('answers.partnerId') %>)

app.use(function(req, res, next) {
  res.locals = {
    ks: sessionID,
  }
  next();
})
<commit_msg>use node_modules dep<commit_after>var Kaltura = require('./node_modules/kaltura/KalturaClient.js');
var config = new Kaltura.KalturaConfiguration(<%- Lucy.answer('partnerId') %>);
config.serviceUrl = <%- Lucy.code.variable('answers.serviceURL') %>;
var client = new Kaltura.KalturaClient(config);
var sessionID = null;
client.session.start(function(ks) {
  if (ks.code && ks.message) {
    console.log('Error starting session', success, ks);
  } else {
    sessionID = ks;
    client.setKs(ks);
  }
}, <%- Lucy.variable("answers.secret") %>,
<%- Lucy.variable("answers.userId") %>,
<%- Lucy.answer('sessionType') === 0 ? 'Kaltura.enums.KalturaSessionType.USER' : 'Kaltura.enums.KalturaSessionType.ADMIN' %>,
<%- Lucy.variable('answers.partnerId') %>)

app.use(function(req, res, next) {
  res.locals = {
    ks: sessionID,
  }
  next();
})
<|endoftext|>


<commit_before>'use strict';
var RRDUtil = require('./util');
var util = require('util');
var net = require('net');

if(typeof String.prototype.startsWith === 'undefined'){
	String.prototype.startsWith = function(prefix) {
		return this.indexOf(prefix) === 0;
	}
};

var escapeRegExp = function(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var RRDCache = function(){
	var client = null;
	var buffer = '';
	var lastReply = null;
};

RRDCache.connect = function(address, callback){
	var self = this;
	if(typeof address === 'undefined'){
		address = 'unix:/tmp/rrdcached.sock';
	} else if (address === ''){
		address = ':42217';
	}
	var options = (address.startsWith('unix:/') ? {path: address.substring(5)} : {host: address.substring(0,address.indexOf(':')), port: address.substring(address.indexOf(':') + 1)});
	self.client = net.createConnection(options);
	self.client.on('connect', function() {
		this.setEncoding('ascii');
		callback();
	});
};

RRDCache.write = function(command, callback){
	var self = this;
	var status = null;
	if(self.client != null && command != null){
		command = command.trim();
		// append newline to terminate command
		if(command.substring(command.length - 1) != "\n"){
			command += "\n";
		}
		if(command === 'QUIT\n'){
			self.client.end(command, 'ascii');
		} else {
			self.client.write(command, 'ascii');
		}
		self.client.on('data', function(data){
			if(!self.buffer){
				self.buffer = "";
			}
			self.buffer += data;
			if(status == null){
				status = parseInt(self.buffer.substring(0, self.buffer.indexOf(' ')));
			}
			var receivedAll = status < 0 || ((self.buffer.match(/\n/g) || []).length == status + 1);
			if(receivedAll){
				self.buffer = "";
				status = null;
				callback(null, processData(data));
			}
		});
	} else {
		callback(new Error('Not Connected!'));
	}
};

var processData = function(data){
	var lines = data.split('\n');
	var statusIdx = lines[0].indexOf(' ');
	var status = parseInt(lines[0].substring(0, statusIdx));
	var error = status < 0 ? true : false;
	var info = Array();
	if(error == false){
		for(var i = 1; i < status; i++){
			info.push(lines[i]);
		}
	}
	RRDCache.lastReply = {
		statuscode: status,
		status: lines[0].substring(statusIdx + 1),
		error: error,
		info: info
	};
	return RRDCache.lastReply;
};

var replaceN = function(value){
	return value.replace(new RegExp(escapeRegExp('N'), 'g'), parseInt(Date.now()/1000));
}

RRDCache.flush = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("FLUSH %s", filename), callback);
};

RRDCache.flushall = function(callback){
	RRDCache.write("FLUSHALL", callback);
};

RRDCache.help = function(command, callback){
	RRDCache.write(util.format("HELP %s", command), callback);
};

RRDCache.pending = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("PENDING %s", filename), callback);
};

RRDCache.forget = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("FORGET %s", filename), callback);
};

RRDCache.queue = function(callback){
	RRDCache.write("QUEUE", function(err, reply){
		if(err){
			callback(err);
		}
		reply.queue = {};
		for(var line of reply.info){
			var split = line.split(" ");
			reply.queue[split[1]] = parseInt(split[0]);
		}
		callback(null, reply);
	});
};

RRDCache.stats = function(callback){
	RRDCache.write("STATS", function(err, reply){
		if(err){
			callback(err);
		}
		reply.stats = {};
		for(var line of reply.info){
			var split = line.split(": ");
			reply.stats[split[0]] = parseInt(split[1]);
		}
		callback(null, reply);
	});
};

RRDCache.ping = function(callback){
	RRDCache.write("PING", callback);
};

RRDCache.update = function(filename, values, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	var newValues = "";
	if(Array.isArray(values)){
		for(var v of values){
			if(Array.isArray(v)){
				newValues += v.join(":") + " ";
			} else {
				newValues += v + " ";
			}
		}
	} else {
		newValues = values;
	}
	RRDCache.write(util.format("UPDATE %s %s", filename, replaceN(newValues)), callback);
};

RRDCache.fetch = function(filename, consFunction, options, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	if(consFunction === undefined){
		callback(new Error("No consolidation function specified!"));
	}
	if(consFunction != "AVERAGE" && consFunction != "MIN" && consFunction != "MAX" && consFunction != "LAST"){
		callback(new Error("Invalid consolidation function. Choose one of AVERAGE, MIN, MAX, LAST."));
	}
	var resolution = options !== null && options.resolution !== undefined ? util.format("-r %s", options.resolution) : "";
	var start = options !== null && options.start !== undefined ? util.format("-s %s", options.resolution) : "";
	var end = options !== null && options.end !== undefined ? util.format("-e %s", options.end) : "";
	var align = options !== null && (options.alignStart !== undefined && options.alignStart || options.a !== undefined && options.a) ? "-a" : "";
	RRDCache.write(util.format("FETCH %s %s %s %s %s %s", filename, consFunction, resolution, start, end, align), callback);
};

RRDCache.first = function(){
	if(arguments.length >= 2 && arguments.length <=3){
		var filename = arguments[0];
		var rranum = arguments.length == 3 ? arguments[1] : 0;
		var callback = arguments.length == 3 ? arguments[2]: arguments[1];
		RRDCache.write(util.format("FIRST %s %d", filename, rranum), callback);
	} else {
		callback(new Error("Invalid number of arguments!"));
	}
};

RRDCache.last = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("LAST %s", filename), callback);
};

RRDCache.info = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("INFO %s", filename), callback);
};

RRDCache.create = function(filename, options, DSDefinitions, RRADefinitions, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	var stepsize = options !== null && options.stepsize !== undefined ? util.format("-s %d", options.stepsize) : "";
	var begintime = options !== null && options.begintime !== undefined ? util.format("-b %d", options.begintime) : "";
	var o = options !== null && options.o !== undefined && options.o ? "-O" : "";
	RRDCache.write(util.format("CREATE %s %s %s %s %s %s", filename, stepsize, begintime, o, DSDefinitions, RRADefinitions), callback);
};

RRDCache.batch = function(commands, callback){
	if(Array.isArray(commands)){
		var command = "BATCH\n";
		for(var c of commands){
			command += c + "\n";
		}
		command += ".";
		RRDCache.write(command, callback);
	}
};

RRDCache.quit = function(callback){
	RRDCache.write("QUIT", callback);
};

RRDCache.getLastReply = function(){
	return this.lastReply;
};

RRDCache.util = RRDUtil;
module.exports = RRDCache;
<commit_msg>added parsing of FETCH reply<commit_after>'use strict';
var RRDUtil = require('./util');
var util = require('util');
var net = require('net');

if(typeof String.prototype.startsWith === 'undefined'){
	String.prototype.startsWith = function(prefix) {
		return this.indexOf(prefix) === 0;
	}
};

var escapeRegExp = function(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var RRDCache = function(){
	var client = null;
	var buffer = '';
	var lastReply = null;
};

RRDCache.connect = function(address, callback){
	var self = this;
	if(typeof address === 'undefined'){
		address = 'unix:/tmp/rrdcached.sock';
	} else if (address === ''){
		address = ':42217';
	}
	var options = (address.startsWith('unix:/') ? {path: address.substring(5)} : {host: address.substring(0,address.indexOf(':')), port: address.substring(address.indexOf(':') + 1)});
	self.client = net.createConnection(options);
	self.client.on('connect', function() {
		this.setEncoding('ascii');
		callback();
	});
};

RRDCache.write = function(command, callback){
	var self = this;
	var status = null;
	if(self.client != null && command != null){
		command = command.trim();
		// append newline to terminate command
		if(command.substring(command.length - 1) != "\n"){
			command += "\n";
		}
		if(command === 'QUIT\n'){
			self.client.end(command, 'ascii');
		} else {
			self.client.write(command, 'ascii');
		}
		self.client.on('data', function(data){
			if(!self.buffer){
				self.buffer = "";
			}
			self.buffer += data;
			if(status == null){
				status = parseInt(self.buffer.substring(0, self.buffer.indexOf(' ')));
			}
			var receivedAll = status < 0 || ((self.buffer.match(/\n/g) || []).length == status + 1);
			if(receivedAll){
				self.buffer = "";
				status = null;
				callback(null, processData(data));
			}
		});
	} else {
		callback(new Error('Not Connected!'));
	}
};

var processData = function(data){
	var lines = data.split('\n');
	var statusIdx = lines[0].indexOf(' ');
	var status = parseInt(lines[0].substring(0, statusIdx));
	var error = status < 0 ? true : false;
	var info = Array();
	if(error == false){
		for(var i = 1; i < status; i++){
			info.push(lines[i]);
		}
	}
	RRDCache.lastReply = {
		statuscode: status,
		status: lines[0].substring(statusIdx + 1),
		error: error,
		info: info
	};
	return RRDCache.lastReply;
};

var replaceN = function(value){
	return value.replace(new RegExp(escapeRegExp('N'), 'g'), parseInt(Date.now()/1000));
}

RRDCache.flush = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("FLUSH %s", filename), callback);
};

RRDCache.flushall = function(callback){
	RRDCache.write("FLUSHALL", callback);
};

RRDCache.help = function(command, callback){
	RRDCache.write(util.format("HELP %s", command), callback);
};

RRDCache.pending = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("PENDING %s", filename), callback);
};

RRDCache.forget = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("FORGET %s", filename), callback);
};

RRDCache.queue = function(callback){
	RRDCache.write("QUEUE", function(err, reply){
		if(err){
			callback(err);
		}
		reply.queue = {};
		for(var line of reply.info){
			var split = line.split(" ");
			reply.queue[split[1]] = parseInt(split[0]);
		}
		callback(null, reply);
	});
};

RRDCache.stats = function(callback){
	RRDCache.write("STATS", function(err, reply){
		if(err){
			callback(err);
		}
		reply.stats = {};
		for(var line of reply.info){
			var split = line.split(": ");
			reply.stats[split[0]] = parseInt(split[1]);
		}
		callback(null, reply);
	});
};

RRDCache.ping = function(callback){
	RRDCache.write("PING", callback);
};

RRDCache.update = function(filename, values, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	var newValues = "";
	if(Array.isArray(values)){
		for(var v of values){
			if(Array.isArray(v)){
				newValues += v.join(":") + " ";
			} else {
				newValues += v + " ";
			}
		}
	} else {
		newValues = values;
	}
	RRDCache.write(util.format("UPDATE %s %s", filename, replaceN(newValues)), callback);
};

RRDCache.fetch = function(filename, consFunction, options, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	if(consFunction === undefined){
		callback(new Error("No consolidation function specified!"));
	}
	if(consFunction != "AVERAGE" && consFunction != "MIN" && consFunction != "MAX" && consFunction != "LAST"){
		callback(new Error("Invalid consolidation function. Choose one of AVERAGE, MIN, MAX, LAST."));
	}
	var resolution = options !== null && options.resolution !== undefined ? util.format("-r %s", options.resolution) : "";
	var start = options !== null && options.start !== undefined ? util.format("-s %s", options.resolution) : "";
	var end = options !== null && options.end !== undefined ? util.format("-e %s", options.end) : "";
	var align = options !== null && (options.alignStart !== undefined && options.alignStart || options.a !== undefined && options.a) ? "-a" : "";
	RRDCache.write(util.format("FETCH %s %s %s %s %s %s", filename, consFunction, resolution, start, end, align), function(err, reply){
		if(err){
			callback(err);
		}
		reply.fetch = {};
		var columns = Array();
		for(var line of reply.info){
			if(line.trim() === ""){
				continue;
			}
			var split = line.split(": ");
			if(split.length == 1){
				for(var col of split[0].trim().split(" ")){
					columns.push(col);
				}
			} else {
				var insert = {};
				insert.date = new Date(split[0] * 1000);
				if(columns.length > 0){
					insert.data = {};
					var values = split[1].split(" ");
					for(var i; i < values; i++){
						insert.data[columns[i]] = values[i];
					}
				} else {
					insert.data = Array();
					for(var value of split[1].split(" ")){
						insert.data.push(value);
					}
				}
				reply.fetch[split[0]] = insert;
			}
		}
		callback(null, reply);
	});
};

RRDCache.first = function(){
	if(arguments.length >= 2 && arguments.length <=3){
		var filename = arguments[0];
		var rranum = arguments.length == 3 ? arguments[1] : 0;
		var callback = arguments.length == 3 ? arguments[2]: arguments[1];
		RRDCache.write(util.format("FIRST %s %d", filename, rranum), callback);
	} else {
		callback(new Error("Invalid number of arguments!"));
	}
};

RRDCache.last = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("LAST %s", filename), callback);
};

RRDCache.info = function(filename, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	RRDCache.write(util.format("INFO %s", filename), callback);
};

RRDCache.create = function(filename, options, DSDefinitions, RRADefinitions, callback){
	if(filename === undefined){
		callback(new Error("No filename specified!"));
	}
	var stepsize = options !== null && options.stepsize !== undefined ? util.format("-s %d", options.stepsize) : "";
	var begintime = options !== null && options.begintime !== undefined ? util.format("-b %d", options.begintime) : "";
	var o = options !== null && options.o !== undefined && options.o ? "-O" : "";
	RRDCache.write(util.format("CREATE %s %s %s %s %s %s", filename, stepsize, begintime, o, DSDefinitions, RRADefinitions), callback);
};

RRDCache.batch = function(commands, callback){
	if(Array.isArray(commands)){
		var command = "BATCH\n";
		for(var c of commands){
			command += c + "\n";
		}
		command += ".";
		RRDCache.write(command, callback);
	}
};

RRDCache.quit = function(callback){
	RRDCache.write("QUIT", callback);
};

RRDCache.getLastReply = function(){
	return this.lastReply;
};

RRDCache.util = RRDUtil;
module.exports = RRDCache;
<|endoftext|>


<commit_before>/*! correctingInterval 1.0.0 | Copyright 2013 Andrew Duthie | MIT License */
;(function(global, factory) {
  // Use UMD pattern to expose exported functions
  if (typeof exports === 'object') {
    // Expose to Node.js
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    // Expose to RequireJS
    define([], factory);
  } else {
    // Expose to global object (likely browser window)
    var exports = factory();
    for (var prop in exports) {
      global[prop] = exports[prop];
    }
  }
}(this, function() {
  // Track running intervals
  var correctingIntervals = [];

  var setCorrectingInterval = (function() {
    // Create closure to save instance settings
    var instance = { };

    // Save to global running intervals
    instance.guid = correctingIntervals.length;
    correctingIntervals.push(instance);

    // Polyfill Date.now
    var now = Date.now || function() {
      return new Date().valueOf();
    };

    var tick = function(func, delay) {
      if (!instance.started) {
        // On first call, save instance settings
        instance.func = func;
        instance.delay = delay;
        instance.startTime = now();
        instance.target = delay;
        instance.started = true;
        instance.intervalId = setTimeout.apply(this, [ tick ].concat([].slice.call(arguments, 1)));
        return instance.guid;
      } else {
        // On subsequent iterations, adjust timeout to correct for latency
        var elapsed = now() - instance.startTime,
          adjust = instance.target - elapsed,
          args = [].slice.call(arguments),
          timeoutArgs = [ tick, instance.delay + adjust ].concat(args);

        instance.func.apply(this, args);
        instance.target += instance.delay;
        instance.intervalId = setTimeout.apply(this, timeoutArgs);
      }
    };

    return tick;
  }());

  var clearCorrectingInterval = function(intervalId) {
    // Clear existing timeout and remove from global running intervals
    clearTimeout(correctingIntervals[intervalId].intervalId);
    correctingIntervals.splice(intervalId, 1);
  };

  return {
    setCorrectingInterval: setCorrectingInterval,
    clearCorrectingInterval: clearCorrectingInterval
  };
}));<commit_msg>Move Date.now polyfill outside function call<commit_after>/*! correctingInterval 1.0.0 | Copyright 2013 Andrew Duthie | MIT License */
;(function(global, factory) {
  // Use UMD pattern to expose exported functions
  if (typeof exports === 'object') {
    // Expose to Node.js
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    // Expose to RequireJS
    define([], factory);
  } else {
    // Expose to global object (likely browser window)
    var exports = factory();
    for (var prop in exports) {
      global[prop] = exports[prop];
    }
  }
}(this, function() {
  // Track running intervals
  var correctingIntervals = [];

  // Polyfill Date.now
  var now = Date.now || function() {
    return new Date().valueOf();
  };

  var setCorrectingInterval = (function() {
    // Create closure to save instance settings
    var instance = { };

    // Save to global running intervals
    instance.guid = correctingIntervals.length;
    correctingIntervals.push(instance);

    var tick = function(func, delay) {
      if (!instance.started) {
        // On first call, save instance settings
        instance.func = func;
        instance.delay = delay;
        instance.startTime = now();
        instance.target = delay;
        instance.started = true;
        instance.intervalId = setTimeout.apply(this, [ tick ].concat([].slice.call(arguments, 1)));
        return instance.guid;
      } else {
        // On subsequent iterations, adjust timeout to correct for latency
        var elapsed = now() - instance.startTime,
          adjust = instance.target - elapsed,
          args = [].slice.call(arguments),
          timeoutArgs = [ tick, instance.delay + adjust ].concat(args);

        instance.func.apply(this, args);
        instance.target += instance.delay;
        instance.intervalId = setTimeout.apply(this, timeoutArgs);
      }
    };

    return tick;
  }());

  var clearCorrectingInterval = function(intervalId) {
    // Clear existing timeout and remove from global running intervals
    clearTimeout(correctingIntervals[intervalId].intervalId);
    correctingIntervals.splice(intervalId, 1);
  };

  return {
    setCorrectingInterval: setCorrectingInterval,
    clearCorrectingInterval: clearCorrectingInterval
  };
}));<|endoftext|>


<commit_before>import React from "react";
import { render } from "react-dom";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle, Text
} from "src";

import preloader from "src/utils/preloader";

import Interactive from "assets/interactive";

require("normalize.css");
require("src/themes/default/index.css");

const slideTransition = ['zoom', 'fade'];
const images = {
  javascript: require("assets/javascript.jpg"),
  javascript2: require("assets/javascript2.jpg"),
  logo: require("assets/logo.png"),
  kanban: require("assets/kanban.gif"),
  moduleCounts: require("assets/module_counts.png"),
  redmonk: require("assets/redmonk.png"),
  jobs: require("assets/jobs.png"),
  jobTitles: require("assets/jobTitles.png"),
  jackie: require("assets/jackie.png"),
};

preloader([images.moduleCounts, images.redmonk, images.jobs]);

render(
  <Spectacle>
    <Deck transition={slideTransition} transitionDuration={500}>
      <Slide transition={["zoom"]} bgColor="primary">
        <Heading size={1} fit caps lineHeight={1} textColor="black">
          How to write a book and
        </Heading>
        <Heading size={1} fit>
          SurviveJS it
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Amazing growth rate.

At this rate bigger than others combined.

">
        <Heading size={1} textColor="tertiary">
          Module Counts
        </Heading>
        <Layout>
          <Image src={images.moduleCounts.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.modulecounts.com/">modulecounts.com</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Popular

Same goes for AltJS

">
        <Layout>
          <Link href="http://redmonk.com/jgovernor/2015/07/31/programming-language-rankings-summer-2015/">
            <Image src={images.redmonk.replace("/", "")} />
          </Link>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Angular dominates the work market.

Early signs of React.

">
        <Heading size={1} textColor="tertiary">
          Job Trends
        </Heading>
        <Layout>
          <Image src={images.jobs.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.indeed.com/jobtrends?q=Angularjs%2C+React.js%2C+Knockout%2C+Backbone.js&l=">Indeed</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Also job titles change.

Increasing demand for full stack developers.

">
        <Heading size={1} textColor="tertiary">
          Job Trends II
        </Heading>
        <Layout>
          <Image src={images.jobTitles.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.indeed.com/jobanalytics/jobtrends?q=frontend%2C+backend%2C+full+stack&l=">Indeed</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.javascript.replace("/", "")} margin="0px auto 40px" height="650px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.jackie.replace("/", "")} margin="0px auto 40px" height="381px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.javascript2.replace("/", "")} margin="0px auto 40px" height="650px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="white" notes="">
        <Image src={images.logo.replace("/", "")} margin="0px auto 40px" height="566px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit caps lineHeight={1} textColor="black">
          SurviveJS
        </Heading>
        <Heading size={1} fit>
          Webpack and React
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.kanban.replace("/", "")} margin="0px auto 40px" height="279px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          @survivejs
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          Quora
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          <Link href="http://www.reactindiebundle.com/">React Indie Bundle</Link>
        </Heading>
      </Slide>

      <Slide transition={["slide"]} bgDarken={0.75}>
        <Appear fid="1">
          <Heading size={1} caps fit textColor="primary">
            Full Width
          </Heading>
        </Appear>
        <Appear fid="2">
          <Heading size={1} caps fit textColor="tertiary">
            Adjustable Darkness
          </Heading>
        </Appear>
        <Appear fid="3">
          <Heading size={1} caps fit textColor="primary">
            Background Imagery
          </Heading>
        </Appear>
      </Slide>

      <Slide transition={["zoom", "fade"]} bgColor="primary">
        <Heading caps fit>Flexible Layouts</Heading>
        <Layout>
          <Fill>
            <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
              Left
            </Heading>
          </Fill>
          <Fill>
            <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
              Right
            </Heading>
          </Fill>
        </Layout>
      </Slide>

      <Slide transition={["slide"]} bgColor="black">

          <Quote>Wonderfully formatted quotes</Quote>
          Ken Wheeler

      </Slide>

      <Slide transition={["spin", "zoom"]} bgColor="tertiary">
        <Heading caps fit size={1} textColor="primary">
          Inline Markdown
        </Heading>
        <Markdown>
          {`
You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And lets not forget **bold**
          `}
        </Markdown>
      </Slide>

      <Slide transition={["slide", "spin"]} bgColor="primary">
        <Heading caps fit size={1} textColor="tertiary">
          Smooth
        </Heading>
        <Heading caps fit size={1} textColor="secondary">
          Combinable Transitions
        </Heading>
      </Slide>

      <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
        <List>
          <ListItem><Appear fid="1">Inline style based theme system</Appear></ListItem>
          <ListItem><Appear fid="2">Autofit text</Appear></ListItem>
          <ListItem><Appear fid="3">Flexbox layout system</Appear></ListItem>
          <ListItem><Appear fid="4">React-Router navigation</Appear></ListItem>
          <ListItem><Appear fid="5">PDF export</Appear></ListItem>
          <ListItem><Appear fid="6">And...</Appear></ListItem>
        </List>
      </Slide>

      <Slide transition={["slide"]} bgColor="primary">
        <Heading size={1} caps fit textColor="tertiary">
          Your presentations are interactive
        </Heading>
        <Interactive/>
      </Slide>

      <Slide transition={["spin", "slide"]} bgColor="tertiary">
        <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
          Made with love in Seattle by
        </Heading>
        <Link href="http://www.formidablelabs.com"><Image width="100%" src={images.logo}/></Link>
      </Slide>
    </Deck>
  </Spectacle>
, document.getElementById("root"));
<commit_msg>Drop caps from SurviveJS<commit_after>import React from "react";
import { render } from "react-dom";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle, Text
} from "src";

import preloader from "src/utils/preloader";

import Interactive from "assets/interactive";

require("normalize.css");
require("src/themes/default/index.css");

const slideTransition = ['zoom', 'fade'];
const images = {
  javascript: require("assets/javascript.jpg"),
  javascript2: require("assets/javascript2.jpg"),
  logo: require("assets/logo.png"),
  kanban: require("assets/kanban.gif"),
  moduleCounts: require("assets/module_counts.png"),
  redmonk: require("assets/redmonk.png"),
  jobs: require("assets/jobs.png"),
  jobTitles: require("assets/jobTitles.png"),
  jackie: require("assets/jackie.png"),
};

preloader([images.moduleCounts, images.redmonk, images.jobs]);

render(
  <Spectacle>
    <Deck transition={slideTransition} transitionDuration={500}>
      <Slide transition={["zoom"]} bgColor="primary">
        <Heading size={1} fit caps lineHeight={1} textColor="black">
          How to write a book and
        </Heading>
        <Heading size={1} fit>
          SurviveJS it
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Amazing growth rate.

At this rate bigger than others combined.

">
        <Heading size={1} textColor="tertiary">
          Module Counts
        </Heading>
        <Layout>
          <Image src={images.moduleCounts.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.modulecounts.com/">modulecounts.com</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Popular

Same goes for AltJS

">
        <Layout>
          <Link href="http://redmonk.com/jgovernor/2015/07/31/programming-language-rankings-summer-2015/">
            <Image src={images.redmonk.replace("/", "")} />
          </Link>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Angular dominates the work market.

Early signs of React.

">
        <Heading size={1} textColor="tertiary">
          Job Trends
        </Heading>
        <Layout>
          <Image src={images.jobs.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.indeed.com/jobtrends?q=Angularjs%2C+React.js%2C+Knockout%2C+Backbone.js&l=">Indeed</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary"
        notes="

Also job titles change.

Increasing demand for full stack developers.

">
        <Heading size={1} textColor="tertiary">
          Job Trends II
        </Heading>
        <Layout>
          <Image src={images.jobTitles.replace("/", "")} padding="20px" />
        </Layout>
        <Layout>
          <Text>
            <Link href="http://www.indeed.com/jobanalytics/jobtrends?q=frontend%2C+backend%2C+full+stack&l=">Indeed</Link>
          </Text>
        </Layout>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.javascript.replace("/", "")} margin="0px auto 40px" height="650px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.jackie.replace("/", "")} margin="0px auto 40px" height="381px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.javascript2.replace("/", "")} margin="0px auto 40px" height="650px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="white" notes="">
        <Image src={images.logo.replace("/", "")} margin="0px auto 40px" height="566px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit lineHeight={1} textColor="black">
          SurviveJS
        </Heading>
        <Heading size={1} fit>
          Webpack and React
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="black" notes="">
        <Image src={images.kanban.replace("/", "")} margin="0px auto 40px" height="279px"/>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">

      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          @survivejs
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          Quora
        </Heading>
      </Slide>

      <Slide transition={slideTransition} bgColor="primary">
        <Heading size={1} fit>
          <Link href="http://www.reactindiebundle.com/">React Indie Bundle</Link>
        </Heading>
      </Slide>

      <Slide transition={["slide"]} bgDarken={0.75}>
        <Appear fid="1">
          <Heading size={1} caps fit textColor="primary">
            Full Width
          </Heading>
        </Appear>
        <Appear fid="2">
          <Heading size={1} caps fit textColor="tertiary">
            Adjustable Darkness
          </Heading>
        </Appear>
        <Appear fid="3">
          <Heading size={1} caps fit textColor="primary">
            Background Imagery
          </Heading>
        </Appear>
      </Slide>

      <Slide transition={["zoom", "fade"]} bgColor="primary">
        <Heading caps fit>Flexible Layouts</Heading>
        <Layout>
          <Fill>
            <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
              Left
            </Heading>
          </Fill>
          <Fill>
            <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
              Right
            </Heading>
          </Fill>
        </Layout>
      </Slide>

      <Slide transition={["slide"]} bgColor="black">

          <Quote>Wonderfully formatted quotes</Quote>
          Ken Wheeler

      </Slide>

      <Slide transition={["spin", "zoom"]} bgColor="tertiary">
        <Heading caps fit size={1} textColor="primary">
          Inline Markdown
        </Heading>
        <Markdown>
          {`
You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And lets not forget **bold**
          `}
        </Markdown>
      </Slide>

      <Slide transition={["slide", "spin"]} bgColor="primary">
        <Heading caps fit size={1} textColor="tertiary">
          Smooth
        </Heading>
        <Heading caps fit size={1} textColor="secondary">
          Combinable Transitions
        </Heading>
      </Slide>

      <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
        <List>
          <ListItem><Appear fid="1">Inline style based theme system</Appear></ListItem>
          <ListItem><Appear fid="2">Autofit text</Appear></ListItem>
          <ListItem><Appear fid="3">Flexbox layout system</Appear></ListItem>
          <ListItem><Appear fid="4">React-Router navigation</Appear></ListItem>
          <ListItem><Appear fid="5">PDF export</Appear></ListItem>
          <ListItem><Appear fid="6">And...</Appear></ListItem>
        </List>
      </Slide>

      <Slide transition={["slide"]} bgColor="primary">
        <Heading size={1} caps fit textColor="tertiary">
          Your presentations are interactive
        </Heading>
        <Interactive/>
      </Slide>

      <Slide transition={["spin", "slide"]} bgColor="tertiary">
        <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
          Made with love in Seattle by
        </Heading>
        <Link href="http://www.formidablelabs.com"><Image width="100%" src={images.logo}/></Link>
      </Slide>
    </Deck>
  </Spectacle>
, document.getElementById("root"));
<|endoftext|>


<commit_before>/* global define:true */
define(['pixi', 'experience/mode', 'experience/issue'], function (PIXI, Mode, Issue) {
    'use strict';

    var ExploreMode = function (canvas) {
        this._canvas = canvas;
        Mode.MODES.push(this);
        Mode.DEFAULT_MODE = this;

        ExploreMode.AUTO_MODE_TIME = 4000;
        ExploreMode.AUTO_MODE_TIMEOUT = 4000;

        this._safeZone = {x: 0, y: 0, width: 0, height: 0};

        return this;
    };

    ExploreMode.prototype = new Mode();
    ExploreMode.prototype.constructor = ExploreMode;

    ExploreMode.prototype.init = function () {
        Mode.prototype.init.call(this);
        // set explore radius based on smallest canvas dimension
        var dimension = Math.min(this._canvas.canvasSize.x, this._canvas.canvasSize.y);
        this._exploreRadius = dimension / 1.7;

        var seed;
        var rSeed;
        var elm;
        var i;
        var isInsideBounds;
        var isOnSafeZone;
        var tries;

        // set issue positions
        for (i = 0; i < this._canvas.issues.length; i ++) {
            elm = this._canvas.issues[i];
            tries = 0;

            do {
                // make it evenly distributed
                seed = (i / this._canvas.issues.length) * Math.PI * 2;
                rSeed = Math.pow(Math.random(), 1/2) * (this._exploreRadius - 20);
                elm.exploreX = Math.sin(seed) * rSeed;
                elm.exploreY = Math.cos(seed) * rSeed;

                isInsideBounds = (
                    elm.exploreX > -this._canvas.canvasSize.x / 2 &&
                    elm.exploreX < this._canvas.canvasSize.x / 2 &&
                    elm.exploreY > -this._canvas.canvasSize.y / 2 &&
                    elm.exploreY < this._canvas.canvasSize.y / 2
                );

                isOnSafeZone = (
                    elm.exploreX > this._safeZone.x &&
                    elm.exploreX < this._safeZone.x + this._safeZone.width &&
                    elm.exploreY > this._safeZone.y &&
                    elm.exploreY < this._safeZone.y + this._safeZone.height
                );
            } while ((!isInsideBounds || isOnSafeZone) && tries++ < 64);

            elm.moveTo(0, 0);
        }

        // set tags positions
        for (i = 0; i < this._canvas.tags.length; i ++) {
            elm = this._canvas.tags[i];

            do {
                seed = Math.random() * Math.PI * 2;
                rSeed = this._exploreRadius + (Math.random() * 5);
                elm.exploreX = Math.sin(seed) * rSeed;
                elm.exploreY = Math.cos(seed) * rSeed;

                isInsideBounds = (
                    elm.exploreX > -this._canvas.canvasSize.x / 2 &&
                    elm.exploreX < this._canvas.canvasSize.x / 2 &&
                    elm.exploreY > -this._canvas.canvasSize.y / 2 &&
                    elm.exploreY < this._canvas.canvasSize.y / 2
                );
            } while (!isInsideBounds);
        }

        // set fakes positions
        for (i = 0; i < this._canvas.fakes.length; i ++) {
            seed = Math.random() * Math.PI * 2;
            rSeed = Math.pow(Math.random(), 1/3) * (this._exploreRadius - 20);

            elm = this._canvas.fakes[i];
            elm.elm.alpha = 0.1 + (0.3 * rSeed / this._exploreRadius);
            elm.exploreX = Math.sin(seed) * rSeed;
            elm.exploreY = Math.cos(seed) * rSeed;
        }

        // var sZ = new PIXI.Graphics();
        // sZ.beginFill(0xFF0000);
        // sZ.drawRect(this._safeZone.x, this._safeZone.y, this._safeZone.width, this._safeZone.height);
        // this._canvas._particlesContainer.addChild(sZ);
    };

    ExploreMode.prototype.setSafeZone = function (safeZone) {
        this._safeZone = safeZone;
    };

    ExploreMode.prototype._startAutoMode = function () {
        this._autoMode = true;

        this._autoModeIssue = this._canvas.issues[Math.floor(Math.random() * this._canvas.issues.length)];
        this._canvas.mousePosition = this._canvas.autoModePosition = new PIXI.Point(
            this._autoModeIssue.elm.x,
            this._autoModeIssue.elm.y
        );
        this._mouseOverIssue(this._autoModeIssue);

        clearTimeout(this._autoModeTimeout);
        this._autoModeTimeout = setTimeout(
            this._endAutoMode.bind(this),
            ExploreMode.AUTO_MODE_TIMEOUT,
            true
        );
    };

    ExploreMode.prototype._endAutoMode = function (startAnother) {
        if (this._autoModeIssue) {
            this._mouseOutIssue(this._autoModeIssue);
        }

        this._autoMode = false;
        this._canvas.autoModePosition = null;

        clearTimeout(this._autoModeTimeout);
        if (startAnother) {
            this._autoModeTimeout = setTimeout(
                this._startAutoMode.bind(this),
                ExploreMode.AUTO_MODE_TIME
            );
        }
    };

    ExploreMode.prototype._drawLines = function () {
        var i;
        var j;
        var issue;
        var related;
        var relatedItem;
        var tags;
        var isOver;

        this._canvas.clearLines();

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            related = issue.data.getRelated();
            tags = issue.data.getTags();

            // draw lines connecting related issues
            for (j = 0; j < related.length; j ++) {
                relatedItem = this._canvas.getElementByData(related[j]);
                isOver = (issue.isOver || relatedItem.isOver);

                this._canvas.drawLine(issue, relatedItem, 0x0, isOver ? 0.10 : 0.02);
            }

            // draw lines connecting related tags
            for (j = 0; j < tags.length; j ++) {
                relatedItem = this._canvas.getElementByData(tags[j]);
                isOver = (issue.isOver || relatedItem.isOver);

                this._canvas.drawLine(issue, relatedItem, 0x0, isOver ? 0.10 : 0.02);
            }
        }
    };

    ExploreMode.prototype._mouseOverIssue = function (issue) {
        this.selectedIssue = issue;

        var related = issue.data.getRelated();
        var tags;
        var relatedIssue;
        var i;

        if (issue.data.getTags) {
            tags =  issue.data.getTags();
        }

        if (issue !== this._autoModeIssue) {
            this._endAutoMode();
        }

        issue.mouseOver(this._canvas.mousePosition);

        for(i = 0; i < related.length; i ++) {
            relatedIssue = this._canvas.getElementByData(related[i]);
            relatedIssue.lightUp();
            relatedIssue.stopMoving();
        }

        if (tags) {
            for(i = 0; i < tags.length; i ++) {
                relatedIssue = this._canvas.getElementByData(tags[i]);
                relatedIssue.lightUp();
                relatedIssue.stopMoving();
            }
        }
    };

    ExploreMode.prototype._mouseOutIssue = function (issue) {
        if (!this._tapped) {
            this.selectedIssue = null;
        }
        this._tapped = null;

        var related = issue.data.getRelated();
        var tags;
        var relatedIssue;
        var i;

        if (issue.data.getTags) {
            tags =  issue.data.getTags();
        }

        if (issue !== this._autoModeIssue) {
            this._endAutoMode(true);
        }

        issue.mouseOut();

        for(i = 0; i < related.length; i ++) {
            if (related[i] === issue.data) {
                continue;
            }
            relatedIssue = this._canvas.getElementByData(related[i]);
            relatedIssue.lightDown();
            relatedIssue._resumeStaticAnimation();
        }

        if (tags) {
            for(i = 0; i < tags.length; i ++) {
                relatedIssue = this._canvas.getElementByData(tags[i]);
                relatedIssue.lightDown();
                relatedIssue._resumeStaticAnimation();
            }
        }
    };

    ExploreMode.prototype._tapIssue = function (issue) {
        this._tapped = true;
        if (!this.selectedIssue) {
            issue._onMouseOver();
        } else if (this.selectedIssue === issue) {
            issue._onPress();
        } else {
            this.selectedIssue._onMouseOut();
            issue._onMouseOver();
        }
    };

    ExploreMode.prototype._onStartShow = function () {
        // set position for issues
        var issue;
        var i;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.setMode(Issue.MODE_EXPLORE);
            issue.moveTo(
                issue.exploreX,
                issue.exploreY,
                issue._resumeStaticAnimation.bind(issue),
                {alpha: 1});
            issue.exploreMouseOver = this._mouseOverIssue.bind(this);
            issue.exploreMouseOut = this._mouseOutIssue.bind(this);
            issue.exploreTap = this._tapIssue.bind(this);
            issue.mouseOverS.add(issue.exploreMouseOver);
            issue.mouseOutS.add(issue.exploreMouseOut);
            issue.tapS.add(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.tags.length; i ++) {
            issue = this._canvas.tags[i];
            issue.setMode(Issue.MODE_TAG);
            issue._x0 = issue.exploreX;
            issue._y0 = issue.exploreY;
            issue.implode();
            issue.exploreMouseOver = this._mouseOverIssue.bind(this);
            issue.exploreMouseOut = this._mouseOutIssue.bind(this);
            issue.exploreTap = this._tapIssue.bind(this);
            issue.mouseOverS.add(issue.exploreMouseOver);
            issue.mouseOutS.add(issue.exploreMouseOut);
            issue.tapS.add(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.fakes.length; i ++) {
            issue = this._canvas.fakes[i];
            issue._x0 = issue.exploreX;
            issue._y0 = issue.exploreY;
            issue.implode();
        }

        this._drawLinesBind = this._drawLines.bind(this);
        this._canvas.renderStartS.add(this._drawLinesBind);

        // start a new autoMode timeout
        this._endAutoMode(true);

        setTimeout(this._onShow.bind(this), 500);
    };

    ExploreMode.prototype._onStartHide = function () {
        var issue;
        var i;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.explode(this._exploreRadius);
            issue.mouseOverS.remove(issue.exploreMouseOver);
            issue.mouseOutS.remove(issue.exploreMouseOut);
            issue.tapS.remove(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.tags.length; i ++) {
            issue = this._canvas.tags[i];
            issue.explode(this._exploreRadius);
            issue.mouseOverS.remove(issue.exploreMouseOver);
            issue.mouseOutS.remove(issue.exploreMouseOut);
            issue.tapS.remove(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.fakes.length; i ++) {
            this._canvas.fakes[i].explode(this._exploreRadius);
        }

        this._canvas.clearLines();
        this._canvas.renderStartS.remove(this._drawLinesBind);

        this._endAutoMode();

        setTimeout(this._onHide.bind(this), 0);
    };

    return ExploreMode;
});<commit_msg>make sure issues dont overlap on explore mode<commit_after>/* global define:true */
define(['pixi', 'experience/mode', 'experience/issue'], function (PIXI, Mode, Issue) {
    'use strict';

    var ExploreMode = function (canvas) {
        this._canvas = canvas;
        Mode.MODES.push(this);
        Mode.DEFAULT_MODE = this;

        ExploreMode.AUTO_MODE_TIME = 4000;
        ExploreMode.AUTO_MODE_TIMEOUT = 4000;

        this._safeZone = {x: 0, y: 0, width: 0, height: 0};

        return this;
    };

    ExploreMode.prototype = new Mode();
    ExploreMode.prototype.constructor = ExploreMode;

    ExploreMode.prototype.init = function () {
        Mode.prototype.init.call(this);
        // set explore radius based on smallest canvas dimension
        var dimension = Math.min(this._canvas.canvasSize.x, this._canvas.canvasSize.y);
        this._exploreRadius = dimension / 1.7;

        var seed;
        var rSeed;
        var elm;
        var i;
        var j;
        var isInsideBounds;
        var isOnSafeZone;
        var tries;
        var lines = [];
        var line;
        var isLineFree;

        var issueWidth = 100;
        var issueHeight = 20;

        // set issue positions
        for (i = 0; i < this._canvas.issues.length; i ++) {
            elm = this._canvas.issues[i];
            tries = 0;
            isLineFree = true;

            do {
                // make it evenly distributed
                seed = (i / this._canvas.issues.length) * Math.PI * 2;
                rSeed = Math.pow(Math.random(), 1/2) * (this._exploreRadius - 20);
                elm.exploreX = Math.sin(seed) * rSeed;
                elm.exploreY = Math.cos(seed) * rSeed;

                line = Math.floor(elm.exploreY / issueWidth);
                elm.exploreY = line * issueWidth;

                // makes sure issues don't overlap
                if (!lines[line]) {
                    lines[line] = [];
                } else {
                    for (j = 0; j < lines[line].length; j ++) {
                        isLineFree = isLineFree && Math.abs(lines[line][j].exploreX - elm.exploreX) > issueHeight;
                    }
                }

                isInsideBounds = (
                    elm.exploreX > -this._canvas.canvasSize.x / 2 &&
                    elm.exploreX < this._canvas.canvasSize.x / 2 &&
                    elm.exploreY > -this._canvas.canvasSize.y / 2 &&
                    elm.exploreY < this._canvas.canvasSize.y / 2
                );

                isOnSafeZone = (
                    elm.exploreX > this._safeZone.x &&
                    elm.exploreX < this._safeZone.x + this._safeZone.width &&
                    elm.exploreY > this._safeZone.y &&
                    elm.exploreY < this._safeZone.y + this._safeZone.height
                );
            } while ((!isInsideBounds || isOnSafeZone || !isLineFree) && tries++ < 64);

            lines[line].push(elm);
            elm.moveTo(0, 0);
        }

        // set tags positions
        for (i = 0; i < this._canvas.tags.length; i ++) {
            elm = this._canvas.tags[i];

            do {
                seed = Math.random() * Math.PI * 2;
                rSeed = this._exploreRadius + (Math.random() * 5);
                elm.exploreX = Math.sin(seed) * rSeed;
                elm.exploreY = Math.cos(seed) * rSeed;

                isInsideBounds = (
                    elm.exploreX > -this._canvas.canvasSize.x / 2 &&
                    elm.exploreX < this._canvas.canvasSize.x / 2 &&
                    elm.exploreY > -this._canvas.canvasSize.y / 2 &&
                    elm.exploreY < this._canvas.canvasSize.y / 2
                );
            } while (!isInsideBounds);
        }

        // set fakes positions
        for (i = 0; i < this._canvas.fakes.length; i ++) {
            seed = Math.random() * Math.PI * 2;
            rSeed = Math.pow(Math.random(), 1/3) * (this._exploreRadius - 20);

            elm = this._canvas.fakes[i];
            elm.elm.alpha = 0.1 + (0.3 * rSeed / this._exploreRadius);
            elm.exploreX = Math.sin(seed) * rSeed;
            elm.exploreY = Math.cos(seed) * rSeed;
        }

        // var sZ = new PIXI.Graphics();
        // sZ.beginFill(0xFF0000);
        // sZ.drawRect(this._safeZone.x, this._safeZone.y, this._safeZone.width, this._safeZone.height);
        // this._canvas._particlesContainer.addChild(sZ);
    };

    ExploreMode.prototype.setSafeZone = function (safeZone) {
        this._safeZone = safeZone;
    };

    ExploreMode.prototype._startAutoMode = function () {
        this._autoMode = true;

        this._autoModeIssue = this._canvas.issues[Math.floor(Math.random() * this._canvas.issues.length)];
        this._canvas.mousePosition = this._canvas.autoModePosition = new PIXI.Point(
            this._autoModeIssue.elm.x,
            this._autoModeIssue.elm.y
        );
        this._mouseOverIssue(this._autoModeIssue);

        clearTimeout(this._autoModeTimeout);
        this._autoModeTimeout = setTimeout(
            this._endAutoMode.bind(this),
            ExploreMode.AUTO_MODE_TIMEOUT,
            true
        );
    };

    ExploreMode.prototype._endAutoMode = function (startAnother) {
        if (this._autoModeIssue) {
            this._mouseOutIssue(this._autoModeIssue);
        }

        this._autoMode = false;
        this._canvas.autoModePosition = null;

        clearTimeout(this._autoModeTimeout);
        if (startAnother) {
            this._autoModeTimeout = setTimeout(
                this._startAutoMode.bind(this),
                ExploreMode.AUTO_MODE_TIME
            );
        }
    };

    ExploreMode.prototype._drawLines = function () {
        var i;
        var j;
        var issue;
        var related;
        var relatedItem;
        var tags;
        var isOver;

        this._canvas.clearLines();

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            related = issue.data.getRelated();
            tags = issue.data.getTags();

            // draw lines connecting related issues
            for (j = 0; j < related.length; j ++) {
                relatedItem = this._canvas.getElementByData(related[j]);
                isOver = (issue.isOver || relatedItem.isOver);

                this._canvas.drawLine(issue, relatedItem, 0x0, isOver ? 0.10 : 0.02);
            }

            // draw lines connecting related tags
            for (j = 0; j < tags.length; j ++) {
                relatedItem = this._canvas.getElementByData(tags[j]);
                isOver = (issue.isOver || relatedItem.isOver);

                this._canvas.drawLine(issue, relatedItem, 0x0, isOver ? 0.10 : 0.02);
            }
        }
    };

    ExploreMode.prototype._mouseOverIssue = function (issue) {
        this.selectedIssue = issue;

        var related = issue.data.getRelated();
        var tags;
        var relatedIssue;
        var i;

        if (issue.data.getTags) {
            tags =  issue.data.getTags();
        }

        if (issue !== this._autoModeIssue) {
            this._endAutoMode();
        }

        issue.mouseOver(this._canvas.mousePosition);

        for(i = 0; i < related.length; i ++) {
            relatedIssue = this._canvas.getElementByData(related[i]);
            relatedIssue.lightUp();
            relatedIssue.stopMoving();
        }

        if (tags) {
            for(i = 0; i < tags.length; i ++) {
                relatedIssue = this._canvas.getElementByData(tags[i]);
                relatedIssue.lightUp();
                relatedIssue.stopMoving();
            }
        }
    };

    ExploreMode.prototype._mouseOutIssue = function (issue) {
        if (!this._tapped) {
            this.selectedIssue = null;
        }
        this._tapped = null;

        var related = issue.data.getRelated();
        var tags;
        var relatedIssue;
        var i;

        if (issue.data.getTags) {
            tags =  issue.data.getTags();
        }

        if (issue !== this._autoModeIssue) {
            this._endAutoMode(true);
        }

        issue.mouseOut();

        for(i = 0; i < related.length; i ++) {
            if (related[i] === issue.data) {
                continue;
            }
            relatedIssue = this._canvas.getElementByData(related[i]);
            relatedIssue.lightDown();
            relatedIssue._resumeStaticAnimation();
        }

        if (tags) {
            for(i = 0; i < tags.length; i ++) {
                relatedIssue = this._canvas.getElementByData(tags[i]);
                relatedIssue.lightDown();
                relatedIssue._resumeStaticAnimation();
            }
        }
    };

    ExploreMode.prototype._tapIssue = function (issue) {
        this._tapped = true;
        if (!this.selectedIssue) {
            issue._onMouseOver();
        } else if (this.selectedIssue === issue) {
            issue._onPress();
        } else {
            this.selectedIssue._onMouseOut();
            issue._onMouseOver();
        }
    };

    ExploreMode.prototype._onStartShow = function () {
        // set position for issues
        var issue;
        var i;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.setMode(Issue.MODE_EXPLORE);
            issue.moveTo(
                issue.exploreX,
                issue.exploreY,
                issue._resumeStaticAnimation.bind(issue),
                {alpha: 1});
            issue.exploreMouseOver = this._mouseOverIssue.bind(this);
            issue.exploreMouseOut = this._mouseOutIssue.bind(this);
            issue.exploreTap = this._tapIssue.bind(this);
            issue.mouseOverS.add(issue.exploreMouseOver);
            issue.mouseOutS.add(issue.exploreMouseOut);
            issue.tapS.add(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.tags.length; i ++) {
            issue = this._canvas.tags[i];
            issue.setMode(Issue.MODE_TAG);
            issue._x0 = issue.exploreX;
            issue._y0 = issue.exploreY;
            issue.implode();
            issue.exploreMouseOver = this._mouseOverIssue.bind(this);
            issue.exploreMouseOut = this._mouseOutIssue.bind(this);
            issue.exploreTap = this._tapIssue.bind(this);
            issue.mouseOverS.add(issue.exploreMouseOver);
            issue.mouseOutS.add(issue.exploreMouseOut);
            issue.tapS.add(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.fakes.length; i ++) {
            issue = this._canvas.fakes[i];
            issue._x0 = issue.exploreX;
            issue._y0 = issue.exploreY;
            issue.implode();
        }

        this._drawLinesBind = this._drawLines.bind(this);
        this._canvas.renderStartS.add(this._drawLinesBind);

        // start a new autoMode timeout
        this._endAutoMode(true);

        setTimeout(this._onShow.bind(this), 500);
    };

    ExploreMode.prototype._onStartHide = function () {
        var issue;
        var i;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.explode(this._exploreRadius);
            issue.mouseOverS.remove(issue.exploreMouseOver);
            issue.mouseOutS.remove(issue.exploreMouseOut);
            issue.tapS.remove(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.tags.length; i ++) {
            issue = this._canvas.tags[i];
            issue.explode(this._exploreRadius);
            issue.mouseOverS.remove(issue.exploreMouseOver);
            issue.mouseOutS.remove(issue.exploreMouseOut);
            issue.tapS.remove(issue.exploreTap);
        }

        for (i = 0; i < this._canvas.fakes.length; i ++) {
            this._canvas.fakes[i].explode(this._exploreRadius);
        }

        this._canvas.clearLines();
        this._canvas.renderStartS.remove(this._drawLinesBind);

        this._endAutoMode();

        setTimeout(this._onHide.bind(this), 0);
    };

    return ExploreMode;
});<|endoftext|>


<commit_before>import React from "react";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle, Text
} from "../src";

import preloader from "../src/utils/preloader";

import createTheme from "../src/themes/default";

import Interactive from "../assets/interactive";

require("normalize.css");
require("../src/themes/default/index.css");

const images = {
  city: require("../assets/city.jpg"),
  kat: require("../assets/kat.png"),
  logo: require("../assets/formidable-logo.svg"),
  markdown: require("../assets/markdown.png")
};

preloader(images);

const theme = createTheme({
  primary: "#ff4081"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>
          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              Spectacle
            </Heading>
            <Heading size={1} fit caps>
              A ReactJS Presentation Library
            </Heading>
            <Heading size={1} fit caps textColor="black">
              Where You Can Write Your Decks In JSX
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">View on Github</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>Hit Your Right Arrow To Begin!</Text>
          </Slide>
          <Slide transition={["slide"]} bgColor="black" notes="You can even put notes on your slide. How awesome is that?">
            <Image src={images.kat.replace("/", "")} margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary" notes="

talk about that

and that

">
            <CodePane
              lang="jsx"
              source={require("raw!../assets/deck.example")}
              margin="20px auto"
            />
          </Slide>
          <Slide transition={["slide"]} bgImage={images.city.replace("/", "")} bgDarken={0.75}>
            <Appear fid="1">
              <Heading size={1} caps fit textColor="primary">
                Full Width
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={1} caps fit textColor="tertiary">
                Adjustable Darkness
              </Heading>
            </Appear>
            <Appear fid="3">
              <Heading size={1} caps fit textColor="primary">
                Background Imagery
              </Heading>
            </Appear>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary">
            <Heading caps fit>Flexible Layouts</Heading>
            <Layout>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Left
                </Heading>
              </Fill>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Right
                </Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["slide"]} bgColor="black">

              <Quote>Wonderfully formatted quotes</Quote>
              Ken Wheeler

          </Slide>
          <Slide transition={["spin", "zoom"]} bgColor="tertiary">
            <Heading caps fit size={1} textColor="primary">
              Inline Markdown
            </Heading>
            <Markdown>
              {`
![Markdown Logo](${images.markdown.replace("/", "")})

You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And lets not forget **bold**
              `}
            </Markdown>
          </Slide>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading caps fit size={1} textColor="tertiary">
              Smooth
            </Heading>
            <Heading caps fit size={1} textColor="secondary">
              Combinable Transitions
            </Heading>
          </Slide>
          <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
            <List>
              <Appear><ListItem>Inline style based theme system</ListItem></Appear>
              <Appear><ListItem>Autofit text</ListItem></Appear>
              <Appear><ListItem>Flexbox layout system</ListItem></Appear>
              <Appear><ListItem>PDF export</ListItem></Appear>
              <Appear><ListItem>And...</ListItem></Appear>
            </List>
          </Slide>
          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Your presentations are interactive
            </Heading>
            <Interactive/>
          </Slide>
          <Slide transition={["spin", "slide"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Seattle by
            </Heading>
            <Link href="http://www.formidable.com"><Image width="100%" src={images.logo}/></Link>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<commit_msg>add missing apostrophe<commit_after>import React from "react";

import {
  Appear, BlockQuote, Cite, CodePane, Deck, Fill,
  Heading, Image, Layout, Link, ListItem, List, Markdown, Quote, Slide, Spectacle, Text
} from "../src";

import preloader from "../src/utils/preloader";

import createTheme from "../src/themes/default";

import Interactive from "../assets/interactive";

require("normalize.css");
require("../src/themes/default/index.css");

const images = {
  city: require("../assets/city.jpg"),
  kat: require("../assets/kat.png"),
  logo: require("../assets/formidable-logo.svg"),
  markdown: require("../assets/markdown.png")
};

preloader(images);

const theme = createTheme({
  primary: "#ff4081"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Spectacle theme={theme}>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>
          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              Spectacle
            </Heading>
            <Heading size={1} fit caps>
              A ReactJS Presentation Library
            </Heading>
            <Heading size={1} fit caps textColor="black">
              Where You Can Write Your Decks In JSX
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">View on Github</Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>Hit Your Right Arrow To Begin!</Text>
          </Slide>
          <Slide transition={["slide"]} bgColor="black" notes="You can even put notes on your slide. How awesome is that?">
            <Image src={images.kat.replace("/", "")} margin="0px auto 40px" height="293px"/>
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary" notes="

talk about that

and that

">
            <CodePane
              lang="jsx"
              source={require("raw!../assets/deck.example")}
              margin="20px auto"
            />
          </Slide>
          <Slide transition={["slide"]} bgImage={images.city.replace("/", "")} bgDarken={0.75}>
            <Appear fid="1">
              <Heading size={1} caps fit textColor="primary">
                Full Width
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={1} caps fit textColor="tertiary">
                Adjustable Darkness
              </Heading>
            </Appear>
            <Appear fid="3">
              <Heading size={1} caps fit textColor="primary">
                Background Imagery
              </Heading>
            </Appear>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary">
            <Heading caps fit>Flexible Layouts</Heading>
            <Layout>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Left
                </Heading>
              </Fill>
              <Fill>
                <Heading size={4} caps textColor="secondary" bgColor="white" margin={10}>
                  Right
                </Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["slide"]} bgColor="black">

              <Quote>Wonderfully formatted quotes</Quote>
              Ken Wheeler

          </Slide>
          <Slide transition={["spin", "zoom"]} bgColor="tertiary">
            <Heading caps fit size={1} textColor="primary">
              Inline Markdown
            </Heading>
            <Markdown>
              {`
![Markdown Logo](${images.markdown.replace("/", "")})

You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax
* Lists too!
* With ~~strikethrough~~ and _italic_
* And let's not forget **bold**
              `}
            </Markdown>
          </Slide>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading caps fit size={1} textColor="tertiary">
              Smooth
            </Heading>
            <Heading caps fit size={1} textColor="secondary">
              Combinable Transitions
            </Heading>
          </Slide>
          <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
            <List>
              <Appear><ListItem>Inline style based theme system</ListItem></Appear>
              <Appear><ListItem>Autofit text</ListItem></Appear>
              <Appear><ListItem>Flexbox layout system</ListItem></Appear>
              <Appear><ListItem>PDF export</ListItem></Appear>
              <Appear><ListItem>And...</ListItem></Appear>
            </List>
          </Slide>
          <Slide transition={["slide"]} bgColor="primary">
            <Heading size={1} caps fit textColor="tertiary">
              Your presentations are interactive
            </Heading>
            <Interactive/>
          </Slide>
          <Slide transition={["spin", "slide"]} bgColor="tertiary">
            <Heading size={1} caps fit lineHeight={1.5} textColor="primary">
              Made with love in Seattle by
            </Heading>
            <Link href="http://www.formidable.com"><Image width="100%" src={images.logo}/></Link>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}
<|endoftext|>