<commit_before>/*
 * favcount.js v1.4.0
 * http://chrishunt.co/favcount
 * Dynamically updates the favicon with a number.
 *
 * Copyright 2013, Chris Hunt
 * Released under the MIT license
 */

(function(){
  function Favcount(icon) {
    this.icon = icon;
    this.opacity = 0.4;
    this.canvas = document.createElement('canvas');
    this.font = "Helvetica, Arial, sans-serif";
  }

  Favcount.prototype.set = function(count) {
    var self = this,
        img  = document.createElement('img');

    if (self.canvas.getContext) {
      img.onload = function() {
        drawCanvas(self.canvas, self.opacity, self.font, img, normalize(count));
      };

      img.src = this.icon;
    }
  };

  function normalize(count) {
    count = Math.round(count);

    if (isNaN(count) || count < 1) {
      return '';
    } else if (count < 10) {
      return ' ' + count;
    } else if (count > 99) {
      return '99';
    } else {
      return count;
    }
  }

  function drawCanvas(canvas, opacity, font, img, count) {
    var head = document.getElementsByTagName('head')[0],
        favicon = document.createElement('link'),
        multiplier, fontSize, context, xOffset, yOffset, border, shadow;

    favicon.rel = 'icon';

    // Scale canvas elements based on favicon size
    multiplier = img.width / 16;
    fontSize   = multiplier * 11;
    xOffset    = multiplier;
    yOffset    = multiplier * 11;
    border     = multiplier;
    shadow     = multiplier * 2;

    canvas.height = canvas.width = img.width;
    context = canvas.getContext('2d');
    context.font = 'bold ' + fontSize + 'px ' + font;

    // Draw faded favicon background
    if (count) { context.globalAlpha = opacity; }
    context.drawImage(img, 0, 0);
    context.globalAlpha = 1.0;

    // Draw white drop shadow
    context.shadowColor = '#FFF';
    context.shadowBlur = shadow;
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;

    // Draw white border
    context.fillStyle = '#FFF';
    context.fillText(count, xOffset, yOffset);
    context.fillText(count, xOffset + border, yOffset);
    context.fillText(count, xOffset, yOffset + border);
    context.fillText(count, xOffset + border, yOffset + border);

    // Draw black count
    context.fillStyle = '#000';
    context.fillText(count,
      xOffset + (border / 2.0),
      yOffset + (border / 2.0)
    );

    // Replace favicon with new favicon
    favicon.href = canvas.toDataURL('image/png');
    head.removeChild(document.querySelector('link[rel=icon]'));
    head.appendChild(favicon);
  }

  this.Favcount = Favcount;
}).call(this);

(function(){
  Favcount.VERSION = '1.4.0';
}).call(this);
<commit_msg>FIX: Allow Favcount to be used with CORS. I've submitted this upstream too:<commit_after>/*
 * favcount.js v1.4.0
 * http://chrishunt.co/favcount
 * Dynamically updates the favicon with a number.
 *
 * Copyright 2013, Chris Hunt
 * Released under the MIT license
 */

(function(){
  function Favcount(icon) {
    this.icon = icon;
    this.opacity = 0.4;
    this.canvas = document.createElement('canvas');
    this.font = "Helvetica, Arial, sans-serif";
  }

  Favcount.prototype.set = function(count) {
    var self = this,
        img  = document.createElement('img');

    if (self.canvas.getContext) {
      img.crossOrigin = "anonymous";

      img.onload = function() {
        drawCanvas(self.canvas, self.opacity, self.font, img, normalize(count));
      };

      img.src = this.icon;
    }
  };

  function normalize(count) {
    count = Math.round(count);

    if (isNaN(count) || count < 1) {
      return '';
    } else if (count < 10) {
      return ' ' + count;
    } else if (count > 99) {
      return '99';
    } else {
      return count;
    }
  }

  function drawCanvas(canvas, opacity, font, img, count) {
    var head = document.getElementsByTagName('head')[0],
        favicon = document.createElement('link'),
        multiplier, fontSize, context, xOffset, yOffset, border, shadow;

    favicon.rel = 'icon';

    // Scale canvas elements based on favicon size
    multiplier = img.width / 16;
    fontSize   = multiplier * 11;
    xOffset    = multiplier;
    yOffset    = multiplier * 11;
    border     = multiplier;
    shadow     = multiplier * 2;

    canvas.height = canvas.width = img.width;
    context = canvas.getContext('2d');
    context.font = 'bold ' + fontSize + 'px ' + font;

    // Draw faded favicon background
    if (count) { context.globalAlpha = opacity; }
    context.drawImage(img, 0, 0);
    context.globalAlpha = 1.0;

    // Draw white drop shadow
    context.shadowColor = '#FFF';
    context.shadowBlur = shadow;
    context.shadowOffsetX = 0;
    context.shadowOffsetY = 0;

    // Draw white border
    context.fillStyle = '#FFF';
    context.fillText(count, xOffset, yOffset);
    context.fillText(count, xOffset + border, yOffset);
    context.fillText(count, xOffset, yOffset + border);
    context.fillText(count, xOffset + border, yOffset + border);

    // Draw black count
    context.fillStyle = '#000';
    context.fillText(count,
      xOffset + (border / 2.0),
      yOffset + (border / 2.0)
    );

    // Replace favicon with new favicon
    favicon.href = canvas.toDataURL('image/png');
    head.removeChild(document.querySelector('link[rel=icon]'));
    head.appendChild(favicon);
  }

  this.Favcount = Favcount;
}).call(this);

(function(){
  Favcount.VERSION = '1.4.0';
}).call(this);
<|endoftext|>


<commit_before>/**
 * Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings
 * and other disasters.
 *
 * @author Alexander Kaupanin <kaupanin@gmail.com>
 * @version 1.1.107
 */

( function( $ ) {

  $.fn.sisyphus = function( options ) {
    var identifier = $.map( this, function( obj, i ) {
      return $( obj ).attr( "id" ) + $( obj ).attr( "name" )
    }).join();

    var sisyphus = Sisyphus.getInstance( identifier );
    sisyphus.protect( this, options );
    return sisyphus;
  };

  var browserStorage = {};

  /**
   * Check if local storage or other browser storage is available
   *
   * @return Boolean
   */
  browserStorage.isAvailable = function() {
    if ( typeof $.jStorage === "object" ) {
      return true;
    }
    try {
      return localStorage.getItem;
    } catch ( e ) {
      return false;
    }
  };

  /**
   * Set data to browser storage
   *
   * @param [String] key
   * @param [String] value
   *
   * @return Boolean
   */
  browserStorage.set = function( key, value ) {
    if ( typeof $.jStorage === "object" ) {
      $.jStorage.set( key, value + "" );
    } else {
      try {
        localStorage.setItem( key, value + "" );
      } catch ( e ) {
        //QUOTA_EXCEEDED_ERR
      }
    }
  };

  /**
   * Get data from browser storage by specified key
   *
   * @param [String] key
   *
   * @return string
   */
  browserStorage.get = function( key ) {
    if ( typeof $.jStorage === "object" ) {
      var result = $.jStorage.get( key );
      return result ? result.toString() : result;
    } else {
      return localStorage.getItem( key );
    }
  };

  /**
   * Delete data from browser storage by specified key
   *
   * @param [String] key
   *
   * @return void
   */
  browserStorage.remove = function( key ) {
    if ( typeof $.jStorage === "object" ) {
      $.jStorage.deleteKey( key );
    } else {
      localStorage.removeItem( key );
    }
  };

  Sisyphus = ( function() {
    var params = {
      instantiated: [],
      started: []
    };

    function init () {

      return {
        setInstanceIdentifier: function( identifier ) {
          this.identifier = identifier
        },

        getInstanceIdentifier: function() {
          return this.identifier;
        },

        /**
         * Set plugin initial options
         *
         * @param [Object] options
         *
         * @return void
         */
        setInitialOptions: function ( options ) {
          var defaults = {
            excludeFields: [],
            customKeySuffix: "",
            locationBased: false,
            timeout: 0,
            autoRelease: true,
            onSave: function() {},
            onBeforeRestore: function() {},
            onRestore: function() {},
            onRelease: function() {}
          };
          this.options = this.options || $.extend( defaults, options );
          this.browserStorage = browserStorage;
        },

        /**
         * Set plugin options
         *
         * @param [Object] options
         *
         * @return void
         */
        setOptions: function ( options ) {
          this.options = this.options || this.setInitialOptions( options );
          this.options = $.extend( this.options, options );
        },

        /**
         * Protect specified forms, store it's fields data to local storage and restore them on page load
         *
         * @param [Object] targets    forms object(s), result of jQuery selector
         * @param Object options      plugin options
         *
         * @return void
         */
        protect: function( targets, options ) {
          this.setOptions( options );
          targets = targets || {};
          var self = this;
          this.targets = this.targets || [];
          this.href = location.hostname + location.pathname + location.search + location.hash;
          this.targets = $.merge( this.targets, targets );
          this.targets = $.unique( this.targets );
          this.targets = $( this.targets );
          if ( ! this.browserStorage.isAvailable() ) {
            return false;
          }

          var callback_result = self.options.onBeforeRestore.call( self );
          if ( callback_result === undefined || callback_result ) {
            self.restoreAllData();
          }

          if ( this.options.autoRelease ) {
            self.bindReleaseData();
          }

          if ( ! params.started[ this.getInstanceIdentifier() ] ) {
            if ( self.isCKEditorPresent() ) {
              var intervalId = setInterval( function() {
                if (CKEDITOR.isLoaded) {
                  clearInterval(intervalId);
                  self.bindSaveData();
                  params.started[ self.getInstanceIdentifier() ] = true;
                }
              }, 100);
            } else {
              self.bindSaveData();
              params.started[ self.getInstanceIdentifier() ] = true;
            }
          }
        },

        isCKEditorPresent: function() {
          if ( this.isCKEditorExists() ) {
            CKEDITOR.isLoaded = false;
            CKEDITOR.on('instanceReady', function() {
              CKEDITOR.isLoaded = true;
            } );
            return true;
          } else {
            return false;
          }
        },

        isCKEditorExists: function() {
          return typeof CKEDITOR != "undefined";
        },

        findFieldsToProtect: function( target ) {
          return target.find( ":input" ).not( ":submit" ).not( ":reset" ).not( ":button" ).not( ":file" ).not( ":password" ).not( ":disabled" ).not( "[readonly]" );
        },

        /**
         * Bind saving data
         *
         * @return void
         */
        bindSaveData: function() {
          var self = this;

          if ( self.options.timeout ) {
            self.saveDataByTimeout();
          }

          self.targets.each( function() {
            var targetFormIdAndName = $( this ).attr( "id" ) + $( this ).attr( "name" );
            self.findFieldsToProtect( $( this ) ).each( function() {
              if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var field = $( this );
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + field.attr( "name" ) + self.options.customKeySuffix;
              if ( field.is( ":text" ) || field.is( "textarea" ) ) {
                if ( ! self.options.timeout ) {
                  self.bindSaveDataImmediately( field, prefix );
                }
              }
              self.bindSaveDataOnChange( field );
            } );
          } );
        },

        /**
         * Save all protected forms data to Local Storage.
         * Common method, necessary to not lead astray user firing 'data is saved' when select/checkbox/radio
         * is changed and saved, while text field data is saved only by timeout
         *
         * @return void
         */
        saveAllData: function() {
          var self = this;
          self.targets.each( function() {
            var targetFormIdAndName = $( this ).attr( "id" ) + $( this ).attr( "name" );
            var multiCheckboxCache = {};

            self.findFieldsToProtect( $( this) ).each( function() {
              var field = $( this );
              if ( $.inArray( this, self.options.excludeFields ) !== -1 || field.attr( "name" ) === undefined ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + field.attr( "name" ) + self.options.customKeySuffix;
              var value = field.val();

              if ( field.is(":checkbox") ) {
                if ( field.attr( "name" ).indexOf( "[" ) !== -1 ) {
                  if ( multiCheckboxCache[ field.attr( "name" ) ] === true ) {
                    return;
                  }
                  value = [];
                  $( "[name='" + field.attr( "name" ) +"']:checked" ).each( function() {
                    value.push( $( this ).val() );
                  } );
                  multiCheckboxCache[ field.attr( "name" ) ] = true;
                } else {
                  value = field.is( ":checked" );
                }
                self.saveToBrowserStorage( prefix, value, false );
              } else if ( field.is( ":radio" ) ) {
                if ( field.is( ":checked" ) ) {
                  value = field.val();
                  self.saveToBrowserStorage( prefix, value, false );
                }
              } else {
                if ( self.isCKEditorExists() ) {
                  var editor;
                  if ( editor = CKEDITOR.instances[ field.attr("name") ] || CKEDITOR.instances[ field.attr("id") ] ) {
                    editor.updateElement();
                    self.saveToBrowserStorage( prefix, field.val(), false);
                  } else {
                    self.saveToBrowserStorage( prefix, value, false );
                  }
                } else {
                  self.saveToBrowserStorage( prefix, value, false );
                }
              }
            } );
          } );
          self.options.onSave.call( self );
        },

        /**
         * Restore forms data from Local Storage
         *
         * @return void
         */
        restoreAllData: function() {
          var self = this;
          var restored = false;

          self.targets.each( function() {
            var target = $( this );
            var targetFormIdAndName = $( this ).attr( "id" ) + $( this ).attr( "name" );

            self.findFieldsToProtect( target ).each( function() {
              if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var field = $( this );
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + field.attr( "name" ) + self.options.customKeySuffix;
              var resque = self.browserStorage.get( prefix );
              if ( resque !== null ) {
                self.restoreFieldsData( field, resque );
                restored = true;
              }
            } );
          } );

          if ( restored ) {
            self.options.onRestore.call( self );
          }
        },

        /**
         * Restore form field data from local storage
         *
         * @param Object field    jQuery form element object
         * @param String resque  previously stored fields data
         *
         * @return void
         */
        restoreFieldsData: function( field, resque ) {
          if ( field.attr( "name" ) === undefined ) {
            return false;
          }
          if ( field.is( ":checkbox" ) && resque !== "false" && field.attr( "name" ).indexOf( "[" ) === -1 ) {
            field.attr( "checked", "checked" );
          } else if( field.is( ":checkbox" ) && resque === "false" && field.attr( "name" ).indexOf( "[" ) === -1 ) {
            field.removeAttr( "checked" );
          } else if ( field.is( ":radio" ) ) {
            if ( field.val() === resque ) {
              field.attr( "checked", "checked" );
            }
          } else if ( field.attr( "name" ).indexOf( "[" ) === -1 ) {
            field.val( resque );
          } else {
            resque = resque.split( "," );
            field.val( resque );
          }
        },

        /**
         * Bind immediate saving (on typing/checking/changing) field data to local storage when user fills it
         *
         * @param Object field    jQuery form element object
         * @param String prefix  prefix used as key to store data in local storage
         *
         * @return void
         */
        bindSaveDataImmediately: function( field, prefix ) {
          var self = this;
          if ( 'onpropertychange' in field ) {
            field.get(0).onpropertychange = function() {
              self.saveToBrowserStorage( prefix, field.val() );
            };
          } else {
            field.get(0).oninput = function() {
              self.saveToBrowserStorage( prefix, field.val() );
            };
          }
          if ( this.isCKEditorExists() ) {
            var editor;
            if ( editor = CKEDITOR.instances[ field.attr("name") ] || CKEDITOR.instances[ field.attr("id") ] ) {
              editor.document.on( 'keyup', function() {
                editor.updateElement();
                self.saveToBrowserStorage( prefix, field.val() );
              } );
            }
          }
        },

        /**
         * Save data to Local Storage and fire callback if defined
         *
         * @param String key
         * @param String value
         * @param Boolean [true] fireCallback
         *
         * @return void
         */
        saveToBrowserStorage: function( key, value, fireCallback ) {
          // if fireCallback is undefined it should be true
          fireCallback = fireCallback === undefined ? true : fireCallback;
          this.browserStorage.set( key, value );
          if ( fireCallback && value !== "" ) {
            this.options.onSave.call( this );
          }
        },

        /**
         * Bind saving field data on change
         *
         * @param Object field    jQuery form element object
         *
         * @return void
         */
        bindSaveDataOnChange: function( field ) {
          var self = this;
          field.change( function() {
            self.saveAllData();
          } );
        },

        /**
         * Saving (by timeout) field data to local storage when user fills it
         *
         * @return void
         */
        saveDataByTimeout: function() {
          var self = this;
          var targetForms = self.targets;
          setTimeout( ( function() {
            function timeout() {
              self.saveAllData();
              setTimeout( timeout, self.options.timeout * 1000 );
            }
            return timeout;
          } )( targetForms ), self.options.timeout * 1000 );
        },

        /**
         * Bind release form fields data from local storage on submit/reset form
         *
         * @return void
         */
        bindReleaseData: function() {
          var self = this;
          self.targets.each( function() {
            var target = $( this );
            var formIdAndName = target.attr( "id" ) + target.attr( "name" );
            $( this ).bind( "submit reset", function() {
              self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
            } );
          } );
        },

        /**
         * Manually release form fields
         *
         * @return void
         */
        manuallyReleaseData: function() {
          var self = this;
          self.targets.each( function() {
            var target = $( this );
            var formIdAndName = target.attr( "id" ) + target.attr( "name" );
            self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
          } );
        },

        /**
         * Bind release form fields data from local storage on submit/resett form
         *
         * @param String targetFormIdAndName  a form identifier consists of its id and name glued
         * @param Object fieldsToProtect    jQuery object contains form fields to protect
         *
         * @return void
         */
        releaseData: function( targetFormIdAndName, fieldsToProtect ) {
          var released = false;
          var self = this;

          // Released form, are not started anymore. Fix for ajax loaded forms.
          params.started[ self.getInstanceIdentifier() ] = false;

          fieldsToProtect.each( function() {
            if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
              // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
              return true;
            }
            var field = $( this );
            var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + field.attr( "name" ) + self.options.customKeySuffix;
            self.browserStorage.remove( prefix );
            released = true;
          } );

          if ( released ) {
            self.options.onRelease.call( self );
          }
        }

      };
    }

    return {
      getInstance: function( identifier ) {
        if ( ! params.instantiated[ identifier ] ) {
          params.instantiated[ identifier ] = init();
          params.instantiated[ identifier ].setInstanceIdentifier( identifier );
          params.instantiated[ identifier ].setInitialOptions();
        }
        if ( identifier ) {
          return params.instantiated[ identifier ];
        }
        return params.instantiated[ identifier ];
      },

      free: function() {
        params = {
          instantiated: [],
          started: []
        };
        return null;
      },
      version: '1.1.107'
    };
  } )();
} )( jQuery );<commit_msg>Update sisyphus to latest version 1.1.3<commit_after>/**
 * Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings
 * and other disasters.
 *
 * https://github.com/simsalabim/sisyphus
 *
 * @author Alexander Kaupanin <kaupanin@gmail.com>
 * @license MIT - see https://github.com/simsalabim/sisyphus/blob/master/MIT-LICENSE
 */

( function( $ ) {

  function getElementIdentifier(el) {
      return '[id=' + el.attr( "id" ) + '][name=' + el.attr( "name" ) + ']';
  }

  $.fn.sisyphus = function( options ) {
    var identifier = $.map( this, function( obj ) {
      return getElementIdentifier( $( obj ) );
    }).join();

    var sisyphus = Sisyphus.getInstance( identifier );
    sisyphus.protect( this, options );
    return sisyphus;
  };

  var browserStorage = {};

  /**
   * Check if local storage or other browser storage is available
   *
   * @return Boolean
   */
  browserStorage.isAvailable = function() {
    if ( typeof $.jStorage === "object" ) {
      return true;
    }
    try {
      return localStorage.getItem;
    } catch ( e ) {
      return false;
    }
  };

  /**
   * Set data to browser storage
   *
   * @param [String] key
   * @param [String] value
   *
   * @return Boolean
   */
  browserStorage.set = function( key, value ) {
    if ( typeof $.jStorage === "object" ) {
      $.jStorage.set( key, value + "" );
    } else {
      try {
        localStorage.setItem( key, value + "" );
      } catch ( e ) {
        //QUOTA_EXCEEDED_ERR
      }
    }
  };

  /**
   * Get data from browser storage by specified key
   *
   * @param [String] key
   *
   * @return string
   */
  browserStorage.get = function( key ) {
    if ( typeof $.jStorage === "object" ) {
      var result = $.jStorage.get( key );
      return result ? result.toString() : result;
    } else {
      return localStorage.getItem( key );
    }
  };

  /**
   * Delete data from browser storage by specified key
   *
   * @param [String] key
   *
   * @return void
   */
  browserStorage.remove = function( key ) {
    if ( typeof $.jStorage === "object" ) {
      $.jStorage.deleteKey( key );
    } else {
      localStorage.removeItem( key );
    }
  };

  Sisyphus = ( function() {
    var params = {
      instantiated: [],
      started: []
    };
    var CKEDITOR = window.CKEDITOR;

    function init () {

      return {
        setInstanceIdentifier: function( identifier ) {
          this.identifier = identifier;
        },

        getInstanceIdentifier: function() {
          return this.identifier;
        },

        /**
         * Set plugin initial options
         *
         * @param [Object] options
         *
         * @return void
         */
        setInitialOptions: function ( options ) {
          var defaults = {
            excludeFields: [],
            customKeySuffix: "",
            locationBased: false,
            timeout: 0,
            autoRelease: true,
            onBeforeSave: function() {},
            onSave: function() {},
            onBeforeRestore: function() {},
            onRestore: function() {},
            onRelease: function() {}
          };
          this.options = this.options || $.extend( defaults, options );
          this.browserStorage = browserStorage;
        },

        /**
         * Set plugin options
         *
         * @param [Object] options
         *
         * @return void
         */
        setOptions: function ( options ) {
          this.options = this.options || this.setInitialOptions( options );
          this.options = $.extend( this.options, options );
        },

        /**
         * Protect specified forms, store it's fields data to local storage and restore them on page load
         *
         * @param [Object] targets    forms object(s), result of jQuery selector
         * @param Object options      plugin options
         *
         * @return void
         */
        protect: function( targets, options ) {
          this.setOptions( options );
          targets = targets || {};
          var self = this;
          this.targets = this.targets || [];
          if ( self.options.name ) {
            this.href = self.options.name;
          } else {
            this.href = location.hostname + location.pathname + location.search + location.hash;
          }
          this.targets = $.merge( this.targets, targets );
          this.targets = $.unique( this.targets );
          this.targets = $( this.targets );
          if ( ! this.browserStorage.isAvailable() ) {
            return false;
          }

          var callback_result = self.options.onBeforeRestore.call( self );
          if ( callback_result === undefined || callback_result ) {
            self.restoreAllData();
          }

          if ( this.options.autoRelease ) {
            self.bindReleaseData();
          }

          if ( ! params.started[ this.getInstanceIdentifier() ] ) {
            if ( self.isCKEditorPresent() ) {
              var intervalId = setInterval( function() {
                if (CKEDITOR.isLoaded) {
                  clearInterval(intervalId);
                  self.bindSaveData();
                  params.started[ self.getInstanceIdentifier() ] = true;
                }
              }, 100);
            } else {
              self.bindSaveData();
              params.started[ self.getInstanceIdentifier() ] = true;
            }
          }
        },

        isCKEditorPresent: function() {
          if ( this.isCKEditorExists() ) {
            CKEDITOR.isLoaded = false;
            CKEDITOR.on('instanceReady', function() {
              CKEDITOR.isLoaded = true;
            } );
            return true;
          } else {
            return false;
          }
        },

        isCKEditorExists: function() {
          return typeof CKEDITOR !== "undefined";
        },

        findFieldsToProtect: function( target ) {
          return target.find( ":input" ).not( ":submit" ).not( ":reset" ).not( ":button" ).not( ":file" ).not( ":password" ).not( ":disabled" ).not( "[readonly]" );
        },

        /**
         * Bind saving data
         *
         * @return void
         */
        bindSaveData: function() {
          var self = this;

          if ( self.options.timeout ) {
            self.saveDataByTimeout();
          }

          self.targets.each( function() {
            var targetFormIdAndName = getElementIdentifier( $( this ) );
            self.findFieldsToProtect( $( this ) ).each( function() {
              if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var field = $( this );
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
              if ( field.is( ":text" ) || field.is( "textarea" ) ) {
                if ( ! self.options.timeout ) {
                  self.bindSaveDataImmediately( field, prefix );
                }
              }
              self.bindSaveDataOnChange( field );
            } );
          } );
        },

        /**
         * Save all protected forms data to Local Storage.
         * Common method, necessary to not lead astray user firing 'data is saved' when select/checkbox/radio
         * is changed and saved, while text field data is saved only by timeout
         *
         * @return void
         */
        saveAllData: function() {
          var self = this;
          self.targets.each( function() {
            var targetFormIdAndName = getElementIdentifier( $( this ) );
            var multiCheckboxCache = {};

            self.findFieldsToProtect( $( this) ).each( function() {
              var field = $( this );
              if ( $.inArray( this, self.options.excludeFields ) !== -1 || ( field.attr( "name" ) === undefined && field.attr( "id" ) === undefined ) ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
              var value = field.val();

              if ( field.is(":checkbox") ) {
                var name = field.attr( "name" );
                if ( name !== undefined && name.indexOf( "[" ) !== -1 ) {
                  if ( multiCheckboxCache[ name ] === true ) {
                    return;
                  }
                  value = [];
                  $( "[name='" + name +"']:checked" ).each( function() {
                    value.push( $( this ).val() );
                  } );
                  multiCheckboxCache[ name ] = true;
                } else {
                  value = field.is( ":checked" );
                }
                self.saveToBrowserStorage( prefix, value, false );
              } else if ( field.is( ":radio" ) ) {
                if ( field.is( ":checked" ) ) {
                  value = field.val();
                  self.saveToBrowserStorage( prefix, value, false );
                }
              } else {
                if ( self.isCKEditorExists() ) {
                  var editor = CKEDITOR.instances[ field.attr("name") ] || CKEDITOR.instances[ field.attr("id") ];
                  if ( editor ) {
                    editor.updateElement();
                    self.saveToBrowserStorage( prefix, field.val(), false);
                  } else {
                    self.saveToBrowserStorage( prefix, value, false );
                  }
                } else {
                  self.saveToBrowserStorage( prefix, value, false );
                }
              }
            } );
          } );
          self.options.onSave.call( self );
        },

        /**
         * Restore forms data from Local Storage
         *
         * @return void
         */
        restoreAllData: function() {
          var self = this;
          var restored = false;

          self.targets.each( function() {
            var target = $( this );
            var targetFormIdAndName = getElementIdentifier( $( this ) );

            self.findFieldsToProtect( target ).each( function() {
              if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
                // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
                return true;
              }
              var field = $( this );
              var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
              var resque = self.browserStorage.get( prefix );
              if ( resque !== null ) {
                self.restoreFieldsData( field, resque );
                restored = true;
              }
            } );
          } );

          if ( restored ) {
            self.options.onRestore.call( self );
          }
        },

        /**
         * Restore form field data from local storage
         *
         * @param Object field    jQuery form element object
         * @param String resque  previously stored fields data
         *
         * @return void
         */
        restoreFieldsData: function( field, resque ) {
          if ( field.attr( "name" ) === undefined && field.attr( "id" ) === undefined ) {
            return false;
          }
          var name = field.attr( "name" );
          if ( field.is( ":checkbox" ) && resque !== "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
            // If we aren't named by name (e.g. id) or we aren't in a multiple element field
            field.prop( "checked", true );
          } else if( field.is( ":checkbox" ) && resque === "false" && ( name === undefined || name.indexOf( "[" ) === -1 ) ) {
            // If we aren't named by name (e.g. id) or we aren't in a multiple element field
            field.prop( "checked", false );
          } else if ( field.is( ":radio" ) ) {
            if ( field.val() === resque ) {
              field.prop( "checked", true );
            }
          } else if ( name === undefined || name.indexOf( "[" ) === -1 ) {
            // If we aren't named by name (e.g. id) or we aren't in a multiple element field
            field.val( resque );
          } else {
            resque = resque.split( "," );
            field.val( resque );
          }
        },

        /**
         * Bind immediate saving (on typing/checking/changing) field data to local storage when user fills it
         *
         * @param Object field    jQuery form element object
         * @param String prefix  prefix used as key to store data in local storage
         *
         * @return void
         */
        bindSaveDataImmediately: function( field, prefix ) {
          var self = this;
          if ( 'onpropertychange' in field ) {
            field.get(0).onpropertychange = function() {
              self.saveToBrowserStorage( prefix, field.val() );
            };
          } else {
            field.get(0).oninput = function() {
              self.saveToBrowserStorage( prefix, field.val() );
            };
          }
          if ( this.isCKEditorExists() ) {
            var editor = CKEDITOR.instances[ field.attr("name") ] || CKEDITOR.instances[ field.attr("id") ];
            if ( editor ) {
              editor.document.on( 'keyup', function() {
                editor.updateElement();
                self.saveToBrowserStorage( prefix, field.val() );
              } );
            }
          }
        },

        /**
         * Save data to Local Storage and fire callback if defined
         *
         * @param String key
         * @param String value
         * @param Boolean [true] fireCallback
         *
         * @return void
         */
        saveToBrowserStorage: function( key, value, fireCallback ) {
          var self = this;

          var callback_result = self.options.onBeforeSave.call( self );
          if ( callback_result !== undefined && callback_result === false ) {
            return;
          }

          // if fireCallback is undefined it should be true
          fireCallback = fireCallback === undefined ? true : fireCallback;
          this.browserStorage.set( key, value );
          if ( fireCallback && value !== "" ) {
            this.options.onSave.call( this );
          }
        },

        /**
         * Bind saving field data on change
         *
         * @param Object field    jQuery form element object
         *
         * @return void
         */
        bindSaveDataOnChange: function( field ) {
          var self = this;
          field.change( function() {
            self.saveAllData();
          } );
        },

        /**
         * Saving (by timeout) field data to local storage when user fills it
         *
         * @return void
         */
        saveDataByTimeout: function() {
          var self = this;
          var targetForms = self.targets;
          setTimeout( ( function() {
            function timeout() {
              self.saveAllData();
              setTimeout( timeout, self.options.timeout * 1000 );
            }
            return timeout;
          } )( targetForms ), self.options.timeout * 1000 );
        },

        /**
         * Bind release form fields data from local storage on submit/reset form
         *
         * @return void
         */
        bindReleaseData: function() {
          var self = this;
          self.targets.each( function() {
            var target = $( this );
            var formIdAndName = getElementIdentifier( target );
            $( this ).bind( "submit reset", function() {
              self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
            } );
          } );
        },

        /**
         * Manually release form fields
         *
         * @return void
         */
        manuallyReleaseData: function() {
          var self = this;
          self.targets.each( function() {
            var target = $( this );
            var formIdAndName = getElementIdentifier( target );
            self.releaseData( formIdAndName, self.findFieldsToProtect( target ) );
          } );
        },

        /**
         * Bind release form fields data from local storage on submit/resett form
         *
         * @param String targetFormIdAndName  a form identifier consists of its id and name glued
         * @param Object fieldsToProtect    jQuery object contains form fields to protect
         *
         * @return void
         */
        releaseData: function( targetFormIdAndName, fieldsToProtect ) {
          var released = false;
          var self = this;

          // Released form, are not started anymore. Fix for ajax loaded forms.
          params.started[ self.getInstanceIdentifier() ] = false;

          fieldsToProtect.each( function() {
            if ( $.inArray( this, self.options.excludeFields ) !== -1 ) {
              // Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
              return true;
            }
            var field = $( this );
            var prefix = (self.options.locationBased ? self.href : "") + targetFormIdAndName + getElementIdentifier( field ) + self.options.customKeySuffix;
            self.browserStorage.remove( prefix );
            released = true;
          } );

          if ( released ) {
            self.options.onRelease.call( self );
          }
        }

      };
    }

    return {
      getInstance: function( identifier ) {
        if ( ! params.instantiated[ identifier ] ) {
          params.instantiated[ identifier ] = init();
          params.instantiated[ identifier ].setInstanceIdentifier( identifier );
          params.instantiated[ identifier ].setInitialOptions();
        }
        if ( identifier ) {
          return params.instantiated[ identifier ];
        }
        return params.instantiated[ identifier ];
      },

      free: function() {
        params = {
          instantiated: [],
          started: []
        };
        return null;
      },
      version: '1.1.3'
    };
  } )();
} )( jQuery );
<|endoftext|>


<commit_before>const fs = require("fs");

class ResponseFactory {
    constructor(app, req, res, root = "") {
        this.app = app;
        this.req = req;
        this.res = res;
        this.root = root;
    }

    sendRenderedResponse(template, data = null, mimeType = "text/html") {
        var sendData = this.getAutomaticTemplateData();
        if (data) sendData = Object.assign({}, sendData, data);
        return this.res.header("Content-Type", mimeType).render(this.root + template, sendData);
    }

    getAutomaticTemplateData() {
        var resources = this.req.place.moduleManager.getResourcesFromModules(this.req);
        var redirectURLPart = this.req.path == "/signin" || this.req.path == "/signup" ? "" : encodeURIComponent(this.req.baseUrl + "/" + this.req.url.substr(1));
        var path = this.req.baseUrl + this.req.path;
        var data = { url: this.req.url, path: path, config: this.app.config, fs: fs, renderCaptcha: () => this.app.recaptcha.render(), redirectURLPart: redirectURLPart, moduleManager: this.req.place.moduleManager, resources: resources, req: this.req, res: this.res };
        if (typeof this.req.user !== undefined && this.req.user) data.user = this.req.user;
        return data;
    }
}

ResponseFactory.prototype = Object.create(ResponseFactory.prototype);

module.exports = ResponseFactory;<commit_msg>OMG FFS<commit_after>const fs = require("fs");

class ResponseFactory {
    constructor(app, req, res, root = "") {
        this.app = app;
        this.req = req;
        this.res = res;
        this.root = root;
    }

    sendRenderedResponse(template, data = null, mimeType = "text/html") {
        var sendData = this.getAutomaticTemplateData();
        if (data) sendData = Object.assign({}, sendData, data);
        return this.res.header("Content-Type", mimeType).render(this.root + template, sendData);
    }

    getAutomaticTemplateData() {
        var resources = this.req.place.moduleManager.getResourcesFromModules(this.req);
        var redirectURLPart = this.req.path == "/signin" || this.req.path == "/signup" ? "" : encodeURIComponent(this.req.baseUrl.substr(1) + "/" + this.req.url.substr(1));
        var path = this.req.baseUrl + this.req.path;
        var data = { url: this.req.url, path: path, config: this.app.config, fs: fs, renderCaptcha: () => this.app.recaptcha.render(), redirectURLPart: redirectURLPart, moduleManager: this.req.place.moduleManager, resources: resources, req: this.req, res: this.res };
        if (typeof this.req.user !== undefined && this.req.user) data.user = this.req.user;
        return data;
    }
}

ResponseFactory.prototype = Object.create(ResponseFactory.prototype);

module.exports = ResponseFactory;<|endoftext|>


<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint node:true */

'use strict';

describe(require('path').basename(__filename), function () {
    it('needs specs');
});<commit_msg>add subscription tests<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint node:true */

'use strict';

describe('Subscription', function () {
    var Subscription;

    helper.before();

    before(function () {
        Subscription = helper.injector.get('Subscription');

        this.messenger = {
            cancel: sinon.stub().returns(
                Q.resolve()
            ),
            deleteQueue: sinon.stub().returns(
                Q.resolve()
            )
        }

        this.subject = new Subscription(
            this.messenger,
            {
                consumerTag: 'consumerTag',
                queue: 'queue'
            }
        );
    })

    helper.after();

    describe('constructor', function () {
        it('assigns messenger to messenger', function () {
            this.subject.messenger.should.deep.equal(this.messenger);
        });

        it('assigns options to options', function () {
            this.subject.options.should.deep.equal({
                consumerTag: 'consumerTag',
                queue: 'queue'
            });
        });

        [
            'queue',
            'consumerTag'
        ].forEach(function (property) {
            it ('provides a ' + property + ' accessor', function () {
                this.subject[property].should.equal(property);
            });
        });
    });

    describe('dispose', function () {
        it('should call messenger.cancel and messenger.deleteQueue', function () {
            var self = this;

            return this.subject.dispose().then(function () {
                self.messenger.cancel.should.have.been.calledWith('consumerTag');
                self.messenger.deleteQueue.should.have.been.calledWith('queue');
            });
        });
    });
});<|endoftext|>


<commit_before>var currentExplManager = undefined;
var currentExplanationStep = undefined;
var saliencyLookupMap = {};

function handleExplanationDetails(explDetails){
	if (explDetails.hasExplPoint()){
        explanationPoint = explDetails.getExplPoint();
        var barChartMessage = explanationPoint.getBarChart();
        var rawChart = convertProtobufChartToJSChart(barChartMessage);
        //ignore true data for testing
        //currentExplManager.setChartData(getSeeSawChart());
        var saliency = explanationPoint.getSaliency();
        saliencyLookupMap = saliency.getSaliencyMapMap();
        var step = sessionIndexManager.getCurrentIndex();
        currentExplManager.setChartData(rawChart, step);
	}
	else {
		console.log("MISSING expl point!");
	}
}

function askBackendForExplanationRewardInfo(stepNumber) {
	var userCommand = new proto.scaii.common.UserCommand;
	userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.EXPLAIN);
	var args = ['' +stepNumber];
	userCommand.setArgsList(args);
	stageUserCommand(userCommand);
	currentExplanationStep = stepNumber;
	if (stepNumber == sessionIndexManager.getCurrentIndex()) {
		//console.log("no need to move - already at step with explanation");
	}
	else {
		jumpToStep(stepNumber);//FIXME - can get rid of this?
	}
}

function renderWhyButton(step, x, y){
    $("#why-button").remove();
    var whyButton = document.createElement("BUTTON");
    var buttonId = "why-button";
    whyButton.setAttribute("id", buttonId);
    var why = document.createTextNode("why?");
    whyButton.appendChild(why);
    whyButton.setAttribute("style", 'z-index:' + zIndexMap["whyButton"] + ';position:relative;left:' + x + 'px;top:-17px;font-family:Arial;');
    $("#explanation-control-panel").append(whyButton);
    $("#" + buttonId).click(function(e) {
        if (currentExplManager.chartVisible) {
            var logLine = templateMap["hideWhy"];
            logLine = logLine.replace("<HIDE_WHY>", "NA");
            targetClickHandler(e, logLine);
        }
        else {
            var logLine = templateMap["showWhy"];
            logLine = logLine.replace("<SHW_WHY>", "NA");
            targetClickHandler(e, logLine);
        }

        e.preventDefault();
        processWhyClick(step);
    })
}
function addFunctionsToRawChart(rawChart){
    var ch = addColorToBars(rawChart);
    ch = addUtilityFunctions(ch);
    ch.actions = ch.getActionsInQuadrantOrder(ch.actions);
    ch = addRankingFunctions(ch);
    ch = addSelectionFunctions(ch);
    ch = addTextFunctions(ch);
    ch = addGeometryFunctions(ch);
    return ch;
}

function setDefaultSelections(chartData,treatmentID) {
    var action = chartData.getMaxValueAction();
    var bar = chartData.getMaxValueBar(action.bars);
    if (treatmentID == "T1"){
        chartData.showSalienciesForActionName(action.name);
    }
    else if (treatmentID == "T3"){
        chartData.showSalienciesForRewardName(bar.name);
    }
    return chartData;
}
function addConvenienceDataStructures(chartData) {
    if (chartData.actionForNameMap == undefined){
        chartData.actionForNameMap = {};
        chartData.actionNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            var actionName = action.name;
            action.fullName = actionName;
            action.type = "action";
            chartData.actionForNameMap[actionName] = action;
            chartData.actionNames.push(actionName);
        }
    }

    if (chartData.actionRewardForNameMap == undefined){
        chartData.actionRewardForNameMap = {};
        chartData.actionRewardNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            for (var j in action.bars){
                var bar = action.bars[j];
                if (bar.name == "Living") {
                    //Do nothing
                } else {
                    bar.fullName = action.name+ "." + bar.name;
                    bar.type = "reward";
                    bar.actionName = action.name;
                    chartData.actionRewardForNameMap[bar.fullName] = bar;
                    chartData.actionRewardNames.push(bar.fullName);
                }
            }
        }
    }

    if (chartData.rewardNames == undefined){
        chartData.rewardNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            for (var j in action.bars){
                var bar = action.bars[j];
                if (bar.name == "Living") {
                    //Do nothing
                }
                else if (!chartData.rewardNames.includes(bar.name)) {
                    chartData.rewardNames.push(bar.name);
                }
            }
        }
    }
    return chartData;
}

function ensureActionValuesSet(chartData) {
    for (var i in chartData.actions) {
        var action = chartData.actions[i];
        var actionTotal = 0.0;
        for (var j in action.bars){
            var bar = action.bars[j];
            actionTotal = actionTotal + bar.value;
        }
        action.value = actionTotal;
    }
    return chartData;
}
function getExplanationsV2Manager(){
    var cm = {};
    cm.data = undefined;
    cm.filename = undefined;
    cm.saliencyRandomized = false;
    cm.renderLog = [];
    cm.userStudyMode = false;
    cm.chartVisible = false;
    cm.showSaliencyAccessButton = false;
    cm.saliencyVisible = false;
    cm.saliencyCombined = false;
    cm.treatmentID = "NA";
    cm.showLosingActionSmaller = false;
    cm.showHoverScores = false;
    cm.chartUI = getChartV2UI();
    cm.saliencyUI = getSaliencyV2UI();
    cm.stepsWithExplanations = [];
    cm.chartDataForStep = {};
    cm.currentQuestionType = undefined;
    cm.entityListForDP = {};
    cm.waitForClickDP = 0;

    cm.captureEntitiesForDecisionPoint = function(step) {
        if (this.entityListForDP[step] == undefined){
            this.entityListForDP[step] = this.cloneMasterEntitiesList();
        }
    }

    cm.removeOverlaysAndOutlines = function() {
        if (this.data != undefined) {
            this.saliencyUI.removeAllOverlaysAndOutlines(this.data);
        }
    }

    cm.removeAndForgetOverlaysAndOutlines = function () {
        if (this.data != undefined) {
            this.saliencyUI.removeAllOverlaysAndOutlines(this.data);
            this.saliencyUI.forgetAllOverlaysAndOutlines(this.data);
        }
    }

    cm.cloneMasterEntitiesList = function() {
        var clone = {};
        for (var i in masterEntities) {
            var entity = masterEntities[i];
            var entityClone = new proto.scaii.common.Entity;
            entityClone.setId(entity.getId());
            if (entity.hasPos()){
                copyPos(entity, entityClone);
            }
            var shapesList = entity.getShapesList();
            for (var j in shapesList){
                var shape = shapesList[j];
                copyShapeIntoCloneEntity(shape, entityClone);
            }
            clone[entityClone.getId()]= entityClone;
        }
        return clone;
    }
    cm.setChartData = function(rawChartData, step){
        var cachedChartData = this.chartDataForStep[step];
        if (cachedChartData == undefined) {
            this.data = addFunctionsToRawChart(rawChartData);
            this.data = ensureActionValuesSet(this.data);
            this.data = addConvenienceDataStructures(this.data);
            this.data = setDefaultSelections(this.data, this.treatmentID);
            this.chartDataForStep[step] = this.data;
            this.stepsWithExplanations.push(step);
        }
        else {
            this.data = cachedChartData;
        }
        this.render();
    }

    cm.switchToExplanationsForThisDecisionPoint = function(step) {
        this.data = this.chartDataForStep[step];
        this.render();
    }

    cm.applyFunctionToEachCachedDataset = function(f, key) {
        for (var i in this.stepsWithExplanations){
            var step = this.stepsWithExplanations[i];
            var data = this.chartDataForStep[step];
            f(data, key);
        }
    }
    cm.hasExplDataForStep = function(step) {
        if (this.chartDataForStep[step] == undefined) {
            return false;
        }
        return true;
    }

    cm.setWhyButtonAccessibility = function() {
        if (userStudyMode) {
            // see if that step has a dp on it.  If so enable, else disable
            if (sessionIndexManager.isAtDecisionPoint()){
                $("#why-button").attr("disabled", "false");
            }
            else {
                $("#why-button").attr("disabled", "true");
            }
        }
    }

    cm.setCurrentStepAfterJump = function(step){
        // find first step less than or equal to this one
        var existingData = this.data;
        for (var i = this.stepsWithExplanations.length - 1; i >= 0; i--){
            var curStep = this.stepsWithExplanations[i];
            if (Number(curStep) <= Number(step)){
                this.data = this.chartDataForStep[curStep];
                if (existingData != this.data){
                    currentExplManager.applyFunctionToEachCachedDataset(detachChannelItem,"overlayCanvas");
                }
                this.render();

                return;
            }
        }
    }

    cm.setQuestionType = function(type) {
        this.currentQuestionType = type;
        if (type == "waitForPredictionClick"){
            this.chartVisible = false;
            this.saliencyVisible = false;
            this.render();
        }
    }
    cm.setExplanationVisibility = function(currentDPIndex, step) {
        if (this.waitForClickDP < currentDPIndex.length && step > currentDPIndex[this.waitForClickDP]) {
            this.waitForClickDP++;
        }
        if (this.currentQuestionType == "waitForPredictionClick" && currentDPIndex[this.waitForClickDP] == step) {
            this.chartVisible = false;
            this.saliencyVisible = false;
            this.render();
        } else {
            this.chartVisible = true;
            this.saliencyVisible = true;
            this.render();
        }
    }
    cm.setFilename = function(filename){
        this.filename = filename;
        if (filename.startsWith("tutorial")){
            this.saliencyRandomized = true;
        }
        else {
            this.saliencyRandomized = false;
        }
    }

    cm.setUserStudyMode = function(val){
        this.userStudyMode = val;
        this.showLosingActionSmaller = val;
        this.showHoverScores = !val;

        this.chartVisible = false;
        this.showSaliencyAccessButton = true;
        this.saliencyVisible = false;
        //.saliencyCombined = !val;
        // turn off combined saliency for now
        this.saliencyCombined = false;
    }

    cm.noteQuestionWasAnswered = function(){
        if (this.currentQuestionType == "waitForPredictionClick"){
            this.resetExplanationVisibility();
        }
    }
    cm.resetExplanationVisibility = function(){
        this.setUserStudyTreatment(this.treatmentID);
        this.render();
    }

    cm.setUserStudyTreatment = function(val) {
        if (val == "T0"){
            this.treatmentID = "T0";
            this.chartVisible = false;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = false;
            this.saliencyCombined = false;
        }
        else if (val == "T1"){
            this.treatmentID = "T1";
            this.chartVisible = false;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = true;
            this.saliencyCombined = false;

        }
        else if (val == "T2"){
            this.treatmentID = "T2";
            this.chartVisible = true;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = false;
            this.saliencyCombined = false;

        }
        else if (val == "T3"){
            this.treatmentID = "T3";
            this.chartVisible = true;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = true;
            this.saliencyCombined = false;

        }
        else {
            alert("unknown treatment name " +val);
        }
    }

    cm.render = function(mode){
        cleanExplanationUI();
        this.renderLog = [];
        if (this.data == undefined) {
            return;
        }
        if (this.treatmentID == "T0"){
            // no action
        }
        else if (this.treatmentID == "T1"){
            this.renderT1(mode);
        } else if (this.treatmentID == "T2"){
            this.renderT2(mode);
        }
        else {
            // normal mode falls through to here and matches T3 as desired
            this.renderT3(mode);
        }
        if (this.userStudyMode){
            ensureStudyControlScreenIsWideEnough();
        }
    }

    cm.renderT1 = function(mode){
        if (this.saliencyVisible) {
            this.renderSaliencyDetailed(mode);
        }
    }

    cm.renderT2 = function(mode){
        if (this.chartVisible){
            this.renderChartDetailed(mode, "T2");
        }
    }

    cm.renderT3 = function(mode){
        if (this.chartVisible){
            this.renderChartDetailed(mode, "T3");
        }
        if (this.showSaliencyAccessButton && this.chartVisible){
            this.renderSaliencyAccessButton(mode);
        }
        if (this.saliencyVisible && this.saliencyCombined){
            this.renderSaliencyCombined(mode);
        }
        if (this.saliencyVisible && !this.saliencyCombined){
            this.renderSaliencyDetailed(mode);
        }
    }

    cm.renderChartDetailed = function(mode, treatment){
        if (mode == "trace"){
            this.renderLog.push("renderChartDetailed");
            return;
        }
        else {
            this.chartUI.renderChartDetailed(this.data, treatment);
        }
    }

    cm.renderSaliencyAccessButton = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyAccessButton");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyAccessControls();
        }
    }

    cm.renderSaliencyCombined = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyCombined");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyCombined(this.data);
        }
    }

    cm.renderSaliencyDetailed = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyDetailed");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyDetailed(this.data);
        }
    }
    return cm;
}
<commit_msg>remember the ranks of the actions<commit_after>var currentExplManager = undefined;
var currentExplanationStep = undefined;
var saliencyLookupMap = {};

function handleExplanationDetails(explDetails){
	if (explDetails.hasExplPoint()){
        explanationPoint = explDetails.getExplPoint();
        var barChartMessage = explanationPoint.getBarChart();
        var rawChart = convertProtobufChartToJSChart(barChartMessage);
        //ignore true data for testing
        //currentExplManager.setChartData(getSeeSawChart());
        var saliency = explanationPoint.getSaliency();
        saliencyLookupMap = saliency.getSaliencyMapMap();
        var step = sessionIndexManager.getCurrentIndex();
        currentExplManager.setChartData(rawChart, step);
	}
	else {
		console.log("MISSING expl point!");
	}
}

function askBackendForExplanationRewardInfo(stepNumber) {
	var userCommand = new proto.scaii.common.UserCommand;
	userCommand.setCommandType(proto.scaii.common.UserCommand.UserCommandType.EXPLAIN);
	var args = ['' +stepNumber];
	userCommand.setArgsList(args);
	stageUserCommand(userCommand);
	currentExplanationStep = stepNumber;
	if (stepNumber == sessionIndexManager.getCurrentIndex()) {
		//console.log("no need to move - already at step with explanation");
	}
	else {
		jumpToStep(stepNumber);//FIXME - can get rid of this?
	}
}

function renderWhyButton(step, x, y){
    $("#why-button").remove();
    var whyButton = document.createElement("BUTTON");
    var buttonId = "why-button";
    whyButton.setAttribute("id", buttonId);
    var why = document.createTextNode("why?");
    whyButton.appendChild(why);
    whyButton.setAttribute("style", 'z-index:' + zIndexMap["whyButton"] + ';position:relative;left:' + x + 'px;top:-17px;font-family:Arial;');
    $("#explanation-control-panel").append(whyButton);
    $("#" + buttonId).click(function(e) {
        if (currentExplManager.chartVisible) {
            var logLine = templateMap["hideWhy"];
            logLine = logLine.replace("<HIDE_WHY>", "NA");
            targetClickHandler(e, logLine);
        }
        else {
            var logLine = templateMap["showWhy"];
            logLine = logLine.replace("<SHW_WHY>", "NA");
            targetClickHandler(e, logLine);
        }

        e.preventDefault();
        processWhyClick(step);
    })
}
function addFunctionsToRawChart(rawChart){
    var ch = addColorToBars(rawChart);
    ch = addUtilityFunctions(ch);
    ch.actions = ch.getActionsInQuadrantOrder(ch.actions);
    ch = addRankingFunctions(ch);
    ch = addSelectionFunctions(ch);
    ch = addTextFunctions(ch);
    ch = addGeometryFunctions(ch);
    return ch;
}

function setDefaultSelections(chartData,treatmentID) {
    var action = chartData.getMaxValueAction();
    var bar = chartData.getMaxValueBar(action.bars);
    if (treatmentID == "T1"){
        chartData.showSalienciesForActionName(action.name);
    }
    else if (treatmentID == "T3"){
        chartData.showSalienciesForRewardName(bar.name);
    }
    return chartData;
}
function addConvenienceDataStructures(chartData) {
    if (chartData.actionForNameMap == undefined){
        chartData.actionForNameMap = {};
        chartData.actionNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            var actionName = action.name;
            action.fullName = actionName;
            action.type = "action";
            chartData.actionForNameMap[actionName] = action;
            chartData.actionNames.push(actionName);
        }
    }

    if (chartData.actionRewardForNameMap == undefined){
        chartData.actionRewardForNameMap = {};
        chartData.actionRewardNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            for (var j in action.bars){
                var bar = action.bars[j];
                if (bar.name == "Living") {
                    //Do nothing
                } else {
                    bar.fullName = action.name+ "." + bar.name;
                    bar.type = "reward";
                    bar.actionName = action.name;
                    chartData.actionRewardForNameMap[bar.fullName] = bar;
                    chartData.actionRewardNames.push(bar.fullName);
                }
            }
        }
    }

    if (chartData.rewardNames == undefined){
        chartData.rewardNames = [];
        for(var i in chartData.actions){
            var action = chartData.actions[i];
            for (var j in action.bars){
                var bar = action.bars[j];
                if (bar.name == "Living") {
                    //Do nothing
                }
                else if (!chartData.rewardNames.includes(bar.name)) {
                    chartData.rewardNames.push(bar.name);
                }
            }
        }
    }
    return chartData;
}

function ensureActionValuesSet(chartData) {
    for (var i in chartData.actions) {
        var action = chartData.actions[i];
        var actionTotal = 0.0;
        for (var j in action.bars){
            var bar = action.bars[j];
            actionTotal = actionTotal + bar.value;
        }
        action.value = actionTotal;
    }
    return chartData;
}
function getExplanationsV2Manager(){
    var cm = {};
    cm.data = undefined;
    cm.filename = undefined;
    cm.saliencyRandomized = false;
    cm.renderLog = [];
    cm.userStudyMode = false;
    cm.chartVisible = false;
    cm.showSaliencyAccessButton = false;
    cm.saliencyVisible = false;
    cm.saliencyCombined = false;
    cm.treatmentID = "NA";
    cm.showLosingActionSmaller = false;
    cm.showHoverScores = false;
    cm.chartUI = getChartV2UI();
    cm.saliencyUI = getSaliencyV2UI();
    cm.stepsWithExplanations = [];
    cm.chartDataForStep = {};
    cm.currentQuestionType = undefined;
    cm.entityListForDP = {};
    cm.waitForClickDP = 0;
    cm.actionsRanked = [];

    cm.captureEntitiesForDecisionPoint = function(step) {
        if (this.entityListForDP[step] == undefined){
            this.entityListForDP[step] = this.cloneMasterEntitiesList();
        }
    }

    cm.removeOverlaysAndOutlines = function() {
        if (this.data != undefined) {
            this.saliencyUI.removeAllOverlaysAndOutlines(this.data);
        }
    }

    cm.removeAndForgetOverlaysAndOutlines = function () {
        if (this.data != undefined) {
            this.saliencyUI.removeAllOverlaysAndOutlines(this.data);
            this.saliencyUI.forgetAllOverlaysAndOutlines(this.data);
        }
    }

    cm.cloneMasterEntitiesList = function() {
        var clone = {};
        for (var i in masterEntities) {
            var entity = masterEntities[i];
            var entityClone = new proto.scaii.common.Entity;
            entityClone.setId(entity.getId());
            if (entity.hasPos()){
                copyPos(entity, entityClone);
            }
            var shapesList = entity.getShapesList();
            for (var j in shapesList){
                var shape = shapesList[j];
                copyShapeIntoCloneEntity(shape, entityClone);
            }
            clone[entityClone.getId()]= entityClone;
        }
        return clone;
    }
    cm.setChartData = function(rawChartData, step){
        var cachedChartData = this.chartDataForStep[step];
        if (cachedChartData == undefined) {
            this.data = addFunctionsToRawChart(rawChartData);
            this.data = ensureActionValuesSet(this.data);
            this.data = addConvenienceDataStructures(this.data);
            this.data = setDefaultSelections(this.data, this.treatmentID);
            this.chartDataForStep[step] = this.data;
            this.stepsWithExplanations.push(step);
            this.actionsRanked = rankThings(this.data.actions, getThingWithMaxValue);
        }
        else {
            this.data = cachedChartData;
        }
        this.render();
    }

    cm.switchToExplanationsForThisDecisionPoint = function(step) {
        this.data = this.chartDataForStep[step];
        this.render();
    }

    cm.applyFunctionToEachCachedDataset = function(f, key) {
        for (var i in this.stepsWithExplanations){
            var step = this.stepsWithExplanations[i];
            var data = this.chartDataForStep[step];
            f(data, key);
        }
    }
    cm.hasExplDataForStep = function(step) {
        if (this.chartDataForStep[step] == undefined) {
            return false;
        }
        return true;
    }

    cm.setWhyButtonAccessibility = function() {
        if (userStudyMode) {
            // see if that step has a dp on it.  If so enable, else disable
            if (sessionIndexManager.isAtDecisionPoint()){
                $("#why-button").attr("disabled", "false");
            }
            else {
                $("#why-button").attr("disabled", "true");
            }
        }
    }

    cm.setCurrentStepAfterJump = function(step){
        // find first step less than or equal to this one
        var existingData = this.data;
        for (var i = this.stepsWithExplanations.length - 1; i >= 0; i--){
            var curStep = this.stepsWithExplanations[i];
            if (Number(curStep) <= Number(step)){
                this.data = this.chartDataForStep[curStep];
                if (existingData != this.data){
                    currentExplManager.applyFunctionToEachCachedDataset(detachChannelItem,"overlayCanvas");
                }
                this.render();

                return;
            }
        }
    }

    cm.setQuestionType = function(type) {
        this.currentQuestionType = type;
        if (type == "waitForPredictionClick"){
            this.chartVisible = false;
            this.saliencyVisible = false;
            this.render();
        }
    }
    cm.setExplanationVisibility = function(currentDPIndex, step) {
        if (this.waitForClickDP < currentDPIndex.length && step > currentDPIndex[this.waitForClickDP]) {
            this.waitForClickDP++;
        }
        if (this.currentQuestionType == "waitForPredictionClick" && currentDPIndex[this.waitForClickDP] == step) {
            this.chartVisible = false;
            this.saliencyVisible = false;
            this.render();
        } else {
            this.chartVisible = true;
            this.saliencyVisible = true;
            this.render();
        }
    }
    cm.setFilename = function(filename){
        this.filename = filename;
        if (filename.startsWith("tutorial")){
            this.saliencyRandomized = true;
        }
        else {
            this.saliencyRandomized = false;
        }
    }

    cm.setUserStudyMode = function(val){
        this.userStudyMode = val;
        this.showLosingActionSmaller = val;
        this.showHoverScores = !val;

        this.chartVisible = false;
        this.showSaliencyAccessButton = true;
        this.saliencyVisible = false;
        //.saliencyCombined = !val;
        // turn off combined saliency for now
        this.saliencyCombined = false;
    }

    cm.noteQuestionWasAnswered = function(){
        if (this.currentQuestionType == "waitForPredictionClick"){
            this.resetExplanationVisibility();
        }
    }
    cm.resetExplanationVisibility = function(){
        this.setUserStudyTreatment(this.treatmentID);
        this.render();
    }

    cm.setUserStudyTreatment = function(val) {
        if (val == "T0"){
            this.treatmentID = "T0";
            this.chartVisible = false;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = false;
            this.saliencyCombined = false;
        }
        else if (val == "T1"){
            this.treatmentID = "T1";
            this.chartVisible = false;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = true;
            this.saliencyCombined = false;

        }
        else if (val == "T2"){
            this.treatmentID = "T2";
            this.chartVisible = true;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = false;
            this.saliencyCombined = false;

        }
        else if (val == "T3"){
            this.treatmentID = "T3";
            this.chartVisible = true;
            this.showSaliencyAccessButton = false;
            this.saliencyVisible = true;
            this.saliencyCombined = false;

        }
        else {
            alert("unknown treatment name " +val);
        }
    }

    cm.render = function(mode){
        cleanExplanationUI();
        this.renderLog = [];
        if (this.data == undefined) {
            return;
        }
        if (this.treatmentID == "T0"){
            // no action
        }
        else if (this.treatmentID == "T1"){
            this.renderT1(mode);
        } else if (this.treatmentID == "T2"){
            this.renderT2(mode);
        }
        else {
            // normal mode falls through to here and matches T3 as desired
            this.renderT3(mode);
        }
        if (this.userStudyMode){
            ensureStudyControlScreenIsWideEnough();
        }
    }

    cm.renderT1 = function(mode){
        if (this.saliencyVisible) {
            this.renderSaliencyDetailed(mode);
        }
    }

    cm.renderT2 = function(mode){
        if (this.chartVisible){
            this.renderChartDetailed(mode, "T2");
        }
    }

    cm.renderT3 = function(mode){
        if (this.chartVisible){
            this.renderChartDetailed(mode, "T3");
        }
        if (this.showSaliencyAccessButton && this.chartVisible){
            this.renderSaliencyAccessButton(mode);
        }
        if (this.saliencyVisible && this.saliencyCombined){
            this.renderSaliencyCombined(mode);
        }
        if (this.saliencyVisible && !this.saliencyCombined){
            this.renderSaliencyDetailed(mode);
        }
    }

    cm.renderChartDetailed = function(mode, treatment){
        if (mode == "trace"){
            this.renderLog.push("renderChartDetailed");
            return;
        }
        else {
            this.chartUI.renderChartDetailed(this.data, treatment);
        }
    }

    cm.renderSaliencyAccessButton = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyAccessButton");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyAccessControls();
        }
    }

    cm.renderSaliencyCombined = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyCombined");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyCombined(this.data);
        }
    }

    cm.renderSaliencyDetailed = function(mode){
        if (mode == "trace"){
            this.renderLog.push("renderSaliencyDetailed");
            return;
        }
        else {
            this.saliencyUI.renderSaliencyDetailed(this.data);
        }
    }
    return cm;
}
<|endoftext|>


<commit_before>'use strict';

module.exports.getList = function getList(name) {
    let obj;
    const nm = name !=null ? name.toLowerCase() : null;
    if(!nm) return {message:'No list name defined'};
    if(name){
        obj = {};
        obj.name = nm;
        obj.list = null;
        switch (nm) {
            case 'stooges':
                obj.list = ['moe', 'larry', 'curly'];
                break;
            case 'jetsons':
                obj.list = ['george', 'jane', 'judy', 'elroy'];
                break;
            case 'flintstones':
                obj.list = ['fred', 'wilma', 'pebbles'];
                break;
            default:
                break;
        }
    }

    return obj;
}<commit_msg>added comment<commit_after>'use strict';
/*
Method for delivering data to the API
 */
module.exports.getList = function getList(name) {
    let obj;
    const nm = name !=null ? name.toLowerCase() : null;
    if(!nm) return {message:'No list name defined'};
    if(name){
        obj = {};
        obj.name = nm;
        obj.list = null;
        switch (nm) {
            case 'stooges':
                obj.list = ['moe', 'larry', 'curly'];
                break;
            case 'jetsons':
                obj.list = ['george', 'jane', 'judy', 'elroy'];
                break;
            case 'flintstones':
                obj.list = ['fred', 'wilma', 'pebbles'];
                break;
            default:
                break;
        }
    }

    return obj;
}<|endoftext|>


<commit_before>var Sequelize = require('sequelize');

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Globals /////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

var GAME_STATES = [
  'INPROG',
  'COMPLETE'
];

var ROUND_STAGES = [
  'ROUND_1',
  'ROUND_2',
  'ROUND_3',
  'ROUND_4',
  'ROUND_5',
  'ROUND_6',
  'FACEOFF_1',
  'FACEOFF_2',
  'FACEOFF_3'
];

var SCORE_BONUSES = [
  'NONE',
  'SPEED'
];

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Model definitions ///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

var User = {
  user_name: Sequelize.STRING
};

var Game = {
  state: Sequelize.ENUM(GAME_STATES),
  winner: Sequelize.INTEGER
};

var Round = {
  stage: Sequelize.ENUM(ROUND_STAGES),
  acronym: Sequelize.ARRAY,
  validator: Sequelize.STRING
};

var Score = {
  score: Sequelize.INTEGER,
  bonus: Sequelize.ENUM(SCORE_BONUSES)
};

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private methods /////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

function _define(connection, modelName, model) {
  try {
    return connection.define(modelName, model);
  } catch (ex) {
    console.error(ex);
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public methods //////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

function _defineAll(connection) {

  if (connection && connection.define) {

    // Define each Model

    var user = _define(connection, 'user', User);
    var game = _define(connection, 'game', Game);
    var round = _define(connection, 'round', Round);
    var score = _define(connection, 'score', Score);

    // Define Model Associations

    // user.belongsTo(game);
    // round.belongsTo(game);
    // score.hasMany(user, round);
  } else {
    console.error('A valid Sequelize connection is required.');
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Export //////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

module.exports = {
  defineAllModels: _defineAll
}<commit_msg>Comment-out relations<commit_after>var Sequelize = require('sequelize');

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Globals /////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

var GAME_STATES = [
  'INPROG',
  'COMPLETE'
];

var ROUND_STAGES = [
  'ROUND_1',
  'ROUND_2',
  'ROUND_3',
  'ROUND_4',
  'ROUND_5',
  'ROUND_6',
  'FACEOFF_1',
  'FACEOFF_2',
  'FACEOFF_3'
];

var SCORE_BONUSES = [
  'NONE',
  'SPEED'
];

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Model definitions ///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

var User = {
  user_name: Sequelize.STRING
};

var Game = {
  state: Sequelize.ENUM(GAME_STATES),
  winner: Sequelize.INTEGER
};

var Round = {
  stage: Sequelize.ENUM(ROUND_STAGES),
  acronym: Sequelize.ARRAY(Sequelize.STRING),
  validator: Sequelize.STRING
};

var Score = {
  score: Sequelize.INTEGER,
  bonus: Sequelize.ENUM(SCORE_BONUSES)
};

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private methods /////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

function _define(connection, modelName, model) {
  try {
    return connection.define(modelName, model);
  } catch (ex) {
    console.error(ex);
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public methods //////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

function _defineAll(connection) {

  if (connection && connection.define) {

    // Define each Model

    var users = _define(connection, 'user', User);
    var games = _define(connection, 'game', Game);
    var rounds = _define(connection, 'round', Round);
    var scores = _define(connection, 'score', Score);

    // Define Model Associations

    // users.belongsTo(games);
    // rounds.belongsTo(games);
    // scores.hasMany(users, rounds);
  } else {
    console.error('A valid Sequelize connection is required.');
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Export //////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

module.exports = {
  defineAllModels: _defineAll
}<|endoftext|>


<commit_before>import React from "react";
import AvatarCropper from "../../lib";
import {
  Modal,
  Button
} from "react-bootstrap";

var App = React.createClass({
  getInitialState: function() {
    return {
      cropperOpen: false,
      img: null,
      croppedImg: "http://www.fillmurray.com/400/400"
    }
  },
  handleFileChange: function(dataURI) {
    this.setState({
      img: dataURI,
      croppedImg: this.state.croppedImg,
      cropperOpen: true
    });
  },
  handleCrop: function(dataURI) {
    this.setState({
      cropperOpen: false,
      img: null,
      croppedImg: dataURI
    });
  },
  handleRequestHide: function() {
    this.setState({
      cropperOpen: false
    });
  },
  render () {
    return (

          <FileUpload handleFileChange={this.handleFileChange} />

            Click to Pick Avatar

        {this.state.cropperOpen &&
          <AvatarCropper
            onRequestHide={this.handleRequestHide}
            onCrop={this.handleCrop}
            image={this.state.img}
            width={400}
            height={400}
          />
        }

    );
  }
});

var FileUpload = React.createClass({

  handleFile: function(e) {
    var reader = new FileReader();
    var file = e.target.files[0];

    if (!file) return;

    reader.onload = function(img) {
      React.findDOMNode(this.refs.in).value = '';
      this.props.handleFileChange(img.target.result);
    }.bind(this);
    reader.readAsDataURL(file);
  },

  render: function() {
    return (
      <input ref="in" type="file" onChange={this.handleFile} />
    );
  }
});

React.render(<App />, document.getElementById("content"));
// React.render(<App />, document.getElementById("cropper"));
<commit_msg>restrict to only images.<commit_after>import React from "react";
import AvatarCropper from "../../lib";
import {
  Modal,
  Button
} from "react-bootstrap";

var App = React.createClass({
  getInitialState: function() {
    return {
      cropperOpen: false,
      img: null,
      croppedImg: "http://www.fillmurray.com/400/400"
    }
  },
  handleFileChange: function(dataURI) {
    this.setState({
      img: dataURI,
      croppedImg: this.state.croppedImg,
      cropperOpen: true
    });
  },
  handleCrop: function(dataURI) {
    this.setState({
      cropperOpen: false,
      img: null,
      croppedImg: dataURI
    });
  },
  handleRequestHide: function() {
    this.setState({
      cropperOpen: false
    });
  },
  render () {
    return (

          <FileUpload handleFileChange={this.handleFileChange} />

            Click to Pick Avatar

        {this.state.cropperOpen &&
          <AvatarCropper
            onRequestHide={this.handleRequestHide}
            onCrop={this.handleCrop}
            image={this.state.img}
            width={400}
            height={400}
          />
        }

    );
  }
});

var FileUpload = React.createClass({

  handleFile: function(e) {
    var reader = new FileReader();
    var file = e.target.files[0];

    if (!file) return;

    reader.onload = function(img) {
      React.findDOMNode(this.refs.in).value = '';
      this.props.handleFileChange(img.target.result);
    }.bind(this);
    reader.readAsDataURL(file);
  },

  render: function() {
    return (
      <input ref="in" type="file" accept="image/*" onChange={this.handleFile} />
    );
  }
});

React.render(<App />, document.getElementById("content"));
// React.render(<App />, document.getElementById("cropper"));
<|endoftext|>


<commit_before>var lang = {
    "There is no item to be added.": "لا يوجد منتج ليتم إضافته",
    "Check item first.": "إضغط على فحص أولاً",
    "Item added to list.": "تم إضافة المنتج",
    "there is no items.": "لا يوجد منتجات مضافه",
    "The list is empty, Please check items to list.": "قائمة المبيعات فارغة , من فضلك أضف المنتجات أولاً",
    "Please enter a valid serial first.": "من فضلك أدخل كود صحيح أولاً",
    "Item is not found.": "المنتج غير موجود",
    "Item is available.": "المنتج موجود",
    "Customer is available.": "العميل موجود",
    "Customer is not found.": "العميل غير موجود",
    "This field is required.": "الحقل مطلوب",
    "Serial can not be empty.": "يجب إدخال الكود",
    "Item already exists.": "المنتج موجود بالفعل",
    "Enter Model Serial": "أدخل كود الموديل",
    "Serial is valid.": "الكود صالح",
    "Model exists": "الموديل موجود ",
    "Model does not exist.": "الموديل غير موجود",
    "Quantity must be greater then zero.": "الكمية يجب ان تكون اكبر من الصفر",
    "Model already exist.": "الموديل موجود بالفعل",
    "Please select model.": "من فضلك أختر الموديل",
    "Please select period.": "من فضلك أختر الفترة",
    "Item already added to list.": "هذا المنتج مضاف مسبقا فى القائمة",
    " L.E.": " جنية",

};
<commit_msg>fixing translation<commit_after>var lang = {
    "There is no item to be added.": "لا يوجد منتج ليتم إضافته",
    "Check item first.": "إضغط على فحص أولاً",
    "Item added to list.": "تم إضافة المنتج",
    "there is no items.": "لا يوجد منتجات مضافه",
    "The list is empty, Please check items to list.": "قائمة المبيعات فارغة , من فضلك أضف المنتجات أولاً",
    "Please enter a valid serial first.": "من فضلك أدخل كود صحيح أولاً",
    "Item is not found.": "المنتج غير موجود",
    "Item is available.": "المنتج موجود",
    "Customer is available.": "العميل موجود",
    "Customer is not found.": "العميل غير موجود",
    "This field is required.": "الحقل مطلوب",
    "Serial can not be empty.": "يجب إدخال الكود",
    "Item already exists.": "المنتج موجود بالفعل",
    "Enter Model Serial": "أدخل كود الموديل",
    "Serial is valid.": "الكود صالح",
    "Model exists": "الموديل موجود ",
    "Model does not exist.": "الموديل غير موجود",
    "Quantity must be greater then zero.": "الكمية يجب ان تكون اكبر من الصفر",
    "Model already exist.": "الموديل موجود بالفعل",
    "Please select model.": "من فضلك أختر الموديل",
    "Please select period.": "من فضلك أختر الفترة",
    "Item already added to list.": "هذا المنتج مضاف مسبقا فى القائمة",
    "Item removed from list.": "تم حذف المنتج من القائمة",
    " L.E.": " جنية",

};
<|endoftext|>