<commit_before>var wordTypes = ['adjective', 'adverb', 'definitive article', 'noun', 'number', 'preposition', 'verb'];

var words = [
   {
      'word': 'bank',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'verb',
            'score': 25
         }
      ]
   },
   {
      'word': 'black',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'adjective',
            'score': 25
         }
      ]
   },
   {
      'word': 'brickbat',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'catachresis',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'centipede',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'company',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'contract',
      'types': [
         {
            'type': 'noun',
            'score': 65
         },
         {
            'type': 'adjective',
            'score': 25
         },
         {
            'type': 'verb',
            'score': 10
         }
      ]
   },
   {
      'word': 'credit',
      'types': [
         {
            'type': 'noun',
            'score': 50
         },
         {
            'type': 'verb',
            'score': 50
         }
      ]
   },
   {
      'word': 'cup',
      'types': [
         {
            'type': 'noun',
            'score': 85
         },
         {
            'type': 'verb',
            'score': 15
         }
      ]
   },
   {
      'word': 'exchange',
      'types': [
         {
            'type': 'verb',
            'score': 65
         },
         {
            'type': 'noun',
            'score': 35
         }
      ]
   },
   {
      'word': 'extemporaneous',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'financial',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'for',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'good',
      'types': [
         {
            'type': 'adjective',
            'score': 90
         },
         {
            'type': 'noun',
            'score': 10
         }
      ]
   },
   {
      'word': 'in',
      'types': [
         {
            'type': 'preposition',
            'score': 87
         },
         {
            'type': 'adverb',
            'score': 10
         },
         {
            'type': 'adjective',
            'score': 3
         }
      ]
   },
   {
      'word': 'management',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'mondegreen',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'nine',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
      'word': 'mnemonic',
      'types': [
         {
            'type': 'adjective',
            'score': 50
         },
         {
            'type': 'noun',
            'score': 50
         }
      ]
   },
   {
      'word': 'of',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'on',
      'types': [
         {
            'type': 'adjective',
            'score': 33
         },
         {
            'type': 'adverb',
            'score': 33
         },
         {
            'type': 'noun',
            'score': 1
         },
         {
            'type': 'preposition',
            'score': 33
         }
      ]
   },
   {
      'word': 'one',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
      'word': 'portfolio',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'protean',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'quiddity',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'red',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'adjective',
            'score': 25
         }
      ]
   },
   {
      'word': 'say',
      'types': [
         {
            'type': 'verb',
            'score': 95
         },
         {
            'type': 'adverb',
            'score': 5
         }
      ]
   },
   {
      'word': 'security',
      'types': [
         {
            'type': 'noun',
            'score': 80
         },
         {
            'type': 'adjective',
            'score': 20
         }
      ]
   },
   {
      'word': 'serotinal',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'sit',
      'types': [
         {
            'type': 'verb',
            'score': 100
         }
      ]
   },
   {
      'word': 'six',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
      'word': 'soup',
      'types': [
         {
            'type': 'noun',
            'score': 92
         },
         {
            'type': 'verb',
            'score': 8
         }
      ]
   },
   {
      'word': 'the',
      'types': [
         {
            'type': 'definitive article',
            'score': 99
         },
         {
            'type': 'adverb',
            'score': 1
         }
      ]
   },
   {
      'word': 'time',
      'types': [
         {
            'type': 'noun',
            'score': 80
         },
         {
            'type': 'adjective',
            'score': 8
         },
         {
            'type': 'verb',
            'score': 12
         }
      ]
   },
   {
      'word': 'to',
      'types': [
         {
            'type': 'preposition',
            'score': 92
         },
         {
            'type': 'adverb',
            'score': 8
         }
      ]
   },
   {
      'word': 'up',
      'types': [
         {
            'type': 'adverb',
            'score': 65
         },
         {
            'type': 'preposition',
            'score': 25
         },
         {
            'type': 'adjective',
            'score': 7
         },
         {
            'type': 'noun',
            'score': 3
         }
      ]
   },
   {
      'word': 'wig',
      'types': [
         {
            'type': 'noun',
            'score': 95
         },
         {
            'type': 'verb',
            'score': 5
         }
      ]
   },
   {
      'word': 'with',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'xeriscaping',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   }
];

exports.words = words;
exports.wordTypes = wordTypes;<commit_msg>new dictionary word: snowflake<commit_after>var wordTypes = ['adjective', 'adverb', 'definitive article', 'noun', 'number', 'preposition', 'verb'];

var words = [
   {
      'word': 'bank',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'verb',
            'score': 25
         }
      ]
   },
   {
      'word': 'black',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'adjective',
            'score': 25
         }
      ]
   },
   {
      'word': 'brickbat',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'catachresis',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'centipede',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'company',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'contract',
      'types': [
         {
            'type': 'noun',
            'score': 65
         },
         {
            'type': 'adjective',
            'score': 25
         },
         {
            'type': 'verb',
            'score': 10
         }
      ]
   },
   {
      'word': 'credit',
      'types': [
         {
            'type': 'noun',
            'score': 50
         },
         {
            'type': 'verb',
            'score': 50
         }
      ]
   },
   {
      'word': 'cup',
      'types': [
         {
            'type': 'noun',
            'score': 85
         },
         {
            'type': 'verb',
            'score': 15
         }
      ]
   },
   {
      'word': 'exchange',
      'types': [
         {
            'type': 'verb',
            'score': 65
         },
         {
            'type': 'noun',
            'score': 35
         }
      ]
   },
   {
      'word': 'extemporaneous',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'financial',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'for',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'good',
      'types': [
         {
            'type': 'adjective',
            'score': 90
         },
         {
            'type': 'noun',
            'score': 10
         }
      ]
   },
   {
      'word': 'in',
      'types': [
         {
            'type': 'preposition',
            'score': 87
         },
         {
            'type': 'adverb',
            'score': 10
         },
         {
            'type': 'adjective',
            'score': 3
         }
      ]
   },
   {
      'word': 'management',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'mondegreen',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'nine',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
      'word': 'mnemonic',
      'types': [
         {
            'type': 'adjective',
            'score': 50
         },
         {
            'type': 'noun',
            'score': 50
         }
      ]
   },
   {
      'word': 'of',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'on',
      'types': [
         {
            'type': 'adjective',
            'score': 33
         },
         {
            'type': 'adverb',
            'score': 33
         },
         {
            'type': 'noun',
            'score': 1
         },
         {
            'type': 'preposition',
            'score': 33
         }
      ]
   },
   {
      'word': 'one',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
      'word': 'portfolio',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'protean',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'quiddity',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   },
   {
      'word': 'red',
      'types': [
         {
            'type': 'noun',
            'score': 75
         },
         {
            'type': 'adjective',
            'score': 25
         }
      ]
   },
   {
      'word': 'say',
      'types': [
         {
            'type': 'verb',
            'score': 95
         },
         {
            'type': 'adverb',
            'score': 5
         }
      ]
   },
   {
      'word': 'security',
      'types': [
         {
            'type': 'noun',
            'score': 80
         },
         {
            'type': 'adjective',
            'score': 20
         }
      ]
   },
   {
      'word': 'serotinal',
      'types': [
         {
            'type': 'adjective',
            'score': 100
         }
      ]
   },
   {
      'word': 'sit',
      'types': [
         {
            'type': 'verb',
            'score': 100
         }
      ]
   },
   {
      'word': 'six',
      'types': [
         {
            'type': 'noun',
            'score': 100
         },
         {
            'type': 'number',
            'score': 100
         }
      ]
   },
   {
    'word': 'snowflake',
    'types': [
      {
        'type': 'noun',
        'score': 100
      }
    ]
  },
   {
      'word': 'soup',
      'types': [
         {
            'type': 'noun',
            'score': 92
         },
         {
            'type': 'verb',
            'score': 8
         }
      ]
   },
   {
      'word': 'the',
      'types': [
         {
            'type': 'definitive article',
            'score': 99
         },
         {
            'type': 'adverb',
            'score': 1
         }
      ]
   },
   {
      'word': 'time',
      'types': [
         {
            'type': 'noun',
            'score': 80
         },
         {
            'type': 'adjective',
            'score': 8
         },
         {
            'type': 'verb',
            'score': 12
         }
      ]
   },
   {
      'word': 'to',
      'types': [
         {
            'type': 'preposition',
            'score': 92
         },
         {
            'type': 'adverb',
            'score': 8
         }
      ]
   },
   {
      'word': 'up',
      'types': [
         {
            'type': 'adverb',
            'score': 65
         },
         {
            'type': 'preposition',
            'score': 25
         },
         {
            'type': 'adjective',
            'score': 7
         },
         {
            'type': 'noun',
            'score': 3
         }
      ]
   },
   {
      'word': 'wig',
      'types': [
         {
            'type': 'noun',
            'score': 95
         },
         {
            'type': 'verb',
            'score': 5
         }
      ]
   },
   {
      'word': 'with',
      'types': [
         {
            'type': 'preposition',
            'score': 100
         }
      ]
   },
   {
      'word': 'xeriscaping',
      'types': [
         {
            'type': 'noun',
            'score': 100
         }
      ]
   }
];

exports.words = words;
exports.wordTypes = wordTypes;<|endoftext|>


<commit_before>/*
ProcessPuzzle User Interface
Backend agnostic, desktop like configurable, browser font-end based on MochaUI.
Copyright (C) 2011  Joe Kueser, Zsolt Zsuffa

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 <http://www.gnu.org/licenses/>.
*/

ROOT_LOGGER_NAME = "WebUI";
FRONT_CONTROLLER = "CommandControllerServlet";

// Main control class, responsible for managing and syncronizing the widgets.
//= require_directory ../FundamentalTypes
//= require ../Singleton/Singleton.js

var WebUIController = new Class({
   Implements: [Class.Singleton, Events, Options],
   Binds : ['changeLanguage',
            'constructDesktop',
            'configureLogger',
            'determineCurrentUserLocale',
            'finalizeConfiguration',
            'loadDocument',
            'loadInternationalizations',
            'loadWebUIConfiguration',
            'onDesktopConstructed',
            'onError',
            'restoreStateFromUrl',
            'storeComponentState',
            'storeStateInUrl',
            'subscribeToWebUIMessages',
            'webUIMessageHandler'],

   options: {
      artifactTypesXslt : "Commons/JavaScript/WebUIController/TransformBusinessDefinitionToArtifactTypes.xsl",
      componentName : "WebUIController",
      configurationUri : "Configuration.xml",
      contextRootPrefix : "../../",
      errorPageUri : "Commons/FrontController/WebUiError.jsp",
      languageSelectorElementId : "LanguageSelectorWidget",
      loggerGroupName : "WebUIController",
      reConfigurationDelay: 500,
      urlRefreshPeriod : 3000,
      window : window
   },

   //Constructors
   initialize: function( options, usedWindow ) { return this.check() || this.setUp( options, usedWindow ); },
   setUp: function( options, usedWindow ){
      this.setOptions( options );
      if( usedWindow != null && usedWindow != 'undefined' ){
          this.options.window = usedWindow;
      }

      //private instance variables
      this.configurationChain = new Chain();
      this.desktop;
      this.error;
      this.isConfigured = false;
      this.languageSelector;
      this.locale;
      this.logger;
      this.messageBus = new WebUIMessageBus();
      this.resourceBundle;
      this.prefferedLanguage;
      this.recentHash = this.determineCurrentHash();
      this.refreshUrlTimer;
      this.skin;
      this.stateManager = new ComponentStateManager();
      this.userName;
      this.userLocation;
      this.warningContainer;
      this.webUIConfiguration;
      this.webUIException;

      this.loadWebUIConfiguration();
      this.configureLogger();

      this.logger.group( this.options.componentName + ".setUp", false );
      this.determineCurrentUserLocale();
      this.determineDefaultSkin();
      this.loadInternationalizations();

      this.logger.debug( "Browser Interface is initialized with context root prefix: "  + this.options.contextRootPrefix );
      this.logger.groupEnd();
   }.protect(),

   //public accessor and mutator methods
   changeLanguage : function( locale ){
      this.logger.debug( this.options.componentName + ".changeLanguage()." );
      this.destroy();
      this.locale = locale;
      this.configure.delay( this.options.reConfigurationDelay, this );
   },

   changeSkin : function( newSkinName ){
      this.logger.debug( this.options.componentName + ".changeSkin()." );
      this.destroy();
      this.skin = newSkinName;
      this.configure.delay( this.options.reConfigurationDelay, this );
   },

   configure : function() {
      this.logger.group( this.options.componentName + ".configure()", false );
      this.configurationChain.chain(
         this.loadWebUIConfiguration,
         this.configureLogger,
         this.restoreStateFromUrl,
         this.determineCurrentUserLocale,
         this.loadInternationalizations,
         this.constructDesktop,
         this.subscribeToWebUIMessages,
         this.storeComponentState,
         this.finalizeConfiguration
      ).callChain();

      this.logger.groupEnd( this.options.componentName + ".configure()" );
   },

   destroy : function() {
      if( this.isConfigured ){
         this.logger.group( this.options.componentName + ".destroy()", false );
         this.locale = null;
         this.messageBus.tearDown();
         if( this.languageSelector ) this.languageSelector.destroy();
         this.desktop.destroy();
         this.webUIConfiguration.release();
         this.resourceBundle.release();
         this.options.window.location.hash = "";
         clearInterval( this.refreshUrlTimer );
         this.isConfigured = false;
         this.logger.groupEnd( this.options.componentName + ".destroy()" );
      }
   },

   loadDocument : function( documentUri, documentType ){
      this.logger.debug( this.options.componentName + ".loadDocument( '" + documentUri + "' )" );
      var message = new MenuSelectedMessage({ activityType : AbstractDocument.Activity.LOAD_DOCUMENT, documentType : documentType, documentURI : documentUri });
      this.messageBus.notifySubscribers( message );
   },

   loadHtmlDocument : function( documentUri ){
      this.loadDocument( documentUri, AbstractDocument.Types.HTML );
   },

   loadSmartDocument : function( documentUri ){
      this.loadDocument( documentUri, AbstractDocument.Types.SMART );
   },

   onDesktopConstructed : function(){
      this.logger.debug( this.options.componentName + ", constructing desktop is finished." );
      this.configurationChain.callChain();
   },

   onError: function( error ){
      this.error = error;
      this.showWebUIExceptionPage( this.error );
   },

   restoreStateFromUrl : function(){
      this.logger.debug( this.options.componentName + ".restoreStateFromUrl() started." );
      if( this.options.window.location.hash.substring(2)) {
         var currentState = this.stateManager.toString();
         try {
            this.stateManager.resetStateFromUri( this.options.window.location.hash.substring(2) );
            this.messageBus.notifySubscribers( new WebUIStateRestoredMessage() );
         }catch( e ){
            this.stateManager.parse( currentState );
            this.logger.debug( "restoreStateFromUrl() exception: " + e );
         }
      }
      this.configurationChain.callChain();
   },

   storeStateInUrl : function() {
	   var stateAsString = this.stateManager.toString();
	   if( this.recentHash != stateAsString ){
	      this.recentHash = stateAsString;
	      this.options.window.location.hash = "!" + stateAsString;
	   }
   },

   webUIMessageHandler: function( webUIMessage ){
      if( !this.isConfigured ) throw new UnconfiguredWebUIControllerException({ source : 'WebUIController.webUIMessageHandler()' });

      if( instanceOf( webUIMessage, LanguageChangedMessage ) && webUIMessage.getNewLocale() != this.getCurrentLocale() ){
         this.changeLanguage( webUIMessage.getNewLocale() );
      }else if( instanceOf( webUIMessage, SkinChangedMessage ) && webUIMessage.getNewSkin() != this.getCurrentSkin() ){
         this.changeSkin( webUIMessage.getNewSkin() );
      }

      this.lastHandledMessage = webUIMessage;
   },

	//Properties
   getContextRootPrefix : function() { return this.contextRootPrefix; },
   getCurrentLocale : function () { return this.locale; },
   getCurrentSkin : function () { return this.skin; },
   getDesktop : function() { return this.desktop; },
   getIsConfigured : function() { return this.isConfigured; },
   getLanguageSelector : function() { return this.languageSelector; },
   getLocale : function() { return this.locale; },
   getLogger : function() { return this.logger; },
   getMessageBus : function() { return this.messageBus; },
   getPrefferedLanguage : function() { return this.prefferedLanguage; },
   getResourceBundle : function() { return this.resourceBundle; },
   getStateManager : function() { return this.stateManager; },
   getText : function( key, defaultValue ) { return this.getTextInternal( key, defaultValue  ); },
   getUserLocation : function() { return this.userLocation; },
   getUserName : function() { return this.userName; },
   getWebUIConfiguration : function() { return this.webUIConfiguration; },
   getWebUIException : function() { return this.webUiException; },
   setUserLocation : function( newLocation ) { this.userLocation = newLocation;},
   setUserName : function( newUserName ) { this.userName = newUserName;},
   setLanguage : function ( newLanguage ) { this.setLanguageInternal( newLanguage ); },

   //private methods
   configureLogger : function() {
      this.logger =  new WebUILogger( this.webUIConfiguration );
      this.logger.debug( this.options.componentName + ".configureLogger() started." );
      this.configurationChain.callChain();
   }.protect(),

   constructDesktop : function() {
      this.logger.debug( this.options.componentName + ".constructDesktop() started." );
      var desktopConfigurationUri = this.webUIConfiguration.getSkinConfiguration( this.skin );
      this.desktop = new Desktop( this.webUIConfiguration, this.resourceBundle, { configurationURI : desktopConfigurationUri, onConstructed : this.onDesktopConstructed, onError : this.onError } );
      this.desktop.unmarshall();
      try{
         this.desktop.construct();
      }catch( e ){
         this.onError( e );
      }
   }.protect(),

   determineCurrentHash: function() {
      if( this.options.window.location.hash.indexOf( "#" ) != -1 )
         return this.options.window.location.hash.substring(1);
      else return "";
   }.protect(),

   determineCurrentUserLocale : function() {
      this.logger.debug( this.options.componentName + ".determineCurrentUserLocale() started." );
      if( this.locale == null ){
         var storedState = this.stateManager.retrieveCurrentState( this.options.componentName );
         if( storedState ) {
            var localeString = storedState['locale'];
            this.locale = new Locale();
            this.locale.parse( localeString );
         }else {
            this.locale = new Locale();
            this.locale.parse( this.webUIConfiguration.getI18DefaultLocale() );
         }
      }
      this.configurationChain.callChain();
   }.protect(),

   determineDefaultSkin : function(){
      this.skin = this.webUIConfiguration.getDefaultSkin();
   }.protect(),

   finalizeConfiguration: function(){
      this.refreshUrlTimer = this.storeStateInUrl.periodical( this.options.urlRefreshPeriod, this );
      this.isConfigured = true;
      this.fireEvent( 'configured', this );
   }.protect(),

   getTextInternal : function ( key, defaultValue ) {
      if( this.resourceBundle == null)
         if( defaultValue != null ) return defaultValue;
         else return key;
      var returnValue;
      try {
         returnValue = this.resourceBundle.getText(key);
      } catch (e) {
         if( e instanceof IllegalArgumentException ) {
            if(defaultValue != null) return defaultValue;
            return key;
         } else {
            var exception = new UserException( "Unknown problem occured.", "WebUIController getText()" );
            throw exception;
         }
      }
      return returnValue;
   }.protect(),

   loadInternationalizations : function () {
      this.logger.debug( this.options.componentName + ".loadInternationalizations() started." );
      try{
         this.resourceBundle = new XMLResourceBundle( this.webUIConfiguration );
         this.resourceBundle.load( this.locale );
         this.logger.debug( "Resource bundles: " + this.options.contextRootPrefix + this.resourceBundle.getResourceBundleNames() + " was loaded." );
      }catch( e ) {
         this.onError( e );
      }
      this.configurationChain.callChain();
   }.protect(),

   loadWebUIConfiguration : function() {
      try{
         this.webUIConfiguration = new WebUIConfiguration( this.options.configurationUri );
         if( !this.webUIConfiguration.isLoaded ) this.webUIConfiguration.load();
      }catch( e ){
         this.onError( e );
      }
      this.configurationChain.callChain();
   }.protect(),

   setLanguage : function( newLanguage ) {
      this.logger.debug( this.options.componentName + ".setLanguage() started." );
      prefferedLanguage = newLanguage;
      if(newLanguage != null) {
         var locale = new Locale(newLanguage);
         if( applicationConfiguration != null) {
            applicationConfiguration.setLocale(locale);
            this.loadInternationalizations(applicationConfiguration.getBundlePath(),locale);
         }
      }
   }.protect(),

   showWebUIExceptionPage : function( exception ) {
      var bodyElement = $$( 'body' );
      this.warningContainer = new Element( 'div', { id: 'warning'} );
      bodyElement.grab( this.warningContainer, 'top' );

      var warningHeader = new Element( 'h1' );
      warningHeader.appendText( "Error Occured" );
      this.warningContainer.grab( warningHeader );

      var warningNameElement = new Element( 'h3' );
      warningNameElement.appendText( exception.name );
      this.warningContainer.grab( warningNameElement );

      var messageElement = new Element( 'p' );
      messageElement.appendText( exception.message );
      this.warningContainer.grab( messageElement );

      var stackElement = new Element( 'p' );
      if( exception.stack ) {
         stackElement.appendText( exception.stack );
         this.warningContainer.grab( stackElement );
      }
   }.protect(),

   storeComponentState : function() {
      this.logger.debug( this.options.componentName + ".storeComponentState() started." );
      this.stateManager.storeCurrentState( this.options.componentName, {locale : this.locale.toString()} );
      this.configurationChain.callChain();
   }.protect(),

   subscribeToWebUIMessages: function() {
      this.logger.debug( this.options.componentName + ".subscribeToWebUIMessages() started." );
      this.messageBus.subscribeToMessage( LanguageChangedMessage, this.webUIMessageHandler );
      this.messageBus.subscribeToMessage( SkinChangedMessage, this.webUIMessageHandler );
      //this.messageBus.subscribeToMessage( MenuSelectedMessage, this.webUIMessageHandler );
      this.configurationChain.callChain();
   }.protect()
});
<commit_msg>Add contentUri argument to loadDocument() method.<commit_after>/*
ProcessPuzzle User Interface
Backend agnostic, desktop like configurable, browser font-end based on MochaUI.
Copyright (C) 2011  Joe Kueser, Zsolt Zsuffa

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 <http://www.gnu.org/licenses/>.
*/

ROOT_LOGGER_NAME = "WebUI";
FRONT_CONTROLLER = "CommandControllerServlet";

// Main control class, responsible for managing and syncronizing the widgets.
//= require_directory ../FundamentalTypes
//= require ../Singleton/Singleton.js

var WebUIController = new Class({
   Implements: [Class.Singleton, Events, Options],
   Binds : ['changeLanguage',
            'constructDesktop',
            'configureLogger',
            'determineCurrentUserLocale',
            'finalizeConfiguration',
            'loadDocument',
            'loadInternationalizations',
            'loadWebUIConfiguration',
            'onDesktopConstructed',
            'onError',
            'restoreStateFromUrl',
            'storeComponentState',
            'storeStateInUrl',
            'subscribeToWebUIMessages',
            'webUIMessageHandler'],

   options: {
      artifactTypesXslt : "Commons/JavaScript/WebUIController/TransformBusinessDefinitionToArtifactTypes.xsl",
      componentName : "WebUIController",
      configurationUri : "Configuration.xml",
      contextRootPrefix : "../../",
      errorPageUri : "Commons/FrontController/WebUiError.jsp",
      languageSelectorElementId : "LanguageSelectorWidget",
      loggerGroupName : "WebUIController",
      reConfigurationDelay: 500,
      urlRefreshPeriod : 3000,
      window : window
   },

   //Constructors
   initialize: function( options, usedWindow ) { return this.check() || this.setUp( options, usedWindow ); },
   setUp: function( options, usedWindow ){
      this.setOptions( options );
      if( usedWindow != null && usedWindow != 'undefined' ){
          this.options.window = usedWindow;
      }

      //private instance variables
      this.configurationChain = new Chain();
      this.desktop;
      this.error;
      this.isConfigured = false;
      this.languageSelector;
      this.locale;
      this.logger;
      this.messageBus = new WebUIMessageBus();
      this.resourceBundle;
      this.prefferedLanguage;
      this.recentHash = this.determineCurrentHash();
      this.refreshUrlTimer;
      this.skin;
      this.stateManager = new ComponentStateManager();
      this.userName;
      this.userLocation;
      this.warningContainer;
      this.webUIConfiguration;
      this.webUIException;

      this.loadWebUIConfiguration();
      this.configureLogger();

      this.logger.group( this.options.componentName + ".setUp", false );
      this.determineCurrentUserLocale();
      this.determineDefaultSkin();
      this.loadInternationalizations();

      this.logger.debug( "Browser Interface is initialized with context root prefix: "  + this.options.contextRootPrefix );
      this.logger.groupEnd();
   }.protect(),

   //public accessor and mutator methods
   changeLanguage : function( locale ){
      this.logger.debug( this.options.componentName + ".changeLanguage()." );
      this.destroy();
      this.locale = locale;
      this.configure.delay( this.options.reConfigurationDelay, this );
   },

   changeSkin : function( newSkinName ){
      this.logger.debug( this.options.componentName + ".changeSkin()." );
      this.destroy();
      this.skin = newSkinName;
      this.configure.delay( this.options.reConfigurationDelay, this );
   },

   configure : function() {
      this.logger.group( this.options.componentName + ".configure()", false );
      this.configurationChain.chain(
         this.loadWebUIConfiguration,
         this.configureLogger,
         this.restoreStateFromUrl,
         this.determineCurrentUserLocale,
         this.loadInternationalizations,
         this.constructDesktop,
         this.subscribeToWebUIMessages,
         this.storeComponentState,
         this.finalizeConfiguration
      ).callChain();

      this.logger.groupEnd( this.options.componentName + ".configure()" );
   },

   destroy : function() {
      if( this.isConfigured ){
         this.logger.group( this.options.componentName + ".destroy()", false );
         this.locale = null;
         this.messageBus.tearDown();
         if( this.languageSelector ) this.languageSelector.destroy();
         this.desktop.destroy();
         this.webUIConfiguration.release();
         this.resourceBundle.release();
         this.options.window.location.hash = "";
         clearInterval( this.refreshUrlTimer );
         this.isConfigured = false;
         this.logger.groupEnd( this.options.componentName + ".destroy()" );
      }
   },

   loadDocument : function( documentUri, contentUri, documentType ){
      this.logger.debug( this.options.componentName + ".loadDocument( '" + documentUri + "' )" );
      var message = new MenuSelectedMessage({ activityType : AbstractDocument.Activity.LOAD_DOCUMENT, documentType : documentType, documentURI : documentUri, documentContentURI : contentUri });
      this.messageBus.notifySubscribers( message );
   },

   loadHtmlDocument : function( documentUri ){
      this.loadDocument( documentUri, null, AbstractDocument.Types.HTML );
   },

   loadSmartDocument : function( documentUri, contentUri ){
      this.loadDocument( documentUri, contentUri, AbstractDocument.Types.SMART );
   },

   onDesktopConstructed : function(){
      this.logger.debug( this.options.componentName + ", constructing desktop is finished." );
      this.configurationChain.callChain();
   },

   onError: function( error ){
      this.error = error;
      this.showWebUIExceptionPage( this.error );
   },

   restoreStateFromUrl : function(){
      this.logger.debug( this.options.componentName + ".restoreStateFromUrl() started." );
      if( this.options.window.location.hash.substring(2)) {
         var currentState = this.stateManager.toString();
         try {
            this.stateManager.resetStateFromUri( this.options.window.location.hash.substring(2) );
            this.messageBus.notifySubscribers( new WebUIStateRestoredMessage() );
         }catch( e ){
            this.stateManager.parse( currentState );
            this.logger.debug( "restoreStateFromUrl() exception: " + e );
         }
      }
      this.configurationChain.callChain();
   },

   storeStateInUrl : function() {
	   var stateAsString = this.stateManager.toString();
	   if( this.recentHash != stateAsString ){
	      this.recentHash = stateAsString;
	      this.options.window.location.hash = "!" + stateAsString;
	   }
   },

   webUIMessageHandler: function( webUIMessage ){
      if( !this.isConfigured ) throw new UnconfiguredWebUIControllerException({ source : 'WebUIController.webUIMessageHandler()' });

      if( instanceOf( webUIMessage, LanguageChangedMessage ) && webUIMessage.getNewLocale() != this.getCurrentLocale() ){
         this.changeLanguage( webUIMessage.getNewLocale() );
      }else if( instanceOf( webUIMessage, SkinChangedMessage ) && webUIMessage.getNewSkin() != this.getCurrentSkin() ){
         this.changeSkin( webUIMessage.getNewSkin() );
      }

      this.lastHandledMessage = webUIMessage;
   },

	//Properties
   getContextRootPrefix : function() { return this.contextRootPrefix; },
   getCurrentLocale : function () { return this.locale; },
   getCurrentSkin : function () { return this.skin; },
   getDesktop : function() { return this.desktop; },
   getIsConfigured : function() { return this.isConfigured; },
   getLanguageSelector : function() { return this.languageSelector; },
   getLocale : function() { return this.locale; },
   getLogger : function() { return this.logger; },
   getMessageBus : function() { return this.messageBus; },
   getPrefferedLanguage : function() { return this.prefferedLanguage; },
   getResourceBundle : function() { return this.resourceBundle; },
   getStateManager : function() { return this.stateManager; },
   getText : function( key, defaultValue ) { return this.getTextInternal( key, defaultValue  ); },
   getUserLocation : function() { return this.userLocation; },
   getUserName : function() { return this.userName; },
   getWebUIConfiguration : function() { return this.webUIConfiguration; },
   getWebUIException : function() { return this.webUiException; },
   setUserLocation : function( newLocation ) { this.userLocation = newLocation;},
   setUserName : function( newUserName ) { this.userName = newUserName;},
   setLanguage : function ( newLanguage ) { this.setLanguageInternal( newLanguage ); },

   //private methods
   configureLogger : function() {
      this.logger =  new WebUILogger( this.webUIConfiguration );
      this.logger.debug( this.options.componentName + ".configureLogger() started." );
      this.configurationChain.callChain();
   }.protect(),

   constructDesktop : function() {
      this.logger.debug( this.options.componentName + ".constructDesktop() started." );
      var desktopConfigurationUri = this.webUIConfiguration.getSkinConfiguration( this.skin );
      this.desktop = new Desktop( this.webUIConfiguration, this.resourceBundle, { configurationURI : desktopConfigurationUri, onConstructed : this.onDesktopConstructed, onError : this.onError } );
      this.desktop.unmarshall();
      try{
         this.desktop.construct();
      }catch( e ){
         this.onError( e );
      }
   }.protect(),

   determineCurrentHash: function() {
      if( this.options.window.location.hash.indexOf( "#" ) != -1 )
         return this.options.window.location.hash.substring(1);
      else return "";
   }.protect(),

   determineCurrentUserLocale : function() {
      this.logger.debug( this.options.componentName + ".determineCurrentUserLocale() started." );
      if( this.locale == null ){
         var storedState = this.stateManager.retrieveCurrentState( this.options.componentName );
         if( storedState ) {
            var localeString = storedState['locale'];
            this.locale = new Locale();
            this.locale.parse( localeString );
         }else {
            this.locale = new Locale();
            this.locale.parse( this.webUIConfiguration.getI18DefaultLocale() );
         }
      }
      this.configurationChain.callChain();
   }.protect(),

   determineDefaultSkin : function(){
      this.skin = this.webUIConfiguration.getDefaultSkin();
   }.protect(),

   finalizeConfiguration: function(){
      this.refreshUrlTimer = this.storeStateInUrl.periodical( this.options.urlRefreshPeriod, this );
      this.isConfigured = true;
      this.fireEvent( 'configured', this );
   }.protect(),

   getTextInternal : function ( key, defaultValue ) {
      if( this.resourceBundle == null)
         if( defaultValue != null ) return defaultValue;
         else return key;
      var returnValue;
      try {
         returnValue = this.resourceBundle.getText(key);
      } catch (e) {
         if( e instanceof IllegalArgumentException ) {
            if(defaultValue != null) return defaultValue;
            return key;
         } else {
            var exception = new UserException( "Unknown problem occured.", "WebUIController getText()" );
            throw exception;
         }
      }
      return returnValue;
   }.protect(),

   loadInternationalizations : function () {
      this.logger.debug( this.options.componentName + ".loadInternationalizations() started." );
      try{
         this.resourceBundle = new XMLResourceBundle( this.webUIConfiguration );
         this.resourceBundle.load( this.locale );
         this.logger.debug( "Resource bundles: " + this.options.contextRootPrefix + this.resourceBundle.getResourceBundleNames() + " was loaded." );
      }catch( e ) {
         this.onError( e );
      }
      this.configurationChain.callChain();
   }.protect(),

   loadWebUIConfiguration : function() {
      try{
         this.webUIConfiguration = new WebUIConfiguration( this.options.configurationUri );
         if( !this.webUIConfiguration.isLoaded ) this.webUIConfiguration.load();
      }catch( e ){
         this.onError( e );
      }
      this.configurationChain.callChain();
   }.protect(),

   setLanguage : function( newLanguage ) {
      this.logger.debug( this.options.componentName + ".setLanguage() started." );
      prefferedLanguage = newLanguage;
      if(newLanguage != null) {
         var locale = new Locale(newLanguage);
         if( applicationConfiguration != null) {
            applicationConfiguration.setLocale(locale);
            this.loadInternationalizations(applicationConfiguration.getBundlePath(),locale);
         }
      }
   }.protect(),

   showWebUIExceptionPage : function( exception ) {
      var bodyElement = $$( 'body' );
      this.warningContainer = new Element( 'div', { id: 'warning'} );
      bodyElement.grab( this.warningContainer, 'top' );

      var warningHeader = new Element( 'h1' );
      warningHeader.appendText( "Error Occured" );
      this.warningContainer.grab( warningHeader );

      var warningNameElement = new Element( 'h3' );
      warningNameElement.appendText( exception.name );
      this.warningContainer.grab( warningNameElement );

      var messageElement = new Element( 'p' );
      messageElement.appendText( exception.message );
      this.warningContainer.grab( messageElement );

      var stackElement = new Element( 'p' );
      if( exception.stack ) {
         stackElement.appendText( exception.stack );
         this.warningContainer.grab( stackElement );
      }
   }.protect(),

   storeComponentState : function() {
      this.logger.debug( this.options.componentName + ".storeComponentState() started." );
      this.stateManager.storeCurrentState( this.options.componentName, {locale : this.locale.toString()} );
      this.configurationChain.callChain();
   }.protect(),

   subscribeToWebUIMessages: function() {
      this.logger.debug( this.options.componentName + ".subscribeToWebUIMessages() started." );
      this.messageBus.subscribeToMessage( LanguageChangedMessage, this.webUIMessageHandler );
      this.messageBus.subscribeToMessage( SkinChangedMessage, this.webUIMessageHandler );
      //this.messageBus.subscribeToMessage( MenuSelectedMessage, this.webUIMessageHandler );
      this.configurationChain.callChain();
   }.protect()
});
<|endoftext|>


<commit_before>/**

  Memetec

  Memetec is a software platform for the creative reuse of media.

  Visit http://mem.ec/ and sign up to begin creating.

  This software is based on the work of Michael Dale's html5 video editor
  built by Kaltura in collaboration with Wikimedia for use in the Wikipedia.
  For video hosting, the sytem uses a Kaltura Server.  For more information
  plese visit http://html5video.org/ and http://kaltura.org/

  © Copyright 2010
  The Memetec Federation, Light Corporation, Inc., and Andrew Davis

  Stop by #memetec on freenode.net irc to discuss this project.

**/

/**
  Setup Dependencies
**/

require.paths.unshift('./npm')
var sys = require('sys'),
    oauth = require('oauth'),
    connect = require('connect'),
    redis_store = require('connect-redis'),
    mongoose = require('mongoose').Mongoose,
    express = require('express'),
    jade = require('jade');

/**
  Are we in a Development or Production environment

  If you're running this on your own computer,
  copy development-settings.json.sample to development-settings.json
  and modify.

  Heroku: make sure you have the following environment variables included
  in your production environment, the handy heroku config command to do this is:

      heroku config:add REDIS_HOST=something.redistogo.com REDIS_PORT=9379 REDIS_PASS=something

  * Make sure you don't set the PORT variable, heroku takes care of that for you.
  http://docs.heroku.com/config-vars
**/

var settings = {};

if (process.env.PORT) {

    redis_url = require('url').parse(process.env.REDISTOGO_URL);

    settings.environment = "Production";
    settings.host = "mem.ec";
    settings.base = "http://mem.ec/";
    settings.port = process.env.PORT;
    settings.mongo_url = process.env.MONGOHQ_URL;
    settings.redis_host = redis_url.hostname;
    settings.redis_pass = redis_url.auth.split(':')[1];
    settings.redis_port = parseInt(redis_url.host.split(redis_url.hostname)[1].replace(':', ''));
    settings.twitter_key = process.env.TWITTER_KEY;
    settings.twitter_secret = process.env.TWITTER_SECRET;
    }
else {
    settings = JSON.parse( require('fs').readFileSync('development-settings.json', encoding='utf8') );
  }

/**
  Setup the Redis connection for user/session management
**/

var session_store = new redis_store({
        maxAge: 60000 * 60 * 24 * 28,
        reapInterval: 60000 *60 * 24 * 7,
        host: settings.redis_host,
        port: settings.redis_port,
        })

var storeAuth = function() { session_store.client.auth( settings.redis_pass ); sys.puts('connected to redis'); }
session_store.client.addListener('connected', storeAuth);
session_store.client.addListener('reconnected', storeAuth);

/**
  * Setup A MongoDB connection for Meme storage

var db = mongoose.connect('mongodb://localhost/test'),
    Memes = mongoose.noSchema('memes',db);
 */

/**
  * We're using twitter for authentication
 */

var Twitter = new oauth.OAuth(
    'http://api.twitter.com/oauth/request_token',
    'http://api.twitter.com/oauth/access_token',
    settings.twitter_key,
    settings.twitter_secret,
    '1.0',
    null,
    'HMAC-SHA1'
    );

/**
  Setup the Express Application
**/

var app = express.createServer(
    connect.cookieDecoder(),
    connect.session({
      store: session_store      })
    );
app.set('view engine', 'jade');
app.configure(function(){
    app.use(express.staticProvider(__dirname + '/public'));
    });

/**
  Express Routing
  /:meme    --> loads up that meme
  /         --> the home page if a session has been established
  /login    --> start Twitter oauth
  /callback --> register a session
**/

app.get('/login', function(req, res) {
    return Twitter.getOAuthRequestToken(function(error, token, secret, url, params) {
      req.session['token'] = token;
      req.session['secret'] = secret;
      //sys.puts(("Request Token: " + (token)));
      //sys.puts(("Request Secret: " + (secret)));
      return res.redirect(("http://api.twitter.com/oauth/authenticate?oauth_token=" + (token)));
      });
    });

app.get('/callback', function(req, res) {
    return Twitter.getOAuthAccessToken(
      req.session['token'],
      req.session['secret'],
      function(error, access_token, access_secret, params) {
        sys.puts(("Access Token: " + (access_token)));
        sys.puts(("Access Secret: " + (access_secret)));
        sys.puts(("Params: " + (JSON.stringify(params))));
        req.session['access_token'] = access_token;
        req.session['access_secret'] = access_secret;
        return res.redirect('/');
        }
      );
    });

app.get('/:meme', function(req, res){
    if (req.params.meme) {
      res.render('meme', {
        locals: {
          meme: req.params.meme,
          host: settings.host,
          base: settings.base,
          title: req.params.meme + '  [ ' + settings.host + ' ]'
          }
        });
      }
    else {
      // render the home page if params are not defined.
      next();
      }
    });

app.get('/', function(req, res){
    if (req.session['access_token']) {
      sys.puts(JSON.stringify(req.session));
      return Twitter.getProtectedResource(
        'http://api.twitter.com/1/account/verify_credentials.json',
        'GET',
        req.session['access_token'],
        req.session['access_secret'],
        function(error, data, response) {
          res.render('home', {
            locals: {
              host: settings.host,
              base: settings.base,
              title: '[ ' + settings.host + ' ]'
              }
            });
          }
        );
      }
    else {
      return res.render('login', {
            locals: {
              host: settings.host,
              base: settings.base,
              title: '[ ' + settings.host + ' ]'
              }
            });
      }
    });

/**
  Express Application Helpers
**/

app.dynamicHelpers({
     session: function(req, res){
       return req.session;
       }
     });

/**
  Let's go!
**/

app.listen(parseInt( settings.port ), null);
sys.puts(settings.environment + " server running at http://" + settings.host + ":" + settings.port + "/");
sys.puts(sys.inspect(settings));
<commit_msg>Broken!!! brainstorming the mongoDB models<commit_after>/**

  Memetec

  Memetec is a software platform for the creative reuse of media.

  Visit http://mem.ec/ and sign up to begin creating.

  This software is based on the work of Michael Dale's html5 video editor
  built by Kaltura in collaboration with Wikimedia for use in the Wikipedia.
  For video hosting, the sytem uses a Kaltura Server.  For more information
  plese visit http://html5video.org/ and http://kaltura.org/

  © Copyright 2010
  The Memetec Federation, Light Corporation, Inc., and Andrew Davis

  Stop by #memetec on freenode.net irc to discuss this project.

**/

/**
  Setup Dependencies
**/

require.paths.unshift('./npm')
var sys = require('sys'),
    oauth = require('oauth'),
    connect = require('connect'),
    redis_store = require('connect-redis'),
    mongoose = require('mongoose').Mongoose,
    express = require('express'),
    jade = require('jade');

/**
  Are we in a Development or Production environment

  If you're running this on your own computer,
  copy development-settings.json.sample to development-settings.json
  and modify.

  Heroku: make sure you have the following environment variables included
  in your production environment, the handy heroku config command to do this is:

      heroku config:add REDIS_HOST=something.redistogo.com REDIS_PORT=9379 REDIS_PASS=something

  * Make sure you don't set the PORT variable, heroku takes care of that for you.
  http://docs.heroku.com/config-vars
**/

var settings = {};

if (process.env.PORT) {

    redis_url = require('url').parse(process.env.REDISTOGO_URL);

    settings.environment = "Production";
    settings.host = "mem.ec";
    settings.base = "http://mem.ec/";
    settings.port = process.env.PORT;
    settings.mongo_url = process.env.MONGOHQ_URL;
    settings.redis_host = redis_url.hostname;
    settings.redis_pass = redis_url.auth.split(':')[1];
    settings.redis_port = parseInt(redis_url.host.split(redis_url.hostname)[1].replace(':', ''));
    settings.twitter_key = process.env.TWITTER_KEY;
    settings.twitter_secret = process.env.TWITTER_SECRET;
    }
else {
    settings = JSON.parse( require('fs').readFileSync('development-settings.json', encoding='utf8') );
  }

/**
  * Setup A MongoDB connection for Meme storage

var db = mongoose.connect('mongodb://localhost/test'),
    Memes = mongoose.noSchema('memes',db);
 */

mongoose.model('Meme', {

  types: {
    title: String,
    version: {
      user: String,
      timestamp: Datetime,
      smil: String,
      }
    }

  indexes: [
    [[title],[version.user],[version.timestamp]],
    [[version.user],[version.timestamp]]
    ],

  setters: {
    title: function(v){
      return this.v.capitalize();
      }
    },
  }

  // Memes Contain Users

); // end of mongoose.model.meme

db.meme.save({title: 'A Short Tale', user:'papyromancer', smil: '<XML>'});

/**
  Setup the Redis connection for user/session management
**/

var session_store = new redis_store({
        maxAge: 60000 * 60 * 24 * 28,
        reapInterval: 60000 *60 * 24 * 7,
        host: settings.redis_host,
        port: settings.redis_port,
        })

var storeAuth = function() { session_store.client.auth( settings.redis_pass ); sys.puts('connected to redis'); }
session_store.client.addListener('connected', storeAuth);
session_store.client.addListener('reconnected', storeAuth);

/**
  * We're using twitter for authentication
 */

var Twitter = new oauth.OAuth(
    'http://api.twitter.com/oauth/request_token',
    'http://api.twitter.com/oauth/access_token',
    settings.twitter_key,
    settings.twitter_secret,
    '1.0',
    null,
    'HMAC-SHA1'
    );

/**
  Setup the Express Application
**/

var app = express.createServer(
    connect.cookieDecoder(),
    connect.session({
      store: session_store      })
    );
app.set('view engine', 'jade');
app.configure(function(){
    app.use(express.staticProvider(__dirname + '/public'));
    });

/**
  Express Routing
  /:meme    --> loads up that meme
  /         --> the home page if a session has been established
  /login    --> start Twitter oauth
  /callback --> register a session
**/

app.get('/login', function(req, res) {
    return Twitter.getOAuthRequestToken(function(error, token, secret, url, params) {
      req.session['token'] = token;
      req.session['secret'] = secret;
      //sys.puts(("Request Token: " + (token)));
      //sys.puts(("Request Secret: " + (secret)));
      return res.redirect(("http://api.twitter.com/oauth/authenticate?oauth_token=" + (token)));
      });
    });

app.get('/callback', function(req, res) {
    return Twitter.getOAuthAccessToken(
      req.session['token'],
      req.session['secret'],
      function(error, access_token, access_secret, params) {
        sys.puts(("Access Token: " + (access_token)));
        sys.puts(("Access Secret: " + (access_secret)));
        sys.puts(("Params: " + (JSON.stringify(params))));
        req.session['access_token'] = access_token;
        req.session['access_secret'] = access_secret;
        return res.redirect('/');
        }
      );
    });

app.get('/:meme', function(req, res){
    if (req.params.meme) {
      res.render('meme', {
        locals: {
          meme: req.params.meme,
          host: settings.host,
          base: settings.base,
          title: req.params.meme + '  [ ' + settings.host + ' ]'
          }
        });
      }
    else {
      // render the home page if params are not defined.
      next();
      }
    });

app.get('/', function(req, res){
    if (req.session['access_token']) {
      sys.puts(JSON.stringify(req.session));
      return Twitter.getProtectedResource(
        'http://api.twitter.com/1/account/verify_credentials.json',
        'GET',
        req.session['access_token'],
        req.session['access_secret'],
        function(error, data, response) {
          res.render('home', {
            locals: {
              host: settings.host,
              base: settings.base,
              title: '[ ' + settings.host + ' ]'
              }
            });
          }
        );
      }
    else {
      return res.render('login', {
            locals: {
              host: settings.host,
              base: settings.base,
              title: '[ ' + settings.host + ' ]'
              }
            });
      }
    });

/**
  Express Application Helpers
**/

app.dynamicHelpers({
     session: function(req, res){
       return req.session;
       }
     });

/**
  Let's go!
**/

app.listen(parseInt( settings.port ), null);
sys.puts(settings.environment + " server running at http://" + settings.host + ":" + settings.port + "/");
sys.puts(sys.inspect(settings));
<|endoftext|>


<commit_before>/* Jquery HTTP NTP Client */
(function($){

	/** Assert that time is valid */
	function assert_time(t) {
		if(typeof t !== 'number') { throw new TypeError('time (' + t + ') is not number!'); }
		if(t <= 1378656286000) {
			throw new TypeError('time (' + t + ') is invalid!');
		}
	}

	/** Asynchronically get time offset between the client and server */
	$.getServerTimeOffset = function(url) {
		if(!url) { throw new TypeError("missing url for .getServerTimeOffset()!"); }

		var client_start_time;

		var p = $.ajax({
			url: url + '/time',
			cache: false,
			dataType: 'text',
			beforeSend: function() {
				client_start_time = (new Date()).getTime();
			}
		}).then(function(json) {
			var client_end_time = (new Date()).getTime();
			assert_time(client_start_time);
			assert_time(client_end_time);
			var id = JSON.parse(json);
			var p2 = $.ajax({
				url: url+'/fetch?id='+encodeURIComponent(id),
				dataType: 'text',
				cache: false
			}).then(function(json) {
				var data = JSON.parse(json);
				assert_time(data.start);
				assert_time(data.end);
				var offset = ( ( data.start - client_start_time ) + (data.end - client_end_time) ) / 2;
				return offset;
			});
			return p2;
		});

		return p;
	};

	/** The time offset on server */
	var _offset;
	$.resetServerTime = function(url) {
		return $.getServerTimeOffset(url).then(function(offset) { return _offset = offset; });
	};

	/** Get server time */
	$.getServerTime = function() {
		if(_offset === undefined) { throw new TypeError("You must call $.resetServerTime() first!"); }
		var time = new Date();
		time.setTime( (new Date()).getTime() + offset);
		return time;
	};

})( jQuery );
/* EOF */
<commit_msg>Fixed getServerTimeOffset<commit_after>/* Jquery HTTP NTP Client */
(function($){

	/** Assert that time is valid */
	function assert_time(t) {
		if(typeof t !== 'number') { throw new TypeError('time (' + t + ') is not number!'); }
		if(t <= 1378656286000) {
			throw new TypeError('time (' + t + ') is invalid!');
		}
	}

	/** Asynchronically get time offset between the client and server */
	$.getServerTimeOffset = function(url) {
		if(!url) { throw new TypeError("missing url for .getServerTimeOffset()!"); }

		var client_start_time;

		var p = $.ajax({
			url: url + '/time',
			cache: false,
			dataType: 'text',
			beforeSend: function() {
				client_start_time = (new Date()).getTime();
			}
		}).then(function(json) {
			var client_end_time = (new Date()).getTime();
			assert_time(client_start_time);
			assert_time(client_end_time);
			var id = JSON.parse(json);
			var p2 = $.ajax({
				url: url+'/fetch?id='+encodeURIComponent(id),
				dataType: 'text',
				cache: false
			}).then(function(json) {
				var data = JSON.parse(json);
				assert_time(data.start);
				assert_time(data.end);
				var offset = ( ( data.start - client_start_time ) + (data.end - client_end_time) ) / 2;
				return offset;
			});
			return p2;
		});

		return p;
	};

	/** The time offset on server */
	var _offset;
	$.resetServerTime = function(url) {
		return $.getServerTimeOffset(url).then(function(offset) { return _offset = offset; });
	};

	/** Get server time */
	$.getServerTime = function() {
		if(_offset === undefined) { throw new TypeError("You must call $.resetServerTime() first!"); }
		var time = new Date();
		time.setTime( (new Date()).getTime() + _offset);
		return time;
	};

})( jQuery );
/* EOF */
<|endoftext|>


<commit_before>CodeMirror.defineMode("karel", function(conf) {
    var ERRORCLASS = 'ka-error';

    function wordRegexp(words) {
        return new RegExp("^((" + words.join(")|(") + "))\\b");
    }

    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
    var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");

    var wordOperators = wordRegexp([]);
    var commonkeywords = ['go', 'turn', 'put', 'get', 'repeat',
                          'while', 'if', 'else', 'def'];
    var commontypes = ['home', 'north', 'wall', 'gem', 'empty', 'and', 'or', 'not'];
    var ka2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
                         'xrange'],
               'keywords': ['exec', 'print']};
    var ka3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
                         'open', 'range', 'zip'],
               'keywords': ['nonlocal']};

    if (!!conf.mode.version && parseInt(conf.mode.version, 10) === 3) {
        commonkeywords = commonkeywords.concat(ka3.keywords);
        commontypes = commontypes.concat(ka3.types);
        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
        commonkeywords = commonkeywords.concat(ka2.keywords);
        commontypes = commontypes.concat(ka2.types);
        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(commonkeywords);
    var types = wordRegexp(commontypes);

    // tokenizers
    function tokenBase(stream, state) {
        // Handle scope changes
        if (stream.sol()) {
            var scopeOffset = state.scopes[0].offset;
            if (stream.eatSpace()) {
                var lineOffset = stream.indentation();
                if (lineOffset > scopeOffset) {
                    return 'ka-indent';
                } else if (lineOffset < scopeOffset) {
                    return 'ka-dedent';
                }
                return 'whitespace';
            } else {
                if (scopeOffset > 0) {
                    dedent(stream, state);
                }
            }
        }
        if (stream.eatSpace()) {
            return 'ka-space';
        }

        var ch = stream.peek();

        // Handle Comments
        if (ch === '#') {
            stream.skipToEnd();
            return 'ka-comment';
        }

        // Handle Number Literals
        if (stream.match(/^[0-9\.]/, false)) {
            var floatLiteral = false;
            // Floats
            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
            if (floatLiteral) {
                // Float literals may be "imaginary"
                stream.eat(/J/i);
                return 'ka-literal';
            }
            // Integers
            var intLiteral = false;
            // Hex
            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
            // Binary
            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
            // Octal
            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
            // Decimal
            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
                // Decimal literals may be "imaginary"
                stream.eat(/J/i);
                // TODO - Can you have imaginary longs?
                intLiteral = true;
            }
            // Zero by itself with no other piece of number.
            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
            if (intLiteral) {
                // Integer literals may be "long"
                stream.eat(/L/i);
                return 'ka-literal';
            }
        }

        // Handle Strings
        if (stream.match(stringPrefixes)) {
            state.tokenize = tokenStringFactory(stream.current());
            return state.tokenize(stream, state);
        }

        // Handle operators and Delimiters
        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
            return 'ka-delimiter';
        }
        if (stream.match(doubleOperators)
            || stream.match(singleOperators)
            || stream.match(wordOperators)) {
            return 'ka-operator';
        }
        if (stream.match(singleDelimiters)) {
            return 'ka-delimiter';
        }

        if (stream.match(types)) {
            return 'ka-type';
        }

        if (stream.match(keywords)) {
            return 'ka-keyword';
        }

        if (stream.match(identifiers)) {
            return 'ka-identifier';
        }

        // Handle non-detected items
        stream.next();
        return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
        while ('rub'.indexOf(delimiter[0].toLowerCase()) >= 0) {
            delimiter = delimiter.substr(1);
        }
        var delim_re = new RegExp(delimiter);
        var singleline = delimiter.length == 1;
        var OUTCLASS = 'ka-string';

        return function tokenString(stream, state) {
            while (!stream.eol()) {
                stream.eatWhile(/[^'"\\]/);
                if (stream.eat('\\')) {
                    stream.next();
                    if (singleline && stream.eol()) {
                        return OUTCLASS;
                    }
                } else if (stream.match(delim_re)) {
                    state.tokenize = tokenBase;
                    return OUTCLASS;
                } else {
                    stream.eat(/['"]/);
                }
            }
            if (singleline) {
                if (conf.mode.singleLineStringErrors) {
                    OUTCLASS = ERRORCLASS
                } else {
                    state.tokenize = tokenBase;
                }
            }
            return OUTCLASS;
        };
    }

    function indent(stream, state, type) {
        type = type || 'py';
        var indentUnit = 0;
        if (type === 'py') {
            for (var i = 0; i < state.scopes.length; ++i) {
                if (state.scopes[i].type === 'py') {
                    indentUnit = state.scopes[i].offset + conf.indentUnit;
                    break;
                }
            }
        } else {
            indentUnit = stream.column() + stream.current().length;
        }
        state.scopes.unshift({
            offset: indentUnit,
            type: type
        });
    }

    function dedent(stream, state) {
        if (state.scopes.length == 1) return;
        if (state.scopes[0].type === 'py') {
            var _indent = stream.indentation();
            var _indent_index = -1;
            for (var i = 0; i < state.scopes.length; ++i) {
                if (_indent === state.scopes[i].offset) {
                    _indent_index = i;
                    break;
                }
            }
            if (_indent_index === -1) {
                return true;
            }
            while (state.scopes[0].offset !== _indent) {
                state.scopes.shift();
            }
            return false
        } else {
            state.scopes.shift();
            return false;
        }
    }

    function tokenLexer(stream, state) {
        var style = state.tokenize(stream, state);
        var current = stream.current();

        // Handle '.' connected identifiers
        if (current === '.') {
            style = state.tokenize(stream, state);
            current = stream.current();
            if (style === 'ka-identifier') {
                return 'ka-identifier';
            } else {
                return ERRORCLASS;
            }
        }

        // Handle decorators
        if (current === '@') {
            style = state.tokenize(stream, state);
            current = stream.current();
            if (style === 'ka-identifier'
                || current === '@staticmethod'
                || current === '@classmethod') {
                return 'ka-decorator';
            } else {
                return ERRORCLASS;
            }
        }

        // Handle scope changes.
        if (current === 'pass' || current === 'return') {
            state.dedent += 1;
        }
        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
            || style === 'ka-indent') {
            indent(stream, state);
        }
        var delimiter_index = '[({'.indexOf(current);
        if (delimiter_index !== -1) {
            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
        }
        if (style === 'ka-dedent') {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        delimiter_index = '])}'.indexOf(current);
        if (delimiter_index !== -1) {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
            if (state.scopes.length > 1) state.scopes.shift();
            state.dedent -= 1;
        }

        return style;
    }

    var external = {
        startState: function(basecolumn) {
            return {
              tokenize: tokenBase,
              scopes: [{offset:basecolumn || 0, type:'py'}],
              lastToken: null,
              lambda: false,
              dedent: 0
          };
        },

        token: function(stream, state) {
            var style = tokenLexer(stream, state);

            state.lastToken = {style:style, content: stream.current()};

            if (stream.eol() && stream.lambda) {
                state.lambda = false;
            }

            return style;
        },

        indent: function(state, textAfter) {
            if (state.tokenize != tokenBase) {
                return 0;
            }

            return state.scopes[0].offset;
        }

    };
    return external;
});

CodeMirror.defineMIME("text/x-karel", "karel");
<commit_msg>fix: ui freezing<commit_after>CodeMirror.defineMode("karel", function(conf) {
    var ERRORCLASS = 'ka-error';

    function wordRegexp(words) {
        return new RegExp("^((" + words.join(")|(") + "))\\b");
    }

    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
    var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");

    var wordOperators = wordRegexp(['not', 'and', 'or']);
    var commonkeywords = ['go', 'turn', 'put', 'get', 'repeat',
                          'while', 'if', 'else', 'def'];
    var commontypes = ['home', 'north', 'wall', 'gem', 'empty'];
    var ka2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
                         'xrange'],
               'keywords': ['exec', 'print']};
    var ka3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
                         'open', 'range', 'zip'],
               'keywords': ['nonlocal']};

    if (!!conf.mode.version && parseInt(conf.mode.version, 10) === 3) {
        commonkeywords = commonkeywords.concat(ka3.keywords);
        commontypes = commontypes.concat(ka3.types);
        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
        commonkeywords = commonkeywords.concat(ka2.keywords);
        commontypes = commontypes.concat(ka2.types);
        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(commonkeywords);
    var types = wordRegexp(commontypes);

    // tokenizers
    function tokenBase(stream, state) {
        // Handle scope changes
        if (stream.sol()) {
            var scopeOffset = state.scopes[0].offset;
            if (stream.eatSpace()) {
                var lineOffset = stream.indentation();
                if (lineOffset > scopeOffset) {
                    return 'ka-indent';
                } else if (lineOffset < scopeOffset) {
                    return 'ka-dedent';
                }
                return 'whitespace';
            } else {
                if (scopeOffset > 0) {
                    dedent(stream, state);
                }
            }
        }
        if (stream.eatSpace()) {
            return 'ka-space';
        }

        var ch = stream.peek();

        // Handle Comments
        if (ch === '#') {
            stream.skipToEnd();
            return 'ka-comment';
        }

        // Handle Number Literals
        if (stream.match(/^[0-9\.]/, false)) {
            var floatLiteral = false;
            // Floats
            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
            if (floatLiteral) {
                // Float literals may be "imaginary"
                stream.eat(/J/i);
                return 'ka-literal';
            }
            // Integers
            var intLiteral = false;
            // Hex
            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
            // Binary
            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
            // Octal
            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
            // Decimal
            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
                // Decimal literals may be "imaginary"
                stream.eat(/J/i);
                // TODO - Can you have imaginary longs?
                intLiteral = true;
            }
            // Zero by itself with no other piece of number.
            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
            if (intLiteral) {
                // Integer literals may be "long"
                stream.eat(/L/i);
                return 'ka-literal';
            }
        }

        // Handle Strings
        if (stream.match(stringPrefixes)) {
            state.tokenize = tokenStringFactory(stream.current());
            return state.tokenize(stream, state);
        }

        // Handle operators and Delimiters
        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
            return 'ka-delimiter';
        }
        if (stream.match(doubleOperators)
            || stream.match(singleOperators)
            || stream.match(wordOperators)) {
            return 'ka-operator';
        }
        if (stream.match(singleDelimiters)) {
            return 'ka-delimiter';
        }

        if (stream.match(types)) {
            return 'ka-type';
        }

        if (stream.match(keywords)) {
            return 'ka-keyword';
        }

        if (stream.match(identifiers)) {
            return 'ka-identifier';
        }

        // Handle non-detected items
        stream.next();
        return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
        while ('rub'.indexOf(delimiter[0].toLowerCase()) >= 0) {
            delimiter = delimiter.substr(1);
        }
        var delim_re = new RegExp(delimiter);
        var singleline = delimiter.length == 1;
        var OUTCLASS = 'ka-string';

        return function tokenString(stream, state) {
            while (!stream.eol()) {
                stream.eatWhile(/[^'"\\]/);
                if (stream.eat('\\')) {
                    stream.next();
                    if (singleline && stream.eol()) {
                        return OUTCLASS;
                    }
                } else if (stream.match(delim_re)) {
                    state.tokenize = tokenBase;
                    return OUTCLASS;
                } else {
                    stream.eat(/['"]/);
                }
            }
            if (singleline) {
                if (conf.mode.singleLineStringErrors) {
                    OUTCLASS = ERRORCLASS
                } else {
                    state.tokenize = tokenBase;
                }
            }
            return OUTCLASS;
        };
    }

    function indent(stream, state, type) {
        type = type || 'py';
        var indentUnit = 0;
        if (type === 'py') {
            for (var i = 0; i < state.scopes.length; ++i) {
                if (state.scopes[i].type === 'py') {
                    indentUnit = state.scopes[i].offset + conf.indentUnit;
                    break;
                }
            }
        } else {
            indentUnit = stream.column() + stream.current().length;
        }
        state.scopes.unshift({
            offset: indentUnit,
            type: type
        });
    }

    function dedent(stream, state) {
        if (state.scopes.length == 1) return;
        if (state.scopes[0].type === 'py') {
            var _indent = stream.indentation();
            var _indent_index = -1;
            for (var i = 0; i < state.scopes.length; ++i) {
                if (_indent === state.scopes[i].offset) {
                    _indent_index = i;
                    break;
                }
            }
            if (_indent_index === -1) {
                return true;
            }
            while (state.scopes[0].offset !== _indent) {
                state.scopes.shift();
            }
            return false
        } else {
            state.scopes.shift();
            return false;
        }
    }

    function tokenLexer(stream, state) {
        var style = state.tokenize(stream, state);
        var current = stream.current();

        // Handle '.' connected identifiers
        if (current === '.') {
            style = state.tokenize(stream, state);
            current = stream.current();
            if (style === 'ka-identifier') {
                return 'ka-identifier';
            } else {
                return ERRORCLASS;
            }
        }

        // Handle decorators
        if (current === '@') {
            style = state.tokenize(stream, state);
            current = stream.current();
            if (style === 'ka-identifier'
                || current === '@staticmethod'
                || current === '@classmethod') {
                return 'ka-decorator';
            } else {
                return ERRORCLASS;
            }
        }

        // Handle scope changes.
        if (current === 'pass' || current === 'return') {
            state.dedent += 1;
        }
        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
            || style === 'ka-indent') {
            indent(stream, state);
        }
        var delimiter_index = '[({'.indexOf(current);
        if (delimiter_index !== -1) {
            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
        }
        if (style === 'ka-dedent') {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        delimiter_index = '])}'.indexOf(current);
        if (delimiter_index !== -1) {
            if (dedent(stream, state)) {
                return ERRORCLASS;
            }
        }
        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
            if (state.scopes.length > 1) state.scopes.shift();
            state.dedent -= 1;
        }

        return style;
    }

    var external = {
        startState: function(basecolumn) {
            return {
              tokenize: tokenBase,
              scopes: [{offset:basecolumn || 0, type:'py'}],
              lastToken: null,
              lambda: false,
              dedent: 0
          };
        },

        token: function(stream, state) {
            var style = tokenLexer(stream, state);

            state.lastToken = {style:style, content: stream.current()};

            if (stream.eol() && stream.lambda) {
                state.lambda = false;
            }

            return style;
        },

        indent: function(state, textAfter) {
            if (state.tokenize != tokenBase) {
                return 0;
            }

            return state.scopes[0].offset;
        }

    };
    return external;
});

CodeMirror.defineMIME("text/x-karel", "karel");
<|endoftext|>


<commit_before>'use strict';
// Author : Pankaj Kumar Dewangan
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    passport = require('passport'),
    logger = require('mean-logger');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */
//Test Line 1
// Initializing system variables
var config = require('./server/config/config');
var db = mongoose.connect(config.db);

// Bootstrap Models, Dependencies, Routes and the app as an express app
var app = require('./server/config/system/bootstrap')(passport, db);

//Test line 2
// Start the app by listening on <port>, optional hostname
app.listen(config.port, config.hostname);
console.log('Mean app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');

// Initializing logger
logger.init(app, passport, mongoose);

// Expose app
exports = module.exports = app;
<commit_msg>#1, Code cleanup.<commit_after>'use strict';
// Author : Pankaj Kumar Dewangan
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    passport = require('passport'),
    logger = require('mean-logger');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */
// Initializing system variables
var config = require('./server/config/config');
var db = mongoose.connect(config.db);

// Bootstrap Models, Dependencies, Routes and the app as an express app
var app = require('./server/config/system/bootstrap')(passport, db);

// Start the app by listening on <port>, optional hostname
app.listen(config.port, config.hostname);
console.log('Mean app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');

// Initializing logger
logger.init(app, passport, mongoose);

// Expose app
exports = module.exports = app;
<|endoftext|>


<commit_before>$(function () {
    var hash = window.location.hash;
    if (hash) {
        var container = $(hash + '.container');
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        if (container.length === 1 && !container.is(currentContainer) && container.css('display') !== 'flex') {
            containers.css({display: 'none'});
            container.css({display: 'flex'})
        }
    }

    $('.left').click(function (e) {
        e.preventDefault();
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        var prev = currentContainer.prev('.container');
        if (prev.length === 0) {
            prev = $('.container:last');
        }
        containers.css({display: 'none'});
        prev.css({display: 'flex'});
        if (prev.attr('id')) {
            window.location.hash = prev.attr('id');
        }
    });

    $('.right').click(function (e) {
        e.preventDefault();
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        var next = currentContainer.next('.container');
        if (next.length === 0) {
            next = $('.container:first');
        }
        containers.css({display: 'none'});
        next.css({display: 'flex'});
        if (next.attr('id')) {
            window.location.hash = next.attr('id');
        }
    });
});<commit_msg>Block IE11<commit_after>$(function () {
    var hash = window.location.hash;
    if (hash) {
        var container = $(hash + '.container');
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        if (container.length === 1 && !container.is(currentContainer) && container.css('display') !== 'flex' && $('.old-browser').css('display') === 'none') {
            containers.css({display: 'none'});
            container.css({display: 'flex'})
        }
    }

    $('.left').click(function (e) {
        e.preventDefault();
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        var prev = currentContainer.prev('.container');
        if (prev.length === 0) {
            prev = $('.container:last');
        }
        containers.css({display: 'none'});
        prev.css({display: 'flex'});
        if (prev.attr('id')) {
            window.location.hash = prev.attr('id');
        }
    });

    $('.right').click(function (e) {
        e.preventDefault();
        var containers = $('.container');
        var currentContainer = containers.filter(function () {
            if ($(this).css('display') === 'flex') {
                return true;
            }
        });
        var next = currentContainer.next('.container');
        if (next.length === 0) {
            next = $('.container:first');
        }
        containers.css({display: 'none'});
        next.css({display: 'flex'});
        if (next.attr('id')) {
            window.location.hash = next.attr('id');
        }
    });
});<|endoftext|>