<commit_before>// Copyright 2014-2015 runtime.js project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Using code adapted and modified from http://wiki.osdev.org/CMOS#Reading_All_RTC_Time_and_Date_Registers
// OSDev's disclaimer: http://wiki.osdev.org/OSDev_Wiki:General_disclaimer

'use strict';

var resources = require('./resources');
var ports = resources.ioRange;

var second = 0;
var minute = 0;
var hour = 0;
var day = 0;
var month = 0;
var year = 0;

var cmosAddress = 0x70;
var cmosData = 0x71;

var port = ports.port(cmosAddress);
var dataPort = ports.port(cmosData);

function getUpdateInProgressFlag() {
  port.write8(0x0A);
  return (dataPort.read8() & 0x80);
}

function getRTCRegister(reg) {
  port.write8(reg);
  return dataPort.read8();
}

// set the time:

var lastSecond = 0;
var lastMinute = 0;
var lastHour = 0;
var lastDay = 0;
var lastMonth = 0;
var lastYear = 0;
var registerB = 0;

while (getUpdateInProgressFlag()) {
  second = getRTCRegister(0x00);
  minute = getRTCRegister(0x02);
  hour = getRTCRegister(0x04);
  day = getRTCRegister(0x07);
  month = getRTCRegister(0x08);
  year = getRTCRegister(0x09);
}

do {
  lastSecond = second;
  lastMinute = minute;
  lastHour = hour;
  lastDay = day;
  lastMonth = month;
  lastYear = year;

  while (getUpdateInProgressFlag());
  second = getRTCRegister(0x00);
  minute = getRTCRegister(0x02);
  hour = getRTCRegister(0x04);
  day = getRTCRegister(0x07);
  month = getRTCRegister(0x08);
  year = getRTCRegister(0x09);
} while ((lastSecond !== second) || (lastMinute !== minute) || (lastHour !== hour) ||
         (lastDay !== day) || (lastMonth !== month) || (lastYear !== year));

registerB = getRTCRegister(0x0B);

if (!(registerB & 0x04)) {
  second = (second & 0x0F) + ((second >>> 4) * 10);
  minute = (minute & 0x0F) + ((minute >>> 4) * 10);
  hour = ((hour & 0x0F) + (((hour & 0x70) >>> 4) * 10)) | (hour & 0x80);
  day = (day & 0x0F) + ((day >>> 4) * 10);
  month = (month & 0x0F) + ((month >>> 4) * 10);
  year = (year & 0x0F) + ((year >>> 4) * 10);
}

year = year + 2000;

var date = new Date(year, month - 1, day, hour, minute, second, 0);
resources.natives.setTime(date.getTime() * 1000);
<commit_msg>Use Date.UTC instead of local time constructor<commit_after>// Copyright 2014-2015 runtime.js project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Using code adapted and modified from http://wiki.osdev.org/CMOS#Reading_All_RTC_Time_and_Date_Registers
// OSDev's disclaimer: http://wiki.osdev.org/OSDev_Wiki:General_disclaimer

'use strict';

var resources = require('./resources');
var ports = resources.ioRange;

var second = 0;
var minute = 0;
var hour = 0;
var day = 0;
var month = 0;
var year = 0;

var cmosAddress = 0x70;
var cmosData = 0x71;

var port = ports.port(cmosAddress);
var dataPort = ports.port(cmosData);

function getUpdateInProgressFlag() {
  port.write8(0x0A);
  return (dataPort.read8() & 0x80);
}

function getRTCRegister(reg) {
  port.write8(reg);
  return dataPort.read8();
}

// set the time:

var lastSecond = 0;
var lastMinute = 0;
var lastHour = 0;
var lastDay = 0;
var lastMonth = 0;
var lastYear = 0;
var registerB = 0;

while (getUpdateInProgressFlag()) {
  second = getRTCRegister(0x00);
  minute = getRTCRegister(0x02);
  hour = getRTCRegister(0x04);
  day = getRTCRegister(0x07);
  month = getRTCRegister(0x08);
  year = getRTCRegister(0x09);
}

do {
  lastSecond = second;
  lastMinute = minute;
  lastHour = hour;
  lastDay = day;
  lastMonth = month;
  lastYear = year;

  while (getUpdateInProgressFlag());
  second = getRTCRegister(0x00);
  minute = getRTCRegister(0x02);
  hour = getRTCRegister(0x04);
  day = getRTCRegister(0x07);
  month = getRTCRegister(0x08);
  year = getRTCRegister(0x09);
} while ((lastSecond !== second) || (lastMinute !== minute) || (lastHour !== hour) ||
         (lastDay !== day) || (lastMonth !== month) || (lastYear !== year));

registerB = getRTCRegister(0x0B);

if (!(registerB & 0x04)) {
  second = (second & 0x0F) + ((second >>> 4) * 10);
  minute = (minute & 0x0F) + ((minute >>> 4) * 10);
  hour = ((hour & 0x0F) + (((hour & 0x70) >>> 4) * 10)) | (hour & 0x80);
  day = (day & 0x0F) + ((day >>> 4) * 10);
  month = (month & 0x0F) + ((month >>> 4) * 10);
  year = (year & 0x0F) + ((year >>> 4) * 10);
}

year = year + 2000;

var utc = Date.UTC(year, month - 1, day, hour, minute, second, 0);
resources.natives.setTime(utc * 1000);
<|endoftext|>


<commit_before>'use strict';

function SlModel( project ) {
    this.project = project;
    this.name    = 'Sl-Model';
}

function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
}

SlModel.prototype.treeFor = function treeFor( name ) {
    var path = require('path'),
        slmodelPath = path.join( 'node_modules', 'sl-model' ),
        testTree,
        vendorTree,
        appTree,
        mergeTrees = require( 'broccoli-merge-trees' ),
        pickFiles = require( 'broccoli-static-compiler' );

    if( name === 'vendor' ) {
        vendorTree = mergeTrees([
            pickFiles( path.join( slmodelPath, 'node_modules', 'sl-modelize', 'dist' ), {
                    srcDir  : '/',
                    destDir : 'sl-modelize'
                }
            ),
            pickFiles( path.join( slmodelPath, 'dist' ), {
                    srcDir  : '/',
                    destDir : 'sl-model'
                }
            )
        ]);

        return vendorTree;
    } else if( name === 'test-support' ){
        testTree = pickFiles( path.join( slmodelPath, 'test-helpers' ), {
            srcDird: '/',
            files: [ 'model-for-sl-model.js' ],
            destFir: '/'
        } );

        return testTree;

    } else if ( name === 'app' ) {
        appTree = pickFiles( path.join( slmodelPath, 'lib', 'initializers' ), {
            srcDir: '/',
            files: [ 'main.js' ],
            destDir : '/initializers'
        } );

        return appTree;
    }
};

SlModel.prototype.blueprintsPath = function() {
    var path = require( 'path' );
    return path.join( 'node_modules', 'sl-model', 'blueprints' );
};

SlModel.prototype.included = function included( app ) {
    this.app = app;

    this.app.import( 'vendor/sl-model/sl-model.js', {
        exports: {
            'sl-model': [
                'default',
                'store',
                'adapter',
                'adapter/ajax',
                'adapter/localstorage'
            ]
        }
    });
    this.app.import( 'vendor/sl-modelize/sl-modelize.js' );
};

module.exports = SlModel;
<commit_msg>fixed typo<commit_after>'use strict';

function SlModel( project ) {
    this.project = project;
    this.name    = 'Sl-Model';
}

function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
}

SlModel.prototype.treeFor = function treeFor( name ) {
    var path = require('path'),
        slmodelPath = path.join( 'node_modules', 'sl-model' ),
        testTree,
        vendorTree,
        appTree,
        mergeTrees = require( 'broccoli-merge-trees' ),
        pickFiles = require( 'broccoli-static-compiler' );

    if( name === 'vendor' ) {
        vendorTree = mergeTrees([
            pickFiles( path.join( slmodelPath, 'node_modules', 'sl-modelize', 'dist' ), {
                    srcDir  : '/',
                    destDir : 'sl-modelize'
                }
            ),
            pickFiles( path.join( slmodelPath, 'dist' ), {
                    srcDir  : '/',
                    destDir : 'sl-model'
                }
            )
        ]);

        return vendorTree;
    } else if( name === 'test-support' ){
        testTree = pickFiles( path.join( slmodelPath, 'test-helpers' ), {
            srcDir: '/',
            files: [ 'model-for-sl-model.js' ],
            destFir: '/'
        } );

        return testTree;

    } else if ( name === 'app' ) {
        appTree = pickFiles( path.join( slmodelPath, 'lib', 'initializers' ), {
            srcDir: '/',
            files: [ 'main.js' ],
            destDir : '/initializers'
        } );

        return appTree;
    }
};

SlModel.prototype.blueprintsPath = function() {
    var path = require( 'path' );
    return path.join( 'node_modules', 'sl-model', 'blueprints' );
};

SlModel.prototype.included = function included( app ) {
    this.app = app;

    this.app.import( 'vendor/sl-model/sl-model.js', {
        exports: {
            'sl-model': [
                'default',
                'store',
                'adapter',
                'adapter/ajax',
                'adapter/localstorage'
            ]
        }
    });
    this.app.import( 'vendor/sl-modelize/sl-modelize.js' );
};

module.exports = SlModel;
<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

// Constant definitions
DEFAULT_SOCKET_URL = 'http://www.hyperlocalcontext.com/notman';
MAX_RSSI = 255;
DOUGHNUT_OPTIONS = {
  legend: {
    display: true,
    labels: {
      fontSize: 24,
      fontColor: "#fff"
    }
  }
};

/**
 * dashboard Module
 * All of the JavaScript specific to the dashboard is contained inside this
 * angular module.  The only external dependencies are:
 * - beaver, cormorant and cuttlefish (reelyActive)
 * - socket.io (btford)
 * - ngSanitize (angular)
 * - chart.js (jtblin)
 */
angular.module('dashboard', ['btford.socket-io', 'reelyactive.beaver',
                             'reelyactive.cormorant',
                             'reelyactive.cuttlefish', 'ngSanitize',
                             'chart.js'])

/**
 * Socket Factory
 * Creates the websocket connection to the given URL using socket.io.
 */
.factory('Socket', function(socketFactory) {
  return socketFactory({
    ioSocket: io.connect(DEFAULT_SOCKET_URL)
  });
})

/**
 * DashCtrl Controller
 * Handles the manipulation of all variables accessed by the HTML view.
 */
.controller('DashCtrl', function($scope, Socket, beaver, cormorant) {

  // Variables accessible in the HTML scope
  $scope.devices = beaver.getDevices();
  $scope.directories = beaver.getDirectories();
  $scope.stats = beaver.getStats();
  $scope.stories = cormorant.getStories();
  $scope.featuredDirectory = null;
  $scope.addFiller = true;
  $scope.doughnutLabels = [ '3', '2', '1', 'Cafe' ];
  $scope.doughnutData = [ 0, 0, 0, 0 ];
  $scope.doughnutColors = [ '#83b7d1', '#0770a2', '#043851', '#ff6900' ];
  $scope.doughnutOptions = DOUGHNUT_OPTIONS;
  $scope.numberOfDevices = 0;

  // beaver.js listens on the websocket for events
  beaver.listen(Socket);

  // Handle events pre-processed by beaver.js
  beaver.on('appearance', function(event) {
    handleEvent(event);
    updateDoughnut(event);
    beaver.addDeviceProperty(event.deviceId, 'featured', false);
  });
  beaver.on('displacement', function(event) {
    handleEvent(event);
    updateDoughnut(event);
  });
  beaver.on('keep-alive', function(event) {
    handleEvent(event);
  });
  beaver.on('disappearance', function(event) {
    handleEvent(event);
    updateDoughnut(event);
  });

  // Handle an event
  function handleEvent(event) {
    updateDeviceStory(event.deviceId, event.deviceUrl);
    updateDirectoryStory(event.receiverDirectory, event.receiverUrl);
    $scope.numberOfDevices = Object.keys($scope.devices).length;
  }

  // Update the device's story
  function updateDeviceStory(deviceId, url) {
    cormorant.getStory(url, function(story, url) {
      beaver.addDeviceProperty(deviceId, 'story', story);
      beaver.addDeviceProperty(deviceId, 'person', includesPerson(story));
    });
  }

  // Update the directory's story
  function updateDirectoryStory(directory, url) {
    cormorant.getStory(url, function(story, url) {
      if(story) {
        beaver.addDirectoryProperty(directory, 'story', story);
        beaver.addDirectoryProperty(directory, 'imageUrl',
                                    story['@graph'][0]['schema:image']);
      }
    });
  }

  // Update the doughnut chart
  function updateDoughnut(event) {
    $scope.doughnutData[0] = getNumberOfDirectoryDevices('notman:third:west')
                         + getNumberOfDirectoryDevices('notman:third:centre')
                         + getNumberOfDirectoryDevices('notman:third:east');
    $scope.doughnutData[1] = getNumberOfDirectoryDevices('notman:second:west')
                         + getNumberOfDirectoryDevices('notman:second:centre')
                         + getNumberOfDirectoryDevices('notman:second:east');
    $scope.doughnutData[2] = getNumberOfDirectoryDevices('notman:first:west')
                         + getNumberOfDirectoryDevices('notman:first:centre')
                         + getNumberOfDirectoryDevices('notman:first:east');
    $scope.doughnutData[3] = getNumberOfDirectoryDevices('notman:cafe');
  }

  // Get the number of devices in the given directory
  function getNumberOfDirectoryDevices(directory) {
    if(!$scope.directories.hasOwnProperty(directory)) {
      return 0;
    }
    return Object.keys($scope.directories[directory].devices).length;
  }

  // Verify if the story includes a Person
  function includesPerson(story) {
    if(story && story.hasOwnProperty('@graph')) {
      for(var cIndex = 0; cIndex < story['@graph'].length; cIndex++) {
        if(story['@graph'][cIndex].hasOwnProperty('@type') &&
           (story['@graph'][cIndex]['@type'] === 'schema:Person')) {
          return true;
        }
      }
    }
    return false;
  }

  // Update the featured directory and story
  function updateFeatured() {
    var people = 0;
    var newFeaturedDirectory = $scope.featuredDirectory;
    for(cDirectory in $scope.directories) {
      var currentPeople = 0;
      var currentDirectory = $scope.directories[cDirectory];
      for(cDevice in currentDirectory.devices) {
        if(currentDirectory.devices[cDevice].person) {
          currentPeople++;
        }
      }
      if((currentPeople > people) &&
         (currentDirectory !== $scope.featuredDirectory)) {
        newFeaturedDirectory = currentDirectory;
      }
    }
    if(newFeaturedDirectory !== $scope.featuredDirectory) {
      $scope.featuredDirectory = newFeaturedDirectory;
    }
    else {
      var directories = Object.keys($scope.directories);
      var randomIndex = Math.floor(Math.random() * directories.length);
      $scope.featuredDirectory = $scope.directories[directories[randomIndex]];
    }

    var people = [];
    for(cDevice in $scope.devices) {
      beaver.addDeviceProperty(cDevice, 'featured', false);
      if($scope.devices[cDevice].person === true) {
        people.push(cDevice);
      }
    }
    if(people.length > 0) {
      $scope.addFiller = false;
      var featuredStoryIndex = Math.floor(Math.random() * people.length);
      beaver.addDeviceProperty(people[featuredStoryIndex], 'featured', true);
    }
    else {
      $scope.addFiller = true;
    }
  }

  setInterval(updateFeatured, 8000);
});
<commit_msg>Areas displayed at bottom now feature more products and people<commit_after>/**
 * Copyright reelyActive 2016
 * We believe in an open Internet of Things
 */

// Constant definitions
DEFAULT_SOCKET_URL = 'http://www.hyperlocalcontext.com/notman';
MAX_RSSI = 255;
DOUGHNUT_OPTIONS = {
  legend: {
    display: true,
    labels: {
      fontSize: 24,
      fontColor: "#fff"
    }
  }
};

/**
 * dashboard Module
 * All of the JavaScript specific to the dashboard is contained inside this
 * angular module.  The only external dependencies are:
 * - beaver, cormorant and cuttlefish (reelyActive)
 * - socket.io (btford)
 * - ngSanitize (angular)
 * - chart.js (jtblin)
 */
angular.module('dashboard', ['btford.socket-io', 'reelyactive.beaver',
                             'reelyactive.cormorant',
                             'reelyactive.cuttlefish', 'ngSanitize',
                             'chart.js'])

/**
 * Socket Factory
 * Creates the websocket connection to the given URL using socket.io.
 */
.factory('Socket', function(socketFactory) {
  return socketFactory({
    ioSocket: io.connect(DEFAULT_SOCKET_URL)
  });
})

/**
 * DashCtrl Controller
 * Handles the manipulation of all variables accessed by the HTML view.
 */
.controller('DashCtrl', function($scope, Socket, beaver, cormorant) {

  // Variables accessible in the HTML scope
  $scope.devices = beaver.getDevices();
  $scope.directories = beaver.getDirectories();
  $scope.stats = beaver.getStats();
  $scope.stories = cormorant.getStories();
  $scope.featuredDirectory = null;
  $scope.addFiller = true;
  $scope.doughnutLabels = [ '3', '2', '1', 'Cafe' ];
  $scope.doughnutData = [ 0, 0, 0, 0 ];
  $scope.doughnutColors = [ '#83b7d1', '#0770a2', '#043851', '#ff6900' ];
  $scope.doughnutOptions = DOUGHNUT_OPTIONS;
  $scope.numberOfDevices = 0;

  // beaver.js listens on the websocket for events
  beaver.listen(Socket);

  // Handle events pre-processed by beaver.js
  beaver.on('appearance', function(event) {
    handleEvent(event);
    updateDoughnut(event);
    beaver.addDeviceProperty(event.deviceId, 'featured', false);
  });
  beaver.on('displacement', function(event) {
    handleEvent(event);
    updateDoughnut(event);
  });
  beaver.on('keep-alive', function(event) {
    handleEvent(event);
  });
  beaver.on('disappearance', function(event) {
    handleEvent(event);
    updateDoughnut(event);
  });

  // Handle an event
  function handleEvent(event) {
    updateDeviceStory(event.deviceId, event.deviceUrl);
    updateDirectoryStory(event.receiverDirectory, event.receiverUrl);
    $scope.numberOfDevices = Object.keys($scope.devices).length;
  }

  // Update the device's story
  function updateDeviceStory(deviceId, url) {
    cormorant.getStory(url, function(story, url) {
      beaver.addDeviceProperty(deviceId, 'story', story);
      beaver.addDeviceProperty(deviceId, 'person', includesPerson(story));
    });
  }

  // Update the directory's story
  function updateDirectoryStory(directory, url) {
    cormorant.getStory(url, function(story, url) {
      if(story) {
        beaver.addDirectoryProperty(directory, 'story', story);
        beaver.addDirectoryProperty(directory, 'imageUrl',
                                    story['@graph'][0]['schema:image']);
      }
    });
  }

  // Update the doughnut chart
  function updateDoughnut(event) {
    $scope.doughnutData[0] = getNumberOfDirectoryDevices('notman:third:west')
                         + getNumberOfDirectoryDevices('notman:third:centre')
                         + getNumberOfDirectoryDevices('notman:third:east');
    $scope.doughnutData[1] = getNumberOfDirectoryDevices('notman:second:west')
                         + getNumberOfDirectoryDevices('notman:second:centre')
                         + getNumberOfDirectoryDevices('notman:second:east');
    $scope.doughnutData[2] = getNumberOfDirectoryDevices('notman:first:west')
                         + getNumberOfDirectoryDevices('notman:first:centre')
                         + getNumberOfDirectoryDevices('notman:first:east');
    $scope.doughnutData[3] = getNumberOfDirectoryDevices('notman:cafe');
  }

  // Get the number of devices in the given directory
  function getNumberOfDirectoryDevices(directory) {
    if(!$scope.directories.hasOwnProperty(directory)) {
      return 0;
    }
    return Object.keys($scope.directories[directory].devices).length;
  }

  // Verify if the story includes a Person
  function includesPerson(story) {
    if(story && story.hasOwnProperty('@graph')) {
      for(var cIndex = 0; cIndex < story['@graph'].length; cIndex++) {
        if(story['@graph'][cIndex].hasOwnProperty('@type') &&
           (story['@graph'][cIndex]['@type'] === 'schema:Person')) {
          return true;
        }
      }
    }
    return false;
  }

  // Update the featured directory and story
  function updateFeatured() {
    var people = 0;
    var products = 0;
    var newFeaturedDirectory = $scope.featuredDirectory;
    for(cDirectory in $scope.directories) {
      var currentPeople = 0;
      var currentProducts = 0;
      var currentDirectory = $scope.directories[cDirectory];
      for(cDevice in currentDirectory.devices) {
        if(currentDirectory.devices[cDevice].person) {
          currentPeople++;
        }
        if(currentDirectory.devices[cDevice].product) {
          currentProducts++;
        }
      }
      if(((currentPeople > people) ||
          ((people === 0) && (currentProducts > products))) &&
         (currentDirectory !== $scope.featuredDirectory)) {
        newFeaturedDirectory = currentDirectory;
      }
    }
    if(newFeaturedDirectory !== $scope.featuredDirectory) {
      $scope.featuredDirectory = newFeaturedDirectory;
    }
    else {
      var directories = Object.keys($scope.directories);
      var randomIndex = Math.floor(Math.random() * directories.length);
      $scope.featuredDirectory = $scope.directories[directories[randomIndex]];
    }

    var people = [];
    for(cDevice in $scope.devices) {
      beaver.addDeviceProperty(cDevice, 'featured', false);
      if($scope.devices[cDevice].person === true) {
        people.push(cDevice);
      }
    }
    if(people.length > 0) {
      $scope.addFiller = false;
      var featuredStoryIndex = Math.floor(Math.random() * people.length);
      beaver.addDeviceProperty(people[featuredStoryIndex], 'featured', true);
    }
    else {
      $scope.addFiller = true;
    }
  }

  setInterval(updateFeatured, 15000);
});
<|endoftext|>


<commit_before>'use strict'

var pretty = require('prettyjson')
var debug = require('debug')
var clor = require('clor')
var _ = debug('fly:log')

/**
 * Apply args to the `console[method]` & Add a date stamp.
 * Bind `this` to an object with the following options:
 *
 * @param  {String} args.date     The color string to use for the date
 * @param  {String} args.method   The `console` method to use
 * @param  {String} args.custom   The custom styling to append to args
 */
function stamp() {
	var args = [].slice.call(arguments)

	if (process.env.DEBUG) {
		return _.apply(_, args)
	}

	// print the curr time.
	process.stdout.write('[' + clor[this.color](timestamp()) + '] ')

	// apply arguments to `console` method
	console[this.method].apply(console, (this.custom ? [this.custom].concat(args) : args))
}

/**
 * Quickly format the current timestamp
 * @return {String}    as `HH:MM:ss`
 */
function timestamp() {
	var now = new Date()
	return [
		now.getHours(),
		now.getMinutes(),
		now.getSeconds()
	].join(':')
}

/**
 * Logging Utilities
 */

function log() {
	stamp.apply({method: 'log', color: 'magenta'}, arguments)
	return this
}

function error() {
	stamp.apply({method: 'error', color: 'red'}, arguments)
	return this
}

function alert() {
	if (process.env.VERBOSE) {
		stamp.apply({
			custom: clor.yellow.bold('%s'),
			method: 'log',
			color: 'yellow'
		}, arguments)
	}
	return this
}

/**
 * PrettyJSON wrapper & stack tracer
 * @param  {Object} e   The Error object
 */
function trace(e) {
	var home = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']
	var msg = pretty.render(e)
	    .replace(/(\sFunction|\sObject)\./g, clor.blue('$1') + '.')
	    .replace(/\((~?\/.*)\)/g, '(' + clor.gray('$1') + ')')
	    .replace(/:([0-9]*):([0-9]*)/g, ' ' + clor.yellow('$1') + ':' + clor.yellow('$2'))
	    .replace(new RegExp(home, 'g'), '~')
	console.error(msg)
}

module.exports = {
	alert: alert,
	error: error,
	log: log,
	stamp: stamp,
	trace: trace
}
<commit_msg>fix mixed spacing<commit_after>'use strict'

var pretty = require('prettyjson')
var debug = require('debug')
var clor = require('clor')
var _ = debug('fly:log')

/**
 * Apply args to the `console[method]` & Add a date stamp.
 * Bind `this` to an object with the following options:
 *
 * @param  {String} args.date     The color string to use for the date
 * @param  {String} args.method   The `console` method to use
 * @param  {String} args.custom   The custom styling to append to args
 */
function stamp() {
	var args = [].slice.call(arguments)

	if (process.env.DEBUG) {
		return _.apply(_, args)
	}

	// print the curr time.
	process.stdout.write('[' + clor[this.color](timestamp()) + '] ')

	// apply arguments to `console` method
	console[this.method].apply(console, (this.custom ? [this.custom].concat(args) : args))
}

/**
 * Quickly format the current timestamp
 * @return {String}    as `HH:MM:ss`
 */
function timestamp() {
	var now = new Date()
	return [
		now.getHours(),
		now.getMinutes(),
		now.getSeconds()
	].join(':')
}

/**
 * Logging Utilities
 */

function log() {
	stamp.apply({method: 'log', color: 'magenta'}, arguments)
	return this
}

function error() {
	stamp.apply({method: 'error', color: 'red'}, arguments)
	return this
}

function alert() {
	if (process.env.VERBOSE) {
		stamp.apply({
			custom: clor.yellow.bold('%s'),
			method: 'log',
			color: 'yellow'
		}, arguments)
	}
	return this
}

/**
 * PrettyJSON wrapper & stack tracer
 * @param  {Object} e   The Error object
 */
function trace(e) {
	var home = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']
	var msg = pretty.render(e)
		.replace(/(\sFunction|\sObject)\./g, clor.blue('$1') + '.')
		.replace(/\((~?\/.*)\)/g, '(' + clor.gray('$1') + ')')
		.replace(/:([0-9]*):([0-9]*)/g, ' ' + clor.yellow('$1') + ':' + clor.yellow('$2'))
		.replace(new RegExp(home, 'g'), '~')
	console.error(msg)
}

module.exports = {
	alert: alert,
	error: error,
	log: log,
	stamp: stamp,
	trace: trace
}
<|endoftext|>


<commit_before>var eventosJsonObject = [

	{
		"nome" : "UaiJUG First Party",
		"data" : "19/01/2016",
		"duracao" : "12",
		"id"   : "100001"
	},

	{
		"nome" : "UaiJUG FrontEnd Day",
		"data" : "16/04/2016",
		"duracao" :  "12",
		"id"   : "100002"
	},

	{
		"nome" : "UaiJUG FrontEnd Day",
		"data" : "19/11/2016",
		"duracao" :  "12",
		"id"   : "100003"
	}
]
<commit_msg>Correções certificados Last Party<commit_after>var eventosJsonObject = [

	{
		"nome" : "UaiJUG First Party",
		"data" : "19/01/2016",
		"duracao" : "12",
		"id"   : "100001"
	},

	{
		"nome" : "UaiJUG FrontEnd Day",
		"data" : "16/04/2016",
		"duracao" :  "12",
		"id"   : "100002"
	},

	{
		"nome" : "UaiJUG Last Party",
		"data" : "19/11/2016",
		"duracao" :  "12",
		"id"   : "100003"
	}
]
<|endoftext|>


<commit_before>//https://tympanus.net/Development/DragDropInteractions/icons.html

// use data-gs-id to get the change in data-gs-x and data-gs-y. Apply the change to adjacent grid to change the width in a responsive  way

//set the min and max height of grid
// data-gs-min-width="1" data-gs-max-width="9" data-gs-min-height="1" data-gs-max-height="4" data-gs-id="1"

//variable for grid
var x = 0,
  y = 0;

$(document).ready(function () {

  $('#sunburst').click(function () {
    createGridStack("sunbusrt");
  });

  $('#treemap').click(function () {
    createGridStack("treemap");
  });

});

function createGridStack(chartName) {

  var i = 1;
   var gridStack;

  //creating dynamic div element
  //if("x" == 0){
      gridStack = document.createElement('div');
      gridStack.className = 'grid-stack';
      gridStack.id = "chartContainer"
  //}

  var gridItem = document.createElement('div'),
    itemContent = document.createElement('div'),
    panelHeading = document.createElement('div'),
    panelBody = document.createElement('div');

  gridItem.className = 'grid-stack-item';
  itemContent.className = 'grid-stack-item-content panel panel-info';
  panelHeading.className = 'panel-heading';
  panelBody.className = 'panel-body';

  gridItem.id = "chartName" + i;
  i = i + 1;

  gridItem.setAttribute("data-gs-height","6");
  gridItem.setAttribute("data-gs-width","6");
  gridItem.setAttribute("data-gs-x","0");
  gridItem.setAttribute("data-gs-y","0");

  panelHeading.innerHTML += '
 "'+chartName+'"
'
  panelBody.innerHTML += '
 "'+chartName+'"
'

  itemContent.appendChild(panelHeading);
  itemContent.appendChild(panelBody);

  gridItem.appendChild(itemContent);
  gridStack.appendChild(gridItem);

  var pageWrapper = document.getElementById('page-content-wrapper');
      pageWrapper.appendChild(gridStack);

}

// variable to define custom grdistack behavior
var options = {
  animate: true,
  disableResize: false,
  disableDrag: false,
  resizable: {
    handles: 'e, w'
  }
};

// using options variable to change gridstack behavior
$('.grid-stack').gridstack(options);

$(document).ready(function () {
  var trigger = $('.hamburger'),
    isClosed = false;

  trigger.click(function () {
    hamburger_cross();
  });

  function hamburger_cross() {

    if (isClosed == true) {
      trigger.removeClass('is-open');
      trigger.addClass('is-closed');
      isClosed = false;
    } else {
      trigger.removeClass('is-closed');
      trigger.addClass('is-open');
      isClosed = true;
    }
  }

  $('[data-toggle="offcanvas"]').click(function () {
    $('#wrapper').toggleClass('toggled');
  });
});<commit_msg>add dynamic layout<commit_after>//https://tympanus.net/Development/DragDropInteractions/icons.html

// variable to define custom grdistack behavior
var options = {
  animate: true,
  disableResize: false,
  disableDrag: false,
  resizable: {
    handles: 'e, w'
  }
};

// using options variable to change gridstack behavior
$('.grid-stack').gridstack(options);

// use data-gs-id to get the change in data-gs-x and data-gs-y. Apply the change to adjacent grid to change the width in a responsive  way

//set the min and max height of grid
// data-gs-min-width="1" data-gs-max-width="9" data-gs-min-height="1" data-gs-max-height="4" data-gs-id="1"

//variable for grid
var x = 0,
  y = 0;
var gridStack;
var i = 1;

$(document).ready(function () {

  $('#sunburst').click(function () {
    createGridStack("sunbusrt");
  });

  $('#treemap').click(function () {
    createGridStack("treemap");
  });

});

function createGridStack(chartName) {

  //creating dynamic div element
  if( x == 0 ){
      gridStack = document.createElement('div');
      gridStack.className = 'grid-stack';
      gridStack.id = "chartContainer"
  }

  var gridItem = document.createElement('div'),
    itemContent = document.createElement('div'),
    panelHeading = document.createElement('div'),
    panelBody = document.createElement('div');

  gridItem.className = 'grid-stack-item';
  itemContent.className = 'grid-stack-item-content panel panel-info';
  panelHeading.className = 'panel-heading';
  panelBody.className = 'panel-body';

  gridItem.id = "chartName" + i;
  i = i + 1;

  gridItem.setAttribute("data-gs-height","6");
  gridItem.setAttribute("data-gs-width","6");
  gridItem.setAttribute("data-gs-x", x);
  gridItem.setAttribute("data-gs-y", y);

  panelHeading.innerHTML += '
 '+chartName+'
'
  panelBody.innerHTML += '
 add data to '+chartName+'
'

  itemContent.appendChild(panelHeading);
  itemContent.appendChild(panelBody);

  gridItem.appendChild(itemContent);
  gridStack.appendChild(gridItem);

  var pageWrapper = document.getElementById('page-content-wrapper');
      pageWrapper.appendChild(gridStack);

   x = x + 6;

  if(x == 12){
    x = 0;
    y = 0;
  }

  // using options variable to change gridstack behavior
  $('.grid-stack').gridstack(options);

}

$(document).ready(function () {
  var trigger = $('.hamburger'),
    isClosed = false;

  trigger.click(function () {
    hamburger_cross();
  });

  function hamburger_cross() {

    if (isClosed == true) {
      trigger.removeClass('is-open');
      trigger.addClass('is-closed');
      isClosed = false;
    } else {
      trigger.removeClass('is-closed');
      trigger.addClass('is-open');
      isClosed = true;
    }
  }

  $('[data-toggle="offcanvas"]').click(function () {
    $('#wrapper').toggleClass('toggled');
  });
});<|endoftext|>


<commit_before>/*
 * patron - The cleanest command framework for discord.js and eris.
 * Copyright (C) 2020  patron contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
"use strict";
const {regexes} = require("./constants.js");

function escapeMarkdown(string) {
  return string.replace(regexes.markdown, "\\$&");
}

function list(items, sep = "and") {
  if(items.length < 3)
    return items.join(` ${sep} `);

  return `${items.slice(0, -1).join(", ")} ${sep} ${items[items.length - 1]}`;
}

function max(string, amount) {
  if(string.length <= amount)
    return string;

  return `${string.slice(0, amount - 4)}...`;
}

function tag(user) {
  return `${user.username}#${user.discriminator}`;
}

function safeTag(user) {
  return `${this.escapeMarkdown(user.username)}#${user.discriminator}`;
}

module.exports = {
  escapeMarkdown,
  list,
  max,
  tag,
  safeTag
};
<commit_msg>Fix reader bug<commit_after>/*
 * patron - The cleanest command framework for discord.js and eris.
 * Copyright (C) 2020  patron contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
"use strict";
const {regexes} = require("./constants.js");

function escapeMarkdown(string) {
  return string.replace(regexes.markdown, "\\$&");
}

function list(items, sep = "and") {
  if(items.length < 3)
    return items.join(` ${sep} `);

  return `${items.slice(0, -1).join(", ")} ${sep} ${items[items.length - 1]}`;
}

function max(string, amount) {
  if(string.length <= amount)
    return string;

  return `${string.slice(0, amount - 4)}...`;
}

function tag(user) {
  return `${user.username}#${user.discriminator}`;
}

function safeTag(user) {
  return `${escapeMarkdown(user.username)}#${user.discriminator}`;
}

module.exports = {
  escapeMarkdown,
  list,
  max,
  tag,
  safeTag
};
<|endoftext|>


<commit_before>var card_width = 300;
var card_height = 186;
var half_card_width = card_width / 2;
var half_card_height = card_height / 2;

var next_outgoing_i = 0; /* the index of the next node that's outgoing */
var next_incoming_i = 0;

/* Which card is currently displayed in the middle of the screen? */
var current_card = null;

/* Height of rendered graph */
var graph_height = null;

var nodes = [];
var cards = [];
var relations = []; // relations are between nodes
var links = []; // links are between cards

var node0 = {
    "summary": "Why a max length of 140 characters? Well, it sure as hell works for Twitter. Seems like just enough to pack some good info into an argument.",
    "outgoing": [],
    "incoming": [node2],
}

var node1 = {
    "summary": "Taxation is theft.",
    "outgoing": [],
    "incoming": [node2],
}

var node2 = {
    "summary": "You pay taxes in exchange for voluntarily living in a country and using its public services.",
    "outgoing": [node0, node1],
    "incoming": [],
}

node0.incoming = [node2];
node1.incoming = [node2];

var link20 = {
    "from": node2,
    "to": node0,
    "type": "support"
}

var link21 = {
    "from": node2,
    "to": node1,
    "type": "oppose"
}

var nodes = [node2, node0, node1];
var relations = [link21, link20];
current_card = node2;

function is_outgoing(node) {
    return current_card.outgoing.indexOf(node) != -1;
}

function is_incoming(node) {
    return current_card.incoming.indexOf(node) != -1;
}

function currently_displayed(node) {
    return (node == current_card) || is_outgoing(node) || is_incoming(node);
}

function x_pos(node) {
    if (node == current_card) {
        node.i = 0; // doesn't matter for current_card
        return (window.innerWidth / 2) - half_card_width;
    } else if (is_outgoing(node)) {
        if (node.i == null) {
            node.i = next_outgoing_i;
            next_outgoing_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else if (is_incoming(node)) {
        if (node.i == null) {
            node.i = next_incoming_i;
            next_incoming_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else {
        if (node.previously_current) {
            return window.innerWidth + 10;
        } else if (node.previously_outgoing) {
            return (window.innerWidth / 2) - half_card_width;
        }
    }
}

function y_pos(node) {
    if (node == current_card) {
        return (graph_height / 2) - half_card_height;
    } else if (is_outgoing(node)) {
        return 10;
    } else if (is_incoming(node)) {
        return graph_height - 10 - card_height;
    } else {
        if (node.previously_current) {
            return (graph_height / 2) - half_card_height;
        } else if (node.previously_outgoing) {
            return -10 - card_height;
        } else {
            console.log(node);
        }
    }
}

function pos2str(pos) {
    return pos[0] + "," + pos[1] + " ";
}

function compute_link_bezier_curve(link) {
    var from = link.from;
    var to = link.to;
    var start_pos = [x_pos(from, from.i) + half_card_width, y_pos(from, from.i)];
    var end_pos = [x_pos(to, to.i) + half_card_width,
                    /* marker-widht is 3, stroke-width is 5 */
                   y_pos(to, to.i) + card_height + (5 * 3)];
    var height = end_pos[1] - start_pos[1];
    var control1 = [start_pos[0], start_pos[1] + (height / 2)];
    var control2 = [end_pos[0], end_pos[1] - (height / 2)];
    return "M" + pos2str(start_pos) + "C" + pos2str(control1)
            + pos2str(control2) + pos2str(end_pos);
}

function reset_globals() {
    for (var i=0; i < nodes.length; i++) {
        node = nodes[i];
        node.i = null;
    }
    next_outgoing_i = 0;
    next_incoming_i = 0;
}

function make_cards() {
    var svg = d3.select("svg#graph");
    cards = svg.selectAll("g").data(nodes);
    new_cards = cards.enter().append("g").classed("argument", true);
    new_cards.append("rect").attr("width", card_width).attr("height", card_height);
    var switch_objects = new_cards.append("switch");
    switch_objects.append("foreignObject").classed("foreign-object", true)
            .attr("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility")
            .attr("width", card_width).attr("height", card_height)
            .append("xhtml:div").classed("summary", true).append("p")
            .classed("summary", true).text(function (d) {
                return d.summary;
            }).attr("xmlns", "http://www.w3.org/1999/xhtml");
    switch_objects.append("text").attr("x", x_pos).attr("y", y_pos)
        .text("Sorry, your browser is not supported.");
    new_cards.on("click", function (d) {
        current_card = d;
        draw_graph();
    })
}

function make_links() {
    var svg = d3.select("svg#graph");
    links = svg.selectAll("path").data(relations);
    links.enter().append("path")
        .attr("class", function(d) {
            return d.type;
        }).attr("d", compute_link_bezier_curve)
        .attr("marker-end", function(d) {
            return "url(#arrow-" + d.type + ")"
        });
}

function draw_graph() {
    reset_globals();
    make_cards();
    make_links();

    var svg = d3.select("svg#graph");
    d3.selectAll("g rect").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    // http://stackoverflow.com/a/11743721/257583
    d3.selectAll(".foreign-object").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    cards.each(function (d) {
        d.previously_current = false;
        d.previously_outgoing = false;

        if (current_card == d) {
            d.previously_current = true;
        } else if (is_outgoing(d)) {
            d.previously_outgoing = true;
        }
    });
    links.transition().duration(150).attr("opacity", function (d) {
        // if one end of the link is currently displayed, then the other is too
        if (currently_displayed(d.from)) {
            return 1;
        } else {
            return 0;
        }
    })
}

window.onload = function () {
    graph_height = $("#graph").height();
    draw_graph();
}<commit_msg>Toggle link visibility when selecting card<commit_after>var card_width = 300;
var card_height = 186;
var half_card_width = card_width / 2;
var half_card_height = card_height / 2;

var next_outgoing_i = 0; /* the index of the next node that's outgoing */
var next_incoming_i = 0;

/* Which card is currently displayed in the middle of the screen? */
var current_card = null;

/* Height of rendered graph */
var graph_height = null;

var nodes = [];
var cards = [];
var relations = []; // relations are between nodes
var links = []; // links are between cards

var node0 = {
    "summary": "Why a max length of 140 characters? Well, it sure as hell works for Twitter. Seems like just enough to pack some good info into an argument.",
    "outgoing": [],
    "incoming": [node2],
}

var node1 = {
    "summary": "Taxation is theft.",
    "outgoing": [],
    "incoming": [node2],
}

var node2 = {
    "summary": "You pay taxes in exchange for voluntarily living in a country and using its public services.",
    "outgoing": [node0, node1],
    "incoming": [],
}

node0.incoming = [node2];
node1.incoming = [node2];

var link20 = {
    "from": node2,
    "to": node0,
    "type": "support"
}

var link21 = {
    "from": node2,
    "to": node1,
    "type": "oppose"
}

var nodes = [node2, node0, node1];
var relations = [link21, link20];
current_card = node2;

function is_outgoing(node) {
    return current_card.outgoing.indexOf(node) != -1;
}

function is_incoming(node) {
    return current_card.incoming.indexOf(node) != -1;
}

function node_visible(node) {
    return (node == current_card) || is_outgoing(node) || is_incoming(node);
}

function link_visible(link) {
    // both ends of a link must be visible for a link to be visible
    return node_visible(link.from) && node_visible(link.to);
}

function x_pos(node) {
    if (node == current_card) {
        node.i = 0; // doesn't matter for current_card
        return (window.innerWidth / 2) - half_card_width;
    } else if (is_outgoing(node)) {
        if (node.i == null) {
            node.i = next_outgoing_i;
            next_outgoing_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else if (is_incoming(node)) {
        if (node.i == null) {
            node.i = next_incoming_i;
            next_incoming_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else {
        if (node.previously_current) {
            return window.innerWidth + 10;
        } else if (node.previously_outgoing) {
            return (window.innerWidth / 2) - half_card_width;
        }
    }
}

function y_pos(node) {
    if (node == current_card) {
        return (graph_height / 2) - half_card_height;
    } else if (is_outgoing(node)) {
        return 10;
    } else if (is_incoming(node)) {
        return graph_height - 10 - card_height;
    } else {
        if (node.previously_current) {
            return (graph_height / 2) - half_card_height;
        } else if (node.previously_outgoing) {
            return -10 - card_height;
        } else {
            console.log(node);
        }
    }
}

function pos2str(pos) {
    return pos[0] + "," + pos[1] + " ";
}

function compute_link_bezier_curve(link) {
    var from = link.from;
    var to = link.to;
    var start_pos = [x_pos(from, from.i) + half_card_width, y_pos(from, from.i)];
    var end_pos = [x_pos(to, to.i) + half_card_width,
                    /* marker-widht is 3, stroke-width is 5 */
                   y_pos(to, to.i) + card_height + (5 * 3)];
    var height = end_pos[1] - start_pos[1];
    var control1 = [start_pos[0], start_pos[1] + (height / 2)];
    var control2 = [end_pos[0], end_pos[1] - (height / 2)];
    return "M" + pos2str(start_pos) + "C" + pos2str(control1)
            + pos2str(control2) + pos2str(end_pos);
}

function reset_globals() {
    for (var i=0; i < nodes.length; i++) {
        node = nodes[i];
        node.i = null;
    }
    next_outgoing_i = 0;
    next_incoming_i = 0;
}

function make_cards() {
    var svg = d3.select("svg#graph");
    cards = svg.selectAll("g").data(nodes);
    new_cards = cards.enter().append("g").classed("argument", true);
    new_cards.append("rect").attr("width", card_width).attr("height", card_height);
    var switch_objects = new_cards.append("switch");
    switch_objects.append("foreignObject").classed("foreign-object", true)
            .attr("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility")
            .attr("width", card_width).attr("height", card_height)
            .append("xhtml:div").classed("summary", true).append("p")
            .classed("summary", true).text(function (d) {
                return d.summary;
            }).attr("xmlns", "http://www.w3.org/1999/xhtml");
    switch_objects.append("text").attr("x", x_pos).attr("y", y_pos)
        .text("Sorry, your browser is not supported.");
    new_cards.on("click", function (d) {
        current_card = d;
        draw_graph();
    })
}

function make_links() {
    var svg = d3.select("svg#graph");
    links = svg.selectAll("path").data(relations);
    links.enter().append("path")
        .attr("class", function(d) {
            return d.type;
        });
}

function draw_graph() {
    reset_globals();
    make_cards();
    make_links();

    var svg = d3.select("svg#graph");
    d3.selectAll("g rect").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    // http://stackoverflow.com/a/11743721/257583
    d3.selectAll(".foreign-object").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    cards.each(function (d) {
        d.previously_current = false;
        d.previously_outgoing = false;

        if (current_card == d) {
            d.previously_current = true;
        } else if (is_outgoing(d)) {
            d.previously_outgoing = true;
        }
    });
    links.transition().duration(500).style("opacity", function (d) {
        // if one end of the link is currently displayed, then the other is too
        if (link_visible(d)) {
            return 1;
        } else {
            return 0;
        }
    }).attr("d", compute_link_bezier_curve).attr("marker-end", function(d) {
        if (link_visible(d)) {
            return "url(#arrow-" + d.type + ")";
        } else {
            return "";
        }
    });
}

window.onload = function () {
    graph_height = $("#graph").height();
    draw_graph();
}<|endoftext|>


<commit_before>/*
 * redis-locking-promise-memoizer
 * https://github.com/pwmckenna/node-redis-locking-promise-memoizer
 *
 * Copyright (c) 2014 Patrick Williams
 * Licensed under the MIT license.
 */

'use strict';

var assert = require('assert');{}
var crypto = require('crypto');
var redis = require('redis');
var redisLock = require('redis-lock');
var q = require('q');

var hash = function (string) {
    return crypto.createHmac('sha1', 'memo').update(string).digest('hex');
};

module.exports = function () {
    var client = redis.createClient.apply(null, arguments);
    var lock = redisLock(client);

    var getRedisKeyValue = function (key) {
        var getRequest = q.defer();
        client.get(key, getRequest.makeNodeResolver());
        return getRequest.promise.then(function (value) {
            assert(typeof value === 'string');
            return JSON.parse(value);
        });
    };

    var setRedisKeyValue = function (key, value, ttl) {
        var setRequest = q.defer();
        client.psetex(key, ttl, JSON.stringify(value), setRequest.makeNodeResolver());
        return setRequest.promise;
    };

    return function memoize (fn, ttl) {
        var functionName = fn.toString();
        var functionKey = hash(functionName);

        return function () {
            var context = this;
            var args = Array.prototype.slice.call(arguments);
            var argumentsKey = hash(args.map(function(arg) { return JSON.stringify(arg); }).join(","));
            var key = 'memos:' + functionKey + ':' + argumentsKey;

            return q.resolve().then(function () {
                return getRedisKeyValue(key);
            }).fail(function () {
                var lockedOperationRequest = q.defer();
                lock(key, function(done) {
                    var setRequest = q.resolve().then(function () {
                        return getRedisKeyValue(key);
                    }).fail(function () {
                        return q.resolve().then(function () {
                            return fn.apply(context, args);
                        }).then(function (value) {
                            return setRedisKeyValue(key, value, ttl).thenResolve(value);
                        });
                    });
                    setRequest.nodeify(done);
                    lockedOperationRequest.resolve(setRequest);
                });
                return lockedOperationRequest.promise;
            });
        };
    };
};
<commit_msg>simplifying hasher<commit_after>/*
 * redis-locking-promise-memoizer
 * https://github.com/pwmckenna/node-redis-locking-promise-memoizer
 *
 * Copyright (c) 2014 Patrick Williams
 * Licensed under the MIT license.
 */

'use strict';

var assert = require('assert');{}
var crypto = require('crypto');
var redis = require('redis');
var redisLock = require('redis-lock');
var q = require('q');

var hash = function (string) {
    return crypto.createHmac('sha1', 'memo').update(string).digest('hex');
};

module.exports = function () {
    var client = redis.createClient.apply(null, arguments);
    var lock = redisLock(client);

    var getRedisKeyValue = function (key) {
        var getRequest = q.defer();
        client.get(key, getRequest.makeNodeResolver());
        return getRequest.promise.then(function (value) {
            assert(typeof value === 'string');
            return JSON.parse(value);
        });
    };

    var setRedisKeyValue = function (key, value, ttl) {
        var setRequest = q.defer();
        client.psetex(key, ttl, JSON.stringify(value), setRequest.makeNodeResolver());
        return setRequest.promise;
    };

    return function memoize (fn, ttl) {
        var functionName = fn.toString();
        var functionKey = hash(functionName);

        return function () {
            var context = this;
            var args = Array.prototype.slice.call(arguments);
            var argumentsKey = hash(args.map(JSON.stringify).join(","));
            var key = 'memos:' + functionKey + ':' + argumentsKey;

            return q.resolve().then(function () {
                return getRedisKeyValue(key);
            }).fail(function () {
                var lockedOperationRequest = q.defer();
                lock(key, function(done) {
                    var setRequest = q.resolve().then(function () {
                        return getRedisKeyValue(key);
                    }).fail(function () {
                        return q.resolve().then(function () {
                            return fn.apply(context, args);
                        }).then(function (value) {
                            return setRedisKeyValue(key, value, ttl).thenResolve(value);
                        });
                    });
                    setRequest.nodeify(done);
                    lockedOperationRequest.resolve(setRequest);
                });
                return lockedOperationRequest.promise;
            });
        };
    };
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');

var EndpointAlreadyDefinedError = TypedError({
    type: 'endpoint-already-defined',
    message: 'endpoint {endpoint} already defined on service {service}',
    service: null,
    endpoint: null,
    oldHandler: null,
    newHandler:  null
});

var InvalidHandlerError = TypedError({
    type: 'invalid-handler',
    message: 'invalid handler function'
});

var NoSuchEndpointError = TypedError({
    type: 'no-such-endpoint',
    message: 'no such endpoint {endpoint} on service {service}',
    service: null,
    endpoint: null
});

function TChannelEndpointHandler(serviceName) {
    if (!(this instanceof TChannelEndpointHandler)) {
        return new TChannelEndpointHandler(serviceName);
    }
    var self = this;
    self.serviceName = serviceName;
    self.endpoints = Object.create(null);
    self.type = null;
}

TChannelEndpointHandler.prototype.register = function register(name, handler) {
    var self = this;
    if (self.endpoints[name] !== undefined) {
        throw EndpointAlreadyDefinedError({
            service: self.serviceName,
            endpoint: name,
            oldHandler: self.endpoints[name],
            newHandler: handler
        });
    }
    if (typeof handler !== 'function') {
        throw InvalidHandlerError();
    }
    self.endpoints[name] = handler;
    return handler;
};

TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, res) {
    var self = this;
    var name = String(req.arg1);
    var handler = self.endpoints[name];
    if (!handler) {
        res.sendNotOk(null, NoSuchEndpointError({
            service: self.serviceName,
            endpoint: name
        }).message);
        return;
    }
    handler(req, res);
};

module.exports = TChannelEndpointHandler;
<commit_msg>endpoint-handler: support streaming<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var TypedError = require('error/typed');

var EndpointAlreadyDefinedError = TypedError({
    type: 'endpoint-already-defined',
    message: 'endpoint {endpoint} already defined on service {service}',
    service: null,
    endpoint: null,
    oldHandler: null,
    newHandler:  null
});

var InvalidHandlerError = TypedError({
    type: 'invalid-handler',
    message: 'invalid handler function'
});

var NoSuchEndpointError = TypedError({
    type: 'no-such-endpoint',
    message: 'no such endpoint {endpoint} on service {service}',
    service: null,
    endpoint: null
});

function TChannelEndpointHandler(serviceName) {
    if (!(this instanceof TChannelEndpointHandler)) {
        return new TChannelEndpointHandler(serviceName);
    }
    var self = this;
    self.serviceName = serviceName;
    self.endpoints = Object.create(null);
    self.type = null;
}

TChannelEndpointHandler.prototype.register = function register(name, handler) {
    var self = this;
    if (self.endpoints[name] !== undefined) {
        throw EndpointAlreadyDefinedError({
            service: self.serviceName,
            endpoint: name,
            oldHandler: self.endpoints[name],
            newHandler: handler
        });
    }
    if (typeof handler !== 'function') {
        throw InvalidHandlerError();
    }
    self.endpoints[name] = handler;
    return handler;
};

TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, res) {
    var self = this;
    // TODO: waterfall
    req.arg1.onValueReady(function arg1Ready(err, arg1) {
        if (err) throw err; // TODO: protocol error, respond with error frame
        var name = String(arg1);
        var handler = self.endpoints[name];
        if (!handler) {
            res.sendNotOk(null, NoSuchEndpointError({
                service: self.serviceName,
                endpoint: name
            }).message);
            return;
        }
        if (handler.canStream) {
            handler(req, res);
        } else {
            parallel({
                arg2: req.arg2.onValueReady,
                arg3: req.arg3.onValueReady
            }, function argsDone(err, args) {
                if (err) throw err; // TODO: protocol error, respond with error frame
                else handler(req, res, args.arg2, args.arg3);
            });
        }
    });
};

module.exports = TChannelEndpointHandler;
<|endoftext|>


<commit_before>/*global

$: true,
Player: true,
extractArtist: true,
showResultsItemContextMenu: true,

*/

function video_Init() {
    $('#info .share').click(function() {
        var videoId = Player.getCurrentVideoId();
        var title = $('#info .title').text();
        var elem = $('#info');
        showVideoSharePopup(videoId, title, elem, 'left');
    });
}

function showVideoSharePopup(videoId, title, elem, arrowDirection) {
    var video = new Video(videoId, title);

    $('#share-video-popup .link input').val(video.getUrl());

    $('#share-video-popup .twitter')
        .unbind('click')
        .click(function(event) {
            event.preventDefault();
            window.open(video.getTwitterShareUrl(), 'Share video on Twitter', 400, 400);
            return false;
        });

    $('#share-video-popup .facebook')
        .unbind('click')
        .click(function(event) {
            event.preventDefault();
            window.open(video.getFacebookShareUrl(), 'Share video on Facebook', 400, 400);
            return false;
        });

    elem.arrowPopup('#share-video-popup', arrowDirection);
}

function Video(videoId, title, type, rating) {
    this.videoId = videoId;
    this.title = $.trim(title) || '';
    this.artist = extractArtist(this.title);
    this.type = type;
    this.rating = rating;
    this.listView = null;

    this.clone = function() {
        return new Video(this.videoId, this.title, this.type, this.rating);
    };

    this.getUrl = function() {
        return location.protocol + '//' + location.host + '/videos/' + this.videoId;
    };

    this.getYouTubeUrl = function() {
        return 'http://www.youtube.com/watch?v=' + this.videoId;
    },

    this.getTwitterShareUrl = function() {
        var url = this.getUrl(),
            text = "Check out this video!" + ' -- ' + this.title;
        return encodeURI('http://twitter.com/share?related=youtify&via=youtify' + '&url=' + url + '&counturl=' + url + '&text=' + text);
    };

    this.getFacebookShareUrl = function() {
        var url = this.getUrl();
        return 'http://facebook.com/sharer.php?u=' + url;
    };

    this.createListView = function() {
        var space = $('	'),
            self = this,
            select = (function(event) {
                    self.listViewSelect(event);
                    event.stopPropagation();
                }),
            play = (function(event) {
                    self.play();
                });

        this.listView = $('
')
            .addClass("draggable")
            .addClass("video")
            .bind('contextmenu', showResultsItemContextMenu)
            .click(select)
            .data('model', self);

        $('▶	')
            .click(play)
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        var titleElem = $('')
            .click(select)
            .text(this.title)
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        $('♥	')
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        $('')
            .text(this.getRatingAsString())
            .appendTo(this.listView);

        this.listView.dblclick(play);
        titleElem.dblclick(play);

        return this.listView;
    };

    this.getRatingAsString = function() {
        return (this.rating === undefined ? 0 : this.rating.toFixed(1));
    };

    this.listViewSelect = function(event) {
        if (event !== undefined && (event.ctrlKey || event.metaKey)) {
            if (this.listView.hasClass('selected')) {
                this.listView.removeClass('selected');
            } else {
                this.listView.addClass('selected');
            }
        } else if (event !== undefined && event.shiftKey &&  this.listView.siblings('.selected').length > 0) {
            var elements = [this.listView],
                found = false;

            // search down
            while (!found && $(elements[0]).next().length > 0) {
                elements.unshift(elements[0].next());
                if ($(elements[0]).hasClass('selected')) {
                    found = true;
                }
            }
            if (!found) {
                elements = [li];
                // search up
                while (!found && $(elements[0]).prev().length > 0) {
                    elements.unshift(elements[0].prev());
                    if ($(elements[0]).hasClass('selected')) {
                        found = true;
                    }
                }
            }
            $(elements).each(function(index, item) {
                $(item).addClass('selected');
            });
        } else {
            console.log('got here', this.listView);
            this.listView.siblings().removeClass('selected');
            this.listView.addClass('selected');
        }
    };

    this.play = function() {
        $('#left li').removeClass('playing');
/*        if (owner) { // playlist
            Player.addSiblingsToPlayorder(this.listView);
            if (owner.leftMenuDOMHandle) {
                owner.leftMenuDOMHandle.addClass('playing');
            }
        } else {
            Player.addSiblingsToPlayorder(this.listView, false);
        }*/

        $('#right .video').removeClass('playing');
        this.listView.addClass("playing");

        Player.play(this);
    };
}

/*
function createResultsItem(title, videoId, rating, isPlaylistItem) {
    var artist = extractArtist(title);
    var additionalMenuButtons = [];

    var li = $('
')
        .addClass("draggable")
        .addClass("video")
        .data('type', 'video') // used for drag n drop
        .data('videoId', videoId)
        .attr('rel', videoId)
        .bind('contextmenu', showResultsItemContextMenu)
        .click(function(event) {
            selectVideo($(this), event);
            event.stopPropagation();
        });

    $('</span')
        .addClass('contextmenu')
        .addClass('clickable')
        .text('▽')
        .click(function(event) {
            var li = $(this).parent();
            li.trigger('contextmenu');
        })
        .appendTo(li);

    if (artist) {
        additionalMenuButtons.push({
            title: 'More from ' + artist,
            args: li,
            callback: function(li) {
                var artist = extractArtist(li.text());
                $('#search input').val(artist).keyup();
            }
        });
    }

    li.data('additionalMenuButtons', additionalMenuButtons);

    if (isPlaylistItem) {
        li.data('additionalMenuButtons').push({
            title: 'Delete',
            args: li,
            callback: deleteVideoButtonClicked
        });
        li.addClass('droppable');
        li.addClass('draggable');
        li.addClass('reorderable');
    }
    return li;
}
*/
<commit_msg>Fix bug where playlists could not be saved<commit_after>/*global

$: true,
Player: true,
extractArtist: true,
showResultsItemContextMenu: true,

*/

function video_Init() {
    $('#info .share').click(function() {
        var videoId = Player.getCurrentVideoId();
        var title = $('#info .title').text();
        var elem = $('#info');
        showVideoSharePopup(videoId, title, elem, 'left');
    });
}

function showVideoSharePopup(videoId, title, elem, arrowDirection) {
    var video = new Video(videoId, title);

    $('#share-video-popup .link input').val(video.getUrl());

    $('#share-video-popup .twitter')
        .unbind('click')
        .click(function(event) {
            event.preventDefault();
            window.open(video.getTwitterShareUrl(), 'Share video on Twitter', 400, 400);
            return false;
        });

    $('#share-video-popup .facebook')
        .unbind('click')
        .click(function(event) {
            event.preventDefault();
            window.open(video.getFacebookShareUrl(), 'Share video on Facebook', 400, 400);
            return false;
        });

    elem.arrowPopup('#share-video-popup', arrowDirection);
}

function Video(videoId, title, type, rating) {
    this.videoId = videoId;
    this.title = $.trim(title) || '';
    this.artist = extractArtist(this.title);
    this.type = type;
    this.rating = rating;
    this.listView = null;

    this.clone = function() {
        return new Video(this.videoId, this.title, this.type, this.rating);
    };

    this.getUrl = function() {
        return location.protocol + '//' + location.host + '/videos/' + this.videoId;
    };

    this.getYouTubeUrl = function() {
        return 'http://www.youtube.com/watch?v=' + this.videoId;
    },

    this.getTwitterShareUrl = function() {
        var url = this.getUrl(),
            text = "Check out this video!" + ' -- ' + this.title;
        return encodeURI('http://twitter.com/share?related=youtify&via=youtify' + '&url=' + url + '&counturl=' + url + '&text=' + text);
    };

    this.getFacebookShareUrl = function() {
        var url = this.getUrl();
        return 'http://facebook.com/sharer.php?u=' + url;
    };

    this.createListView = function() {
        var space = $('	'),
            self = this,
            select = (function(event) {
                    self.listViewSelect(event);
                    event.stopPropagation();
                }),
            play = (function(event) {
                    self.play();
                });

        this.listView = $('
')
            .addClass("draggable")
            .addClass("video")
            .bind('contextmenu', showResultsItemContextMenu)
            .click(select)
            .data('model', self);

        $('▶	')
            .click(play)
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        var titleElem = $('')
            .click(select)
            .text(this.title)
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        $('♥	')
            .appendTo(this.listView);
        space.clone().appendTo(this.listView);

        $('')
            .text(this.getRatingAsString())
            .appendTo(this.listView);

        this.listView.dblclick(play);
        titleElem.dblclick(play);

        return this.listView;
    };

    this.getRatingAsString = function() {
        return (this.rating === undefined ? 0 : this.rating.toFixed(1));
    };

    this.listViewSelect = function(event) {
        if (event !== undefined && (event.ctrlKey || event.metaKey)) {
            if (this.listView.hasClass('selected')) {
                this.listView.removeClass('selected');
            } else {
                this.listView.addClass('selected');
            }
        } else if (event !== undefined && event.shiftKey &&  this.listView.siblings('.selected').length > 0) {
            var elements = [this.listView],
                found = false;

            // search down
            while (!found && $(elements[0]).next().length > 0) {
                elements.unshift(elements[0].next());
                if ($(elements[0]).hasClass('selected')) {
                    found = true;
                }
            }
            if (!found) {
                elements = [li];
                // search up
                while (!found && $(elements[0]).prev().length > 0) {
                    elements.unshift(elements[0].prev());
                    if ($(elements[0]).hasClass('selected')) {
                        found = true;
                    }
                }
            }
            $(elements).each(function(index, item) {
                $(item).addClass('selected');
            });
        } else {
            console.log('got here', this.listView);
            this.listView.siblings().removeClass('selected');
            this.listView.addClass('selected');
        }
    };

    this.play = function() {
        $('#left li').removeClass('playing');
/*        if (owner) { // playlist
            Player.addSiblingsToPlayorder(this.listView);
            if (owner.leftMenuDOMHandle) {
                owner.leftMenuDOMHandle.addClass('playing');
            }
        } else {
            Player.addSiblingsToPlayorder(this.listView, false);
        }*/

        $('#right .video').removeClass('playing');
        this.listView.addClass("playing");

        Player.play(this);
    };

    this.toJSON = function() {
        return {
            'videoId': this.videoId,
            'title': this.title
        };
    };
}

/*
function createResultsItem(title, videoId, rating, isPlaylistItem) {
    var artist = extractArtist(title);
    var additionalMenuButtons = [];

    var li = $('
')
        .addClass("draggable")
        .addClass("video")
        .data('type', 'video') // used for drag n drop
        .data('videoId', videoId)
        .attr('rel', videoId)
        .bind('contextmenu', showResultsItemContextMenu)
        .click(function(event) {
            selectVideo($(this), event);
            event.stopPropagation();
        });

    $('</span')
        .addClass('contextmenu')
        .addClass('clickable')
        .text('▽')
        .click(function(event) {
            var li = $(this).parent();
            li.trigger('contextmenu');
        })
        .appendTo(li);

    if (artist) {
        additionalMenuButtons.push({
            title: 'More from ' + artist,
            args: li,
            callback: function(li) {
                var artist = extractArtist(li.text());
                $('#search input').val(artist).keyup();
            }
        });
    }

    li.data('additionalMenuButtons', additionalMenuButtons);

    if (isPlaylistItem) {
        li.data('additionalMenuButtons').push({
            title: 'Delete',
            args: li,
            callback: deleteVideoButtonClicked
        });
        li.addClass('droppable');
        li.addClass('draggable');
        li.addClass('reorderable');
    }
    return li;
}
*/
<|endoftext|>


<commit_before><commit_msg>Remove empty file<commit_after><|endoftext|>


<commit_before>var parser;
var treeData;
var changeSize = function(target, delta) {
    target.setOption('fontSize', target.getOption('fontSize') + delta);
};
var setSize = function(target, size) {
    target.setOption('fontSize', size);
};
$('document').ready(function() {
    // Create the PEG editor
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

    // No static JS analysis
    editor.setOption("useWorker", false);

    // Personal preferences:
    editor.setOption("tabSize", 2);
    editor.setOption('scrollPastEnd', 100);

    // Store retrieve text
    editor.setValue(localStorage["grammar"]);
    if (editor.getValue !== "") {
        $('#build_parser_btn').click();
    }

    editor.getSession().on("change", function() {
        localStorage.setItem("grammar", editor.getValue());
        if ($('#auto-build').prop('checked')) {
            $('#build_parser_btn').click();
        }
    });

    // Resize editor
    $('#editor').css("height", window.innerHeight);
    editor.resize();

    // Create parse string editor
    output = ace.edit("output");
    output.setOption("useWorker", false);
    output.setValue(localStorage["source"]);
    output.getSession().on('change', function() {
        localStorage.setItem("source", output.getValue());
        $('#parse_btn').click();
    });

    $('#output').css('height', window.innerHeight / 2);
    output.resize();
    $('#build_parser_btn').click(function() {
        try {
            editor.getSession().clearAnnotations();
            parser = PEG.buildParser(editor.getValue());
            $('.alert-warning').remove();
        } catch (exn) {
            $('#treediv').html('
Grammar Error: ' + exn.message + '
');
            console.log(exn);
            //if (!editor.getSession().$annotations) {
            editor.getSession().$annotations = [];
            //}

            var myAnno = {
                "column": exn['column'],
                "row": exn['line'] - 1,
                "type": "error",
                "raw": exn['message'],
                "text": exn['message']
            };

            editor.getSession().$annotations.push(myAnno);
            editor.getSession().setAnnotations(editor.getSession().$annotations);
        } // catch(exn)

    });

    $('#parse_btn').click(function(e) {
        e.preventDefault();

        // If a parser hasn't been built, build one:
        if (!parser) {
            $('#build_parser_btn').click();
        }

        // Now parse!
        try {
            result = parser.parse(output.getValue());
            treeData = result;
            $('.alert').remove();
            doTree();

            // Log any parse errors in the console:
        } catch (e) {
            $('#treediv').html('
Parse Error: ' + e.message + '
');
            console.error(e);
        }
    });

    $('#peg-zoom-in').click(function() {
        changeSize(editor, 2);
        changeSize(output, 2);

    });
    $('#peg-zoom-out').click(function() {
        changeSize(editor, -2);
        changeSize(output, -2);
    });
    $('#peg-reset').click(function() {
        setSize(editor, 14);
        setSize(output, 14);
    });
    $(output).focus(function() {
        if (editor.getValue()) {
            $('#build_parser_btn').click();
        }
    });

    $('#peg_editor a').click(function(e) {
        e.preventDefault();

    });
    $('#peg_editor_settings').click(function(e) {
        e.preventDefault();

        editor.execCommand('showSettingsMenu');
    });

    $('#tree-reset').click(function() {
        $('#parse_btn').click();
    });
});<commit_msg>Reduced scrollPastEnd to 40 lines.<commit_after>var parser;
var treeData;
var changeSize = function(target, delta) {
    target.setOption('fontSize', target.getOption('fontSize') + delta);
};
var setSize = function(target, size) {
    target.setOption('fontSize', size);
};
$('document').ready(function() {
    // Create the PEG editor
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

    // No static JS analysis
    editor.setOption("useWorker", false);

    // Personal preferences:
    editor.setOption("tabSize", 2);
    editor.setOption('scrollPastEnd', '40');

    // Store retrieve text
    editor.setValue(localStorage["grammar"]);
    if (editor.getValue !== "") {
        $('#build_parser_btn').click();
    }

    editor.getSession().on("change", function() {
        localStorage.setItem("grammar", editor.getValue());
        if ($('#auto-build').prop('checked')) {
            $('#build_parser_btn').click();
        }
    });

    // Resize editor
    $('#editor').css("height", window.innerHeight);
    editor.resize();

    // Create parse string editor
    output = ace.edit("output");
    output.setOption("useWorker", false);
    output.setValue(localStorage["source"]);
    output.getSession().on('change', function() {
        localStorage.setItem("source", output.getValue());
        $('#parse_btn').click();
    });

    $('#output').css('height', window.innerHeight / 2);
    output.resize();
    $('#build_parser_btn').click(function() {
        try {
            editor.getSession().clearAnnotations();
            parser = PEG.buildParser(editor.getValue());
            $('.alert-warning').remove();
        } catch (exn) {
            $('#treediv').html('
Grammar Error: ' + exn.message + '
');
            console.log(exn);
            //if (!editor.getSession().$annotations) {
            editor.getSession().$annotations = [];
            //}

            var myAnno = {
                "column": exn['column'],
                "row": exn['line'] - 1,
                "type": "error",
                "raw": exn['message'],
                "text": exn['message']
            };

            editor.getSession().$annotations.push(myAnno);
            editor.getSession().setAnnotations(editor.getSession().$annotations);
        } // catch(exn)

    });

    $('#parse_btn').click(function(e) {
        e.preventDefault();

        // If a parser hasn't been built, build one:
        if (!parser) {
            $('#build_parser_btn').click();
        }

        // Now parse!
        try {
            result = parser.parse(output.getValue());
            treeData = result;
            $('.alert').remove();
            doTree();

            // Log any parse errors in the console:
        } catch (e) {
            $('#treediv').html('
Parse Error: ' + e.message + '
');
            console.error(e);
        }
    });

    $('#peg-zoom-in').click(function() {
        changeSize(editor, 2);
        changeSize(output, 2);

    });
    $('#peg-zoom-out').click(function() {
        changeSize(editor, -2);
        changeSize(output, -2);
    });
    $('#peg-reset').click(function() {
        setSize(editor, 14);
        setSize(output, 14);
    });
    $(output).focus(function() {
        if (editor.getValue()) {
            $('#build_parser_btn').click();
        }
    });

    $('#peg_editor a').click(function(e) {
        e.preventDefault();

    });
    $('#peg_editor_settings').click(function(e) {
        e.preventDefault();

        editor.execCommand('showSettingsMenu');
    });

    $('#tree-reset').click(function() {
        $('#parse_btn').click();
    });
});<|endoftext|>