<commit_before>define(['../../msdos/util.js'], function(dosUtil) {

  'use strict';

  function TrailerView(buffer, byteSource, byteLength) {
    this.dv = new DataView(buffer, byteSource, byteLength);
    this.bytes = new Uint8Array(buffer, byteSource, byteLength);
  }
  TrailerView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === TrailerView.signature;
    },
    get partNumber() {
      return this.dv.getUint16(4, true);
    },
    get centralDirFirstPart() {
      return this.dv.getUint16(6, true);
    },
    get partEntryCount() {
      return this.dv.getUint16(8, true);
    },
    get totalEntryCount() {
      return this.dv.getUint16(10, true);
    },
    get centralDirByteLength() {
      return this.dv.getUint32(12, true);
    },
    get centralDirFirstOffset() {
      return this.dv.getUint32(16, true);
    },
    get commentByteLength() {
      return this.dv.getUint16(20, true);
    },
  };
  TrailerView.signature = 'PK\x05\x06';
  TrailerView.byteLength = 22;

  function CentralRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  CentralRecordView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === CentralRecordView.signature;
    },
    get creationSystem() {
      var systemCode = this.dv.getUint8(5);
      switch(systemCode) {
        case 0: return 'fat'; // FAT / VFAT / FAT32: MS-DOS and OS/2
        case 1: return 'amiga';
        case 2: return 'openVMS';
        case 3: return 'unix';
        case 4: return 'vm/cms';
        case 5: return 'atariST';
        case 6: return 'hpfs'; // OS/2
        case 7: return 'mac';
        case 8: return 'z';
        case 9: return 'cp/m';
        case 10: return 'ntfs';
        case 11: return 'mvs';
        case 12: return 'vse';
        case 13: return 'acorn';
        case 14: return 'vfat';
        case 15: return 'mvsAlternate';
        case 16: return 'beOS';
        case 17: return 'tandem';
        case 18: return 'os/400';
        case 19: return 'osx'; // darwin
        default: return systemCode;
      }
    },
    get zipSpecificationVersion() {
      return this.dv.getUint8(4);
    },
    get requiredPKZipVersion() {
      return this.dv.getUint16(6, true) / 10;
    },
    get flags() {
      return this.dv.getUint16(8, true);
    },
    get isEncrypted() {
      return !!(this.flags & (1 << 0));
    },
    get usesCompressionOption1() {
      return !!(this.flags & (1 << 1));
    },
    get usesCompressionOption2() {
      return !!(this.flags & (1 << 2));
    },
    get hasDataDescriptor() {
      return !!(this.flags & (1 << 3));
    },
    get hasEnhancedDeflation() {
      return !!(this.flags & (1 << 4));
    },
    get hasCompressedPatchedData() {
      return !!(this.flags & (1 << 5));
    },
    get hasStrongEncryption() {
      return !!(this.flags & (1 << 6));
    },
    get hasUTF8Encoding() {
      return !!(this.flags & (1 << 11));
    },
    get hasMaskHeaderValues() {
      return !!(this.flags & (1 << 13));
    },
    get compressionMethod() {
      var methodCode = this.dv.getUint16(10, true);
      switch(methodCode) {
        case 0: return 'none';
        case 1: return 'shrunk';
        case 2: return 'factor1';
        case 3: return 'factor2';
        case 4: return 'factor3';
        case 5: return 'factor4';
        case 6: return 'imploded';
        case 8: return 'deflated';
        case 9: return 'enhancedDeflated';
        case 10: return 'dclImploded';
        case 12: return 'bzip2';
        case 14: return 'lzma';
        case 18: return 'terse';
        case 19: return 'lz77';
        case 98: return 'ppmd';
        default: return methodCode;
      }
    },
    get modifiedAt() {
      return dosUtil.getTimeAndDate(this.dv, 12);
    },
    get crc32() {
      return ('0000000' + this.dv.getUint32(16, true).toString(16).toUpperCase()).slice(-8);
    },
    get compressedByteLength32() {
      return this.dv.getUint32(20, true);
    },
    get uncompressedByteLength32() {
      return this.dv.getUint32(24, true);
    },
    get isZip64() {
      return this.compressedSize32 === 0xffffffff && this.uncompressedSize32 === 0xffffffff;
    },
    get pathByteLength() {
      return this.dv.getUint16(28, true);
    },
    get extraByteLength() {
      return this.dv.getUint16(30, true);
    },
    get commentByteLength() {
      return this.dv.getUint16(32, true);
    },
    get firstDiskNumber() {
      return this.dv.getUint16(34, true);
    },
    get internalAttributes() {
      return this.dv.getUint16(36, true);
    },
    get isApparentlyTextFile() {
      return !!(this.internalAttributes && (1 << 0));
    },
    get hasControlFieldRecordsBeforeLogicalRecords() {
      return !!(this.internalAttributes && (1 << 2));
    },
    get externalAttributes() {
      return this.dv.getUint32(38, true);
    },
    get localRecordOffset() {
      return this.dv.getUint32(42, true);
    },
    get pathPos() {
      return CentralRecordView.fixedByteLength;
    },
    get decode() {
      return this.hasUTF8Encoding ? utf_8.decode : latin_us.decode;
    },
    get path() {
      return this.decode(this.bytes, this.pathPos, this.pathByteLength);
    },
    get extraPos() {
      return this.pathPos + this.pathByteLength;
    },
    get commentPos() {
      return this.extraPos + this.extraByteLength;
    },
    get comment() {
      return this.decode(this.bytes, this.commentPos, this.commentByteLength);
    },
    get byteLength() {
      return this.pathPos + this.pathByteLength + this.extraByteLength + this.commentByteLength;
    },
  };
  CentralRecordView.signature = 'PK\x01\x02';
  CentralRecordView.fixedByteLength = 46;

  function LocalRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  LocalRecordView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === LocalRecordView.signature;
    },
    get version() {
      return this.dv.getUint16(4, true) / 10;
    },
    get flags() {
      return this.dv.getUint16(6, true) / 10;
    },
    get isEncrypted() {
      return !!(this.flags & (1 << 0));
    },
    get usesCompressionOption1() {
      return !!(this.flags & (1 << 1));
    },
    get usesCompressionOption2() {
      return !!(this.flags & (1 << 2));
    },
    get hasDataDescriptor() {
      return !!(this.flags & (1 << 3));
    },
    get hasEnhancedDeflation() {
      return !!(this.flags & (1 << 4));
    },
    get hasCompressedPatchedData() {
      return !!(this.flags & (1 << 5));
    },
    get hasStrongEncryption() {
      return !!(this.flags & (1 << 6));
    },
    get hasUTF8Encoding() {
      return !!(this.flags & (1 << 11));
    },
    get hasMaskHeaderValues() {
      return !!(this.flags & (1 << 13));
    },
    get compressionMethod() {
      var methodCode = this.dv.getUint16(8, true);
      switch(methodCode) {
        case 0: return 'none';
        case 1: return 'shrunk';
        case 2: return 'factor1';
        case 3: return 'factor2';
        case 4: return 'factor3';
        case 5: return 'factor4';
        case 6: return 'imploded';
        case 8: return 'deflated';
        case 9: return 'enhancedDeflated';
        case 10: return 'dclImploded';
        case 12: return 'bzip2';
        case 14: return 'lzma';
        case 18: return 'terse';
        case 19: return 'lz77';
        case 98: return 'ppmd';
        default: return methodCode;
      }
    },
    get modifiedAt() {
      return dosUtil.getTimeAndDate(this.dv, 0xA);
    },
    get crc32() {
      return ('0000000' + this.dv.getUint32(0xE, true).toString(16).toUpperCase()).slice(-8);
    },
    get compressedSize32() {
      return this.dv.getUint32(0x12, true);
    },
    get uncompressedSize32() {
      return this.dv.getUint32(0x16, true);
    },
    get isZip64() {
      return this.compressedSize32 === 0xffffffff && this.uncompressedSize32 === 0xffffffff;
    },
    get pathByteLength() {
      return this.dv.getInt16(0x1a, true);
    },
    get extraByteLength() {
      return this.dv.getInt16(0x1c, true);
    },
    get byteLength() {
      return LocalRecordView.byteLength + this.pathByteLength + this.extraByteLength + this.compressedByteLength32;
    },
  };
  LocalRecordView.byteLength = 0x1e;
  LocalRecordView.signature = 'PK\x03\x04';

  return {
    getStructView: function(segment) {
      switch (segment.getTypeParam('type')) {
        case 'trailer': return TrailerView;
        case 'central-record': return CentralRecordView;
        case 'local-record': return LocalRecordView;
        default: return null;
      }
    },
  };

});
<commit_msg>Fix method name<commit_after>define(['../../msdos/util.js'], function(dosUtil) {

  'use strict';

  function TrailerView(buffer, byteSource, byteLength) {
    this.dv = new DataView(buffer, byteSource, byteLength);
    this.bytes = new Uint8Array(buffer, byteSource, byteLength);
  }
  TrailerView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === TrailerView.signature;
    },
    get partNumber() {
      return this.dv.getUint16(4, true);
    },
    get centralDirFirstPart() {
      return this.dv.getUint16(6, true);
    },
    get partEntryCount() {
      return this.dv.getUint16(8, true);
    },
    get totalEntryCount() {
      return this.dv.getUint16(10, true);
    },
    get centralDirByteLength() {
      return this.dv.getUint32(12, true);
    },
    get centralDirFirstOffset() {
      return this.dv.getUint32(16, true);
    },
    get commentByteLength() {
      return this.dv.getUint16(20, true);
    },
  };
  TrailerView.signature = 'PK\x05\x06';
  TrailerView.byteLength = 22;

  function CentralRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  CentralRecordView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === CentralRecordView.signature;
    },
    get creationSystem() {
      var systemCode = this.dv.getUint8(5);
      switch(systemCode) {
        case 0: return 'fat'; // FAT / VFAT / FAT32: MS-DOS and OS/2
        case 1: return 'amiga';
        case 2: return 'openVMS';
        case 3: return 'unix';
        case 4: return 'vm/cms';
        case 5: return 'atariST';
        case 6: return 'hpfs'; // OS/2
        case 7: return 'mac';
        case 8: return 'z';
        case 9: return 'cp/m';
        case 10: return 'ntfs';
        case 11: return 'mvs';
        case 12: return 'vse';
        case 13: return 'acorn';
        case 14: return 'vfat';
        case 15: return 'mvsAlternate';
        case 16: return 'beOS';
        case 17: return 'tandem';
        case 18: return 'os/400';
        case 19: return 'osx'; // darwin
        default: return systemCode;
      }
    },
    get zipSpecificationVersion() {
      return this.dv.getUint8(4);
    },
    get requiredPKZipVersion() {
      return this.dv.getUint16(6, true) / 10;
    },
    get flags() {
      return this.dv.getUint16(8, true);
    },
    get isEncrypted() {
      return !!(this.flags & (1 << 0));
    },
    get usesCompressionOption1() {
      return !!(this.flags & (1 << 1));
    },
    get usesCompressionOption2() {
      return !!(this.flags & (1 << 2));
    },
    get hasDataDescriptor() {
      return !!(this.flags & (1 << 3));
    },
    get hasEnhancedDeflation() {
      return !!(this.flags & (1 << 4));
    },
    get hasCompressedPatchedData() {
      return !!(this.flags & (1 << 5));
    },
    get hasStrongEncryption() {
      return !!(this.flags & (1 << 6));
    },
    get hasUTF8Encoding() {
      return !!(this.flags & (1 << 11));
    },
    get hasMaskHeaderValues() {
      return !!(this.flags & (1 << 13));
    },
    get compressionMethod() {
      var methodCode = this.dv.getUint16(10, true);
      switch(methodCode) {
        case 0: return 'none';
        case 1: return 'shrunk';
        case 2: return 'factor1';
        case 3: return 'factor2';
        case 4: return 'factor3';
        case 5: return 'factor4';
        case 6: return 'imploded';
        case 8: return 'deflated';
        case 9: return 'enhancedDeflated';
        case 10: return 'dclImploded';
        case 12: return 'bzip2';
        case 14: return 'lzma';
        case 18: return 'terse';
        case 19: return 'lz77';
        case 98: return 'ppmd';
        default: return methodCode;
      }
    },
    get modifiedAt() {
      return dosUtil.getTimeAndDate(this.dv, 12);
    },
    get crc32() {
      return ('0000000' + this.dv.getUint32(16, true).toString(16).toUpperCase()).slice(-8);
    },
    get compressedByteLength32() {
      return this.dv.getUint32(20, true);
    },
    get uncompressedByteLength32() {
      return this.dv.getUint32(24, true);
    },
    get isZip64() {
      return this.compressedSize32 === 0xffffffff && this.uncompressedSize32 === 0xffffffff;
    },
    get pathByteLength() {
      return this.dv.getUint16(28, true);
    },
    get extraByteLength() {
      return this.dv.getUint16(30, true);
    },
    get commentByteLength() {
      return this.dv.getUint16(32, true);
    },
    get firstDiskNumber() {
      return this.dv.getUint16(34, true);
    },
    get internalAttributes() {
      return this.dv.getUint16(36, true);
    },
    get isApparentlyTextFile() {
      return !!(this.internalAttributes && (1 << 0));
    },
    get hasControlFieldRecordsBeforeLogicalRecords() {
      return !!(this.internalAttributes && (1 << 2));
    },
    get externalAttributes() {
      return this.dv.getUint32(38, true);
    },
    get localRecordOffset() {
      return this.dv.getUint32(42, true);
    },
    get pathPos() {
      return CentralRecordView.fixedByteLength;
    },
    get decode() {
      return this.hasUTF8Encoding ? utf_8.decode : latin_us.decode;
    },
    get path() {
      return this.decode(this.bytes, this.pathPos, this.pathByteLength);
    },
    get extraPos() {
      return this.pathPos + this.pathByteLength;
    },
    get commentPos() {
      return this.extraPos + this.extraByteLength;
    },
    get comment() {
      return this.decode(this.bytes, this.commentPos, this.commentByteLength);
    },
    get byteLength() {
      return this.pathPos + this.pathByteLength + this.extraByteLength + this.commentByteLength;
    },
  };
  CentralRecordView.signature = 'PK\x01\x02';
  CentralRecordView.fixedByteLength = 46;

  function LocalRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  LocalRecordView.prototype = {
    get hasValidSignature() {
      return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === LocalRecordView.signature;
    },
    get version() {
      return this.dv.getUint16(4, true) / 10;
    },
    get flags() {
      return this.dv.getUint16(6, true) / 10;
    },
    get isEncrypted() {
      return !!(this.flags & (1 << 0));
    },
    get usesCompressionOption1() {
      return !!(this.flags & (1 << 1));
    },
    get usesCompressionOption2() {
      return !!(this.flags & (1 << 2));
    },
    get hasDataDescriptor() {
      return !!(this.flags & (1 << 3));
    },
    get hasEnhancedDeflation() {
      return !!(this.flags & (1 << 4));
    },
    get hasCompressedPatchedData() {
      return !!(this.flags & (1 << 5));
    },
    get hasStrongEncryption() {
      return !!(this.flags & (1 << 6));
    },
    get hasUTF8Encoding() {
      return !!(this.flags & (1 << 11));
    },
    get hasMaskHeaderValues() {
      return !!(this.flags & (1 << 13));
    },
    get compressionMethod() {
      var methodCode = this.dv.getUint16(8, true);
      switch(methodCode) {
        case 0: return 'none';
        case 1: return 'shrunk';
        case 2: return 'factor1';
        case 3: return 'factor2';
        case 4: return 'factor3';
        case 5: return 'factor4';
        case 6: return 'imploded';
        case 8: return 'deflated';
        case 9: return 'enhancedDeflated';
        case 10: return 'dclImploded';
        case 12: return 'bzip2';
        case 14: return 'lzma';
        case 18: return 'terse';
        case 19: return 'lz77';
        case 98: return 'ppmd';
        default: return methodCode;
      }
    },
    get modifiedAt() {
      return dosUtil.getTimeAndDate(this.dv, 0xA);
    },
    get crc32() {
      return ('0000000' + this.dv.getUint32(0xE, true).toString(16).toUpperCase()).slice(-8);
    },
    get compressedSize32() {
      return this.dv.getUint32(0x12, true);
    },
    get uncompressedSize32() {
      return this.dv.getUint32(0x16, true);
    },
    get isZip64() {
      return this.compressedSize32 === 0xffffffff && this.uncompressedSize32 === 0xffffffff;
    },
    get pathByteLength() {
      return this.dv.getInt16(0x1a, true);
    },
    get extraByteLength() {
      return this.dv.getInt16(0x1c, true);
    },
    get byteLength() {
      return LocalRecordView.byteLength + this.pathByteLength + this.extraByteLength + this.compressedByteLength32;
    },
  };
  LocalRecordView.byteLength = 0x1e;
  LocalRecordView.signature = 'PK\x03\x04';

  return {
    getStructView: function(segment) {
      switch (segment.getTypeParameter('type')) {
        case 'trailer': return TrailerView;
        case 'central-record': return CentralRecordView;
        case 'local-record': return LocalRecordView;
        default: return null;
      }
    },
  };

});
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// NotebookList
//============================================================================

var IPython = (function (IPython) {

    var ClusterList = function (selector) {
        this.selector = selector;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.style();
            this.bind_events();
        }
    };

    ClusterList.prototype.style = function () {
        $('#cluster_toolbar').addClass('list_toolbar');
        $('#cluster_list_info').addClass('toolbar_info');
        $('#cluster_buttons').addClass('toolbar_buttons');
        $('div#cluster_header').addClass('list_header ui-widget ui-widget-header ui-helper-clearfix');
        $('div#cluster_header').children().eq(0).addClass('profile_col');
        $('div#cluster_header').children().eq(1).addClass('action_col');
        $('div#cluster_header').children().eq(2).addClass('engines_col');
        $('div#cluster_header').children().eq(3).addClass('status_col');
        $('#refresh_cluster_list').button({
            icons : {primary: 'ui-icon-arrowrefresh-1-s'},
            text : false
        });
    };

    ClusterList.prototype.bind_events = function () {
        var that = this;
        $('#refresh_cluster_list').click(function () {
            that.load_list();
        });
    };

    ClusterList.prototype.load_list = function () {
        var settings = {
            processData : false,
            cache : false,
            type : "GET",
            dataType : "json",
            success : $.proxy(this.load_list_success, this)
        };
        var url = $('body').data('baseProjectUrl') + 'clusters';
        $.ajax(url, settings);
    };

    ClusterList.prototype.clear_list = function () {
        this.element.children('.list_item').remove();
    }

    ClusterList.prototype.load_list_success = function (data, status, xhr) {
        this.clear_list();
        var len = data.length;
        for (var i=0; i<len; i++) {
            var item_div = $('<div/>');
            var item = new ClusterItem(item_div);
            item.update_state(data[i]);
            item_div.data('item', item);
            this.element.append(item_div);
        };
    };

    var ClusterItem = function (element) {
        this.element = $(element);
        this.data = null;
        this.style();
    };

    ClusterItem.prototype.style = function () {
        this.element.addClass('list_item ui-widget ui-widget-content ui-helper-clearfix');
        this.element.css('border-top-style','none');
    }

    ClusterItem.prototype.update_state = function (data) {
        this.data = data;
        if (data.status === 'running') {
            this.state_running();
        } else if (data.status === 'stopped') {
            this.state_stopped();
        };

    }

    ClusterItem.prototype.state_stopped = function () {
        var that = this;
        this.element.empty();
        var profile_col = $('<span/>').addClass('profile_col').text(this.data.profile);
        var status_col = $('<span/>').addClass('status_col').html('stopped');
        var engines_col = $('<span/>').addClass('engines_col');
        var input = $('<input/>').attr('type','number').
                attr('size',3).addClass('engine_num_input');
        engines_col.append(input);
        var action_col = $('<span/>').addClass('action_col');
        var start_button = $('<button>Start</button>').button();
        action_col.append(start_button);
        this.element.append(profile_col).
            append(action_col).
            append(engines_col).
            append(status_col);
        start_button.click(function (e) {
            var n = that.element.find('.engine_num_input').val();
            if (!/^\d+$/.test(n) && n.length>0) {
                status_col.html('invalid engine #');
            } else {
                var settings = {
                    cache : false,
                    data : {n:n},
                    type : "POST",
                    dataType : "json",
                    success : function (data, status, xhr) {
                        that.update_state(data);
                    },
                    error : function (data, status, xhr) {
                        status_col.html("error starting cluster")
                    }
                };
                status_col.html('starting');
                var url = $('body').data('baseProjectUrl') + 'clusters/' + that.data.profile + '/start';
                $.ajax(url, settings);
            };
        });
    };

    ClusterItem.prototype.state_running = function () {
        this.element.empty();
        var that = this;
        var profile_col = $('<span/>').addClass('profile_col').text(this.data.profile);
        var status_col = $('<span/>').addClass('status_col').html('running');
        var engines_col = $('<span/>').addClass('engines_col').html(this.data.n);
        var action_col = $('<span/>').addClass('action_col');
        var stop_button = $('<button>Stop</button>').button();
        action_col.append(stop_button);
        this.element.append(profile_col).
            append(action_col).
            append(engines_col).
            append(status_col);
        stop_button.click(function (e) {
            var settings = {
                cache : false,
                type : "POST",
                dataType : "json",
                success : function (data, status, xhr) {
                    that.update_state(data);
                },
                error : function (data, status, xhr) {
                    console.log('error',data);
                    status_col.html("error stopping cluster")
                }
            };
            status_col.html('stopping')
            var url = $('body').data('baseProjectUrl') + 'clusters/' + that.data.profile + '/stop';
            $.ajax(url, settings);
        });
    };

    IPython.ClusterList = ClusterList;
    IPython.ClusterItem = ClusterItem;

    return IPython;

}(IPython));

<commit_msg>min and default for engine number<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// NotebookList
//============================================================================

var IPython = (function (IPython) {

    var ClusterList = function (selector) {
        this.selector = selector;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.style();
            this.bind_events();
        }
    };

    ClusterList.prototype.style = function () {
        $('#cluster_toolbar').addClass('list_toolbar');
        $('#cluster_list_info').addClass('toolbar_info');
        $('#cluster_buttons').addClass('toolbar_buttons');
        $('div#cluster_header').addClass('list_header ui-widget ui-widget-header ui-helper-clearfix');
        $('div#cluster_header').children().eq(0).addClass('profile_col');
        $('div#cluster_header').children().eq(1).addClass('action_col');
        $('div#cluster_header').children().eq(2).addClass('engines_col');
        $('div#cluster_header').children().eq(3).addClass('status_col');
        $('#refresh_cluster_list').button({
            icons : {primary: 'ui-icon-arrowrefresh-1-s'},
            text : false
        });
    };

    ClusterList.prototype.bind_events = function () {
        var that = this;
        $('#refresh_cluster_list').click(function () {
            that.load_list();
        });
    };

    ClusterList.prototype.load_list = function () {
        var settings = {
            processData : false,
            cache : false,
            type : "GET",
            dataType : "json",
            success : $.proxy(this.load_list_success, this)
        };
        var url = $('body').data('baseProjectUrl') + 'clusters';
        $.ajax(url, settings);
    };

    ClusterList.prototype.clear_list = function () {
        this.element.children('.list_item').remove();
    }

    ClusterList.prototype.load_list_success = function (data, status, xhr) {
        this.clear_list();
        var len = data.length;
        for (var i=0; i<len; i++) {
            var item_div = $('<div/>');
            var item = new ClusterItem(item_div);
            item.update_state(data[i]);
            item_div.data('item', item);
            this.element.append(item_div);
        };
    };

    var ClusterItem = function (element) {
        this.element = $(element);
        this.data = null;
        this.style();
    };

    ClusterItem.prototype.style = function () {
        this.element.addClass('list_item ui-widget ui-widget-content ui-helper-clearfix');
        this.element.css('border-top-style','none');
    }

    ClusterItem.prototype.update_state = function (data) {
        this.data = data;
        if (data.status === 'running') {
            this.state_running();
        } else if (data.status === 'stopped') {
            this.state_stopped();
        };

    }

    ClusterItem.prototype.state_stopped = function () {
        var that = this;
        this.element.empty();
        var profile_col = $('<span/>').addClass('profile_col').text(this.data.profile);
        var status_col = $('<span/>').addClass('status_col').html('stopped');
        var engines_col = $('<span/>').addClass('engines_col');
        var input = $('<input/>').attr('type','number')
                .attr('min',1)
                .attr('value',2)
                .attr('size',3)
                .addClass('engine_num_input');
        engines_col.append(input);
        var action_col = $('<span/>').addClass('action_col');
        var start_button = $('<button>Start</button>').button();
        action_col.append(start_button);
        this.element.append(profile_col).
            append(action_col).
            append(engines_col).
            append(status_col);
        start_button.click(function (e) {
            var n = that.element.find('.engine_num_input').val();
            if (!/^\d+$/.test(n) && n.length>0) {
                status_col.html('invalid engine #');
            } else {
                var settings = {
                    cache : false,
                    data : {n:n},
                    type : "POST",
                    dataType : "json",
                    success : function (data, status, xhr) {
                        that.update_state(data);
                    },
                    error : function (data, status, xhr) {
                        status_col.html("error starting cluster")
                    }
                };
                status_col.html('starting');
                var url = $('body').data('baseProjectUrl') + 'clusters/' + that.data.profile + '/start';
                $.ajax(url, settings);
            };
        });
    };

    ClusterItem.prototype.state_running = function () {
        this.element.empty();
        var that = this;
        var profile_col = $('<span/>').addClass('profile_col').text(this.data.profile);
        var status_col = $('<span/>').addClass('status_col').html('running');
        var engines_col = $('<span/>').addClass('engines_col').html(this.data.n);
        var action_col = $('<span/>').addClass('action_col');
        var stop_button = $('<button>Stop</button>').button();
        action_col.append(stop_button);
        this.element.append(profile_col).
            append(action_col).
            append(engines_col).
            append(status_col);
        stop_button.click(function (e) {
            var settings = {
                cache : false,
                type : "POST",
                dataType : "json",
                success : function (data, status, xhr) {
                    that.update_state(data);
                },
                error : function (data, status, xhr) {
                    console.log('error',data);
                    status_col.html("error stopping cluster")
                }
            };
            status_col.html('stopping')
            var url = $('body').data('baseProjectUrl') + 'clusters/' + that.data.profile + '/stop';
            $.ajax(url, settings);
        });
    };

    IPython.ClusterList = ClusterList;
    IPython.ClusterItem = ClusterItem;

    return IPython;

}(IPython));

<|endoftext|>


<commit_before>const AWS = require('aws-sdk');
const moment = require('moment');
const BlueBirdPromise = require('bluebird');
const __ = require('lodash');
const base64 = require('base-64');

AWS.config.setPromisesDependency(BlueBirdPromise);

class AutoScalingClient {

  constructor(accessKey = '', secretKey = '', region = 'us-west-2') {

    this._accessKey = accessKey;
    this._secretKey = secretKey;
    this._region = region;
  }

  get _awsAutoScalingClient() {

    if(!this._internalAutoScalingClient) {
      let params = {
        accessKeyId: this._accessKey,
        secretAccessKey: this._secretKey,
        apiVersion: '2011-01-01',
        region: this._region
      };
      this._internalAutoScalingClient = new AWS.AutoScaling(params);
    }

    return this._internalAutoScalingClient;
  }

  //TODO: Create a createOrUpdate method for AutoScalingGroup and LaunchConfiguration

  /**
   *
   * @param launchConfigurationConfig
   * {
   *     name: <Name of the launch configuration>,
   *     baseImageId: <ImageId that will be the base AMI for the EC2 instances>,
   *     securityGroupId: <id of the security group to be applied to the EC2 instances>,
   *     instanceType: <Instance type that will be used for the EC2 instances,
   *     sshKeyName: (Optional) SSH Key associated with the EC2 instances
   *     ecsClusterName: (Optional) <This is the ECS cluster that will be associated with the launch configuration>
   *   }
   * @return {Promise.<TResult>|*}
   */
  createLaunchConfigurationFromConfig(launchConfigurationConfig) {
    return this.getLaunchConfigurationArn(launchConfigurationConfig.name).then(launchConfigurationArn => {
      if(!launchConfigurationArn) {
        return this._createLaunchConfiguration(launchConfigurationConfig.name,
          launchConfigurationConfig.baseImageId,
          launchConfigurationConfig.securityGroupId,
          launchConfigurationConfig.instanceType,
          launchConfigurationConfig.sshKeyName,
          launchConfigurationConfig.ecsClusterName);
      } else {
        this.logMessage(`LaunchConfiguration already exists. No Action taken. [LaunchConfigurationName: ${launchConfigurationConfig.name}] [LaunchConfigurationArn: ${launchConfigurationArn}]`);
      }
    });
  }

  /**
   * Creates a Launch Configuration
   * @param name This is the name of the launch configuration.
   * @param imageId This is the AMI Id that will be the base of the Launch Configuration.
   * @param instanceType This is the instance type (size) that will be launched.
   * @param sshKeyName (Optional) This is the sshKeyName associated with the box.
   * @param ecsClusterName (Optional)
   * @return {Promise<D>}
   */
  _createLaunchConfiguration(name, imageId, securityGroupId, instanceType, sshKeyName = null, ecsClusterName = null) {

    let params = {
      LaunchConfigurationName: name, /* required */
      AssociatePublicIpAddress: true,
      BlockDeviceMappings: [],
      EbsOptimized: false,
      IamInstanceProfile: 'ecsInstanceRole',
      ImageId: imageId,
      InstanceMonitoring: {
        Enabled: false
      },
      InstanceType: instanceType,
      PlacementTenancy: 'default',
      SecurityGroups: [securityGroupId]
    };

    if(sshKeyName) {
      params.KeyName = sshKeyName;
    }

    if(ecsClusterName) {
      let ec2StartupScript = `#!/bin/bash
echo ECS_CLUSTER=${ecsClusterName} >> /etc/ecs/ecs.config`;

      params.UserData = base64.encode(ec2StartupScript);
    }

    this.logMessage(`Creating Launch Configuration. [Name: ${name}] [Params: ${JSON.stringify(params)}]`);
    let createLaunchConfigurationPromise = this._awsAutoScalingClient.createLaunchConfiguration(params).promise();

    return createLaunchConfigurationPromise;
  }

  /**
   *
   * @param environment
   * @param name
   * @param launchConfigurationName
   * @param minSize
   * @param maxSize
   * @param desiredCapacity
   * @param targetGroupArns
   * @param vpcSubnets
   * @return {Promise.<TResult>|*}
   */
  createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets) {
    return this.getAutoScalingGroupArn(name).then(autoScalingGroupArn => {
      if(!autoScalingGroupArn) {
        return this._createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets);
      } else {
        this.logMessage(`AutoScalingGroup already exists. No Action taken. [AutoScalingGroupName: ${name}] [AutoScalingGroupArn: ${autoScalingGroupArn}]`);
      }
    });
  }

  /**
   *
   * @param environment
   * @param name (Required)
   * @param launchConfigurationName
   * @param minSize
   * @param maxSize
   * @param desiredCapacity
   * @param targetGroupArns This is an array of TargetGroupArns
   * @param vpcSubnets This is a CSV of subnets where the instances will be launched into
   * @return {Promise<D>}
   */
  _createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets) {

    let formattedTargetGroupArns = targetGroupArns;
    if(!__.isArray(formattedTargetGroupArns)) {
      formattedTargetGroupArns = [targetGroupArns];
    }

    let params = {
      AutoScalingGroupName: name, /* required */
      MaxSize: maxSize, /* required */
      MinSize: minSize, /* required */
      DefaultCooldown: 300,
      DesiredCapacity: desiredCapacity,
      HealthCheckGracePeriod: 0,
      LaunchConfigurationName: launchConfigurationName,
      NewInstancesProtectedFromScaleIn: false,
      Tags: [
        {
          Key: 'Name', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: `${environment} - ECS Instance`
        },
        {
          Key: 'Environment', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: environment
        },
        {
          Key: 'Created', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: moment().format()
        }
      ],
      TargetGroupARNs: formattedTargetGroupArns,
      VPCZoneIdentifier: vpcSubnets
    };

    let createAutoScalingGroupPromise = this._awsAutoScalingClient.createAutoScalingGroup(params).promise();

    return createAutoScalingGroupPromise;
  }

  /**
   *
   * @param launchConfigurationName
   * @return {Promise.<TResult>}
   */
  getLaunchConfigurationArn(launchConfigurationName) {
    let params = {
      LaunchConfigurationNames: [launchConfigurationName]
    };

    let describeLaunchConfigurationPromise = this._awsAutoScalingClient.describeLaunchConfigurations(params).promise();

    return describeLaunchConfigurationPromise.then(result => {
      if(result && result.LaunchConfigurations && result.LaunchConfigurations.length > 0) {
        return result.LaunchConfigurations[0].LaunchConfigurationARN;
      } else {
        return '';
      }
    });

  }

  getAutoScalingGroupArn(autoScalingGroupName) {
    let params = {
      AutoScalingGroupNames: [autoScalingGroupName]
    };

    let describeAutoScalingGroupsPromise = this._awsAutoScalingClient.describeAutoScalingGroups(params).promise();

    return describeAutoScalingGroupsPromise.then(result => {
      if(result && result.AutoScalingGroups && result.AutoScalingGroups.length > 0) {
        return result.AutoScalingGroups[0].AutoScalingGroupARN;
      } else {
        return '';
      }
    });
  }

  /**
   * Logs messages
   * @param msg
   */
  logMessage(msg) {
    console.log(msg);
  }
}

module.exports = AutoScalingClient;
<commit_msg>Fixing newline formatting issue<commit_after>const AWS = require('aws-sdk');
const moment = require('moment');
const BlueBirdPromise = require('bluebird');
const __ = require('lodash');
const base64 = require('base-64');

AWS.config.setPromisesDependency(BlueBirdPromise);

class AutoScalingClient {

  constructor(accessKey = '', secretKey = '', region = 'us-west-2') {

    this._accessKey = accessKey;
    this._secretKey = secretKey;
    this._region = region;
  }

  get _awsAutoScalingClient() {

    if(!this._internalAutoScalingClient) {
      let params = {
        accessKeyId: this._accessKey,
        secretAccessKey: this._secretKey,
        apiVersion: '2011-01-01',
        region: this._region
      };
      this._internalAutoScalingClient = new AWS.AutoScaling(params);
    }

    return this._internalAutoScalingClient;
  }

  //TODO: Create a createOrUpdate method for AutoScalingGroup and LaunchConfiguration

  /**
   *
   * @param launchConfigurationConfig
   * {
   *     name: <Name of the launch configuration>,
   *     baseImageId: <ImageId that will be the base AMI for the EC2 instances>,
   *     securityGroupId: <id of the security group to be applied to the EC2 instances>,
   *     instanceType: <Instance type that will be used for the EC2 instances,
   *     sshKeyName: (Optional) SSH Key associated with the EC2 instances
   *     ecsClusterName: (Optional) <This is the ECS cluster that will be associated with the launch configuration>
   *   }
   * @return {Promise.<TResult>|*}
   */
  createLaunchConfigurationFromConfig(launchConfigurationConfig) {
    return this.getLaunchConfigurationArn(launchConfigurationConfig.name).then(launchConfigurationArn => {
      if(!launchConfigurationArn) {
        return this._createLaunchConfiguration(launchConfigurationConfig.name,
          launchConfigurationConfig.baseImageId,
          launchConfigurationConfig.securityGroupId,
          launchConfigurationConfig.instanceType,
          launchConfigurationConfig.sshKeyName,
          launchConfigurationConfig.ecsClusterName);
      } else {
        this.logMessage(`LaunchConfiguration already exists. No Action taken. [LaunchConfigurationName: ${launchConfigurationConfig.name}] [LaunchConfigurationArn: ${launchConfigurationArn}]`);
      }
    });
  }

  /**
   * Creates a Launch Configuration
   * @param name This is the name of the launch configuration.
   * @param imageId This is the AMI Id that will be the base of the Launch Configuration.
   * @param instanceType This is the instance type (size) that will be launched.
   * @param sshKeyName (Optional) This is the sshKeyName associated with the box.
   * @param ecsClusterName (Optional)
   * @return {Promise<D>}
   */
  _createLaunchConfiguration(name, imageId, securityGroupId, instanceType, sshKeyName = null, ecsClusterName = null) {

    let params = {
      LaunchConfigurationName: name, /* required */
      AssociatePublicIpAddress: true,
      BlockDeviceMappings: [],
      EbsOptimized: false,
      IamInstanceProfile: 'ecsInstanceRole',
      ImageId: imageId,
      InstanceMonitoring: {
        Enabled: false
      },
      InstanceType: instanceType,
      PlacementTenancy: 'default',
      SecurityGroups: [securityGroupId]
    };

    if(sshKeyName) {
      params.KeyName = sshKeyName;
    }

    if(ecsClusterName) {
      let ec2StartupScript = `#!/bin/bash\necho ECS_CLUSTER=${ecsClusterName} >> /etc/ecs/ecs.config`;

      params.UserData = base64.encode(ec2StartupScript);
    }

    this.logMessage(`Creating Launch Configuration. [Name: ${name}] [Params: ${JSON.stringify(params)}]`);
    let createLaunchConfigurationPromise = this._awsAutoScalingClient.createLaunchConfiguration(params).promise();

    return createLaunchConfigurationPromise;
  }

  /**
   *
   * @param environment
   * @param name
   * @param launchConfigurationName
   * @param minSize
   * @param maxSize
   * @param desiredCapacity
   * @param targetGroupArns
   * @param vpcSubnets
   * @return {Promise.<TResult>|*}
   */
  createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets) {
    return this.getAutoScalingGroupArn(name).then(autoScalingGroupArn => {
      if(!autoScalingGroupArn) {
        return this._createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets);
      } else {
        this.logMessage(`AutoScalingGroup already exists. No Action taken. [AutoScalingGroupName: ${name}] [AutoScalingGroupArn: ${autoScalingGroupArn}]`);
      }
    });
  }

  /**
   *
   * @param environment
   * @param name (Required)
   * @param launchConfigurationName
   * @param minSize
   * @param maxSize
   * @param desiredCapacity
   * @param targetGroupArns This is an array of TargetGroupArns
   * @param vpcSubnets This is a CSV of subnets where the instances will be launched into
   * @return {Promise<D>}
   */
  _createAutoScalingGroup(environment, name, launchConfigurationName, minSize, maxSize, desiredCapacity, targetGroupArns, vpcSubnets) {

    let formattedTargetGroupArns = targetGroupArns;
    if(!__.isArray(formattedTargetGroupArns)) {
      formattedTargetGroupArns = [targetGroupArns];
    }

    let params = {
      AutoScalingGroupName: name, /* required */
      MaxSize: maxSize, /* required */
      MinSize: minSize, /* required */
      DefaultCooldown: 300,
      DesiredCapacity: desiredCapacity,
      HealthCheckGracePeriod: 0,
      LaunchConfigurationName: launchConfigurationName,
      NewInstancesProtectedFromScaleIn: false,
      Tags: [
        {
          Key: 'Name', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: `${environment} - ECS Instance`
        },
        {
          Key: 'Environment', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: environment
        },
        {
          Key: 'Created', /* required */
          PropagateAtLaunch: true,
          ResourceType: 'auto-scaling-group',
          Value: moment().format()
        }
      ],
      TargetGroupARNs: formattedTargetGroupArns,
      VPCZoneIdentifier: vpcSubnets
    };

    let createAutoScalingGroupPromise = this._awsAutoScalingClient.createAutoScalingGroup(params).promise();

    return createAutoScalingGroupPromise;
  }

  /**
   *
   * @param launchConfigurationName
   * @return {Promise.<TResult>}
   */
  getLaunchConfigurationArn(launchConfigurationName) {
    let params = {
      LaunchConfigurationNames: [launchConfigurationName]
    };

    let describeLaunchConfigurationPromise = this._awsAutoScalingClient.describeLaunchConfigurations(params).promise();

    return describeLaunchConfigurationPromise.then(result => {
      if(result && result.LaunchConfigurations && result.LaunchConfigurations.length > 0) {
        return result.LaunchConfigurations[0].LaunchConfigurationARN;
      } else {
        return '';
      }
    });

  }

  getAutoScalingGroupArn(autoScalingGroupName) {
    let params = {
      AutoScalingGroupNames: [autoScalingGroupName]
    };

    let describeAutoScalingGroupsPromise = this._awsAutoScalingClient.describeAutoScalingGroups(params).promise();

    return describeAutoScalingGroupsPromise.then(result => {
      if(result && result.AutoScalingGroups && result.AutoScalingGroups.length > 0) {
        return result.AutoScalingGroups[0].AutoScalingGroupARN;
      } else {
        return '';
      }
    });
  }

  /**
   * Logs messages
   * @param msg
   */
  logMessage(msg) {
    console.log(msg);
  }
}

module.exports = AutoScalingClient;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { browserHistory } from 'react-router'
import update from 'react-addons-update'
import _pickBy from 'lodash/pickBy'

import API from './api'
import Button from './button'
import TextField from './textField'
import SelectField from './selectField'
import Modal from './modal'

const STATUS = [
  {id: 'Desaparecido', label: 'Desaparecido'},
  {id: 'Encontrado', label: 'Encontrado'},
  {id: 'Fallecido', label: 'Fallecido'}
]

const GENDER = [
  {id: 'm', label: 'Hombre'},
  {id: 'f', label: 'Mujer'}
]

export default class People extends Component {
  constructor () {
    super()
    this.data = {
      people: [],
      filters: {
        nombre: '',
        sexo: '',
        edad: '',
        estado: ''
      },
      modalOpen: false,
      reqInProg: false,
      name: '',
      gender: '',
      age: '',
      status: '',
      notes: '',
      id: ''
    }
    this.state = Object.assign({}, this.data)
  }

  componentDidMount () {
    this.loadData()
  }

  onChangeFiltersName (e) {
    this.setState({filters: update(this.state.filters, {nombre: {$set: e.target.value}})})
  }

  onChangeFiltersGender (e) {
    this.setState({filters: update(this.state.filters, {sexo: {$set: e.target.value}})})
  }

  onChangeFiltersAge (e) {
    this.setState({filters: update(this.state.filters, {edad: {$set: e.target.value}})})
  }

  onChangeFiltersStatus (e) {
    this.setState({filters: update(this.state.filters, {estado: {$set: e.target.value}})})
  }

  onChangeName (e) {
    this.setState({name: e.target.value})
  }

  onChangeAge (e) {
    this.setState({age: e.target.value})
  }

  onChangeGender (e) {
    this.setState({gender: e.target.value})
  }

  onChangeStatus (e) {
    this.setState({status: e.target.value})
  }

  onChangeNotes (e) {
    this.setState({notes: e.target.value})
  }

  onCleanFilters () {
    this.setState({filters: this.data.filters}, this.onFilter)
  }

  toggleModal () {
    this.setState({modalOpen: !this.state.modalOpen})
  }

  onFilter () {
    browserHistory.push('/personas')
    this.loadData()
  }

  resetState () {
    this.setState({
      id: '',
      name: '',
      age: '',
      gender: '',
      status: '',
      notes: ''
    })
  }

  setPerson (person) {
    this.setState({
      name: person.nombre,
      age: person.edad,
      gender: person.sexo,
      status: person.estado,
      notes: person.notas,
      id: person.id
    }, this.toggleModal)
  }

  onSubmit (id = '') {
    let { name, age, gender, status, notes, people } = this.state
    let data = {
      nombre: name,
      edad: age,
      sexo: gender,
      estado: status,
      notas: notes
    }
    if (id) {
      API.People.Update(id, data)
        .then(response => {
          let updatedPerson = response.persona
          people = people.map(person => person.id === updatedPerson.id ? updatedPerson : person)
          this.setState({ people }, this.resetState)
        })
    } else {
      API.People.SendNewds(data)
        .then(response => {
          people.push(response.persona)
          this.setState({ people })
        })
    }
    this.toggleModal()
  }

  // Get clients
  loadData () {
    let { filters, currentPage, sort } = this.state
    let _filters = _pickBy(filters, filter => filter.length > 0)
    // let page = currentPage > 1 ? {page: currentPage} : {}
    let params = Object.assign({}, _filters)
    this.setState({reqInProg: true})
    API.People.GetList(params)
      .then(response => {
        this.setState({people: response.personas, reqInProg: false})
      })
  }

  renderNewButton () {
    return (

        <Button
          className='is-pulled-right'
          buttonStyle='primary'
          onClick={this.toggleModal.bind(this)}
          icon='plus'
        >
          Nuevo Reporte de Persona
        </Button>

    )
  }

  renderFilters () {
    return (

          <TextField
            onChange={this.onChangeFiltersName.bind(this)}
            placeholder='Nombre'
            value={this.state.filters.nombre}
            onEnter={this.onFilter.bind(this)}
          />

          <SelectField
            options={GENDER}
            onChange={this.onChangeFiltersGender.bind(this)}
            placeholder='Sexo'
            value={this.state.filters.sexo}
          />

          <TextField
            onChange={this.onChangeFiltersAge.bind(this)}
            placeholder='Edad'
            value={this.state.filters.edad}
            onEnter={this.onFilter.bind(this)}
          />

          <SelectField
            onChange={this.onChangeFiltersStatus.bind(this)}
            placeholder='Estado'
            value={this.state.filters.estado}
            options={STATUS}
          />

              <Button
                className='is-fullwidth'
                onClick={this.onCleanFilters.bind(this)}
                icon='close-circle-outline'
              >Limpiar</Button>

              <Button
                className='is-fullwidth'
                buttonStyle='info is-outlined'
                onClick={this.onFilter.bind(this)}
                icon='magnify'
              >Filtrar</Button>

    )
  }

  renderTable () {
    let { people, reqInProg } = this.state
    if (reqInProg) return
Cargando...

    let table =
No hay resultados...

    if (people.length > 0) {
      let peopleList = people.map(person => {
        let gender = 'Otro / no especificado'
        if (person.sexo === 'm') gender = 'Hombre'
        if (person.sexo === 'f') gender = 'Mujer'
        return (
          <tr
            key={`people-${person.id}`}
            onClick={this.setPerson.bind(this, person)}
          >
            {person.nombre}
            {person.edad}
            {gender}
            {person.estado}
            {person.notas}

        )
      })
      table = (

                Nombre
                Edad
                Sexo
                Estado
                Notas

              {peopleList}

      )
    }
    return table
  }

  renderModal () {
    return (
      <Modal
        title='Nuevo Reporte de Persona'
        isActive={this.state.modalOpen}
        toggleModal={this.toggleModal.bind(this)}
        onSubmit={this.onSubmit.bind(this, this.state.id)}
      >

              <TextField
                label='Nombre'
                value={this.state.name}
                onChange={this.onChangeName.bind(this)}
              />

              <TextField
                label='Edad'
                type='number'
                value={this.state.age}
                onChange={this.onChangeAge.bind(this)}
              />

              <SelectField
                placeholder='Sexo'
                options={GENDER}
                label='Sexo'
                value={this.state.gender}
                onChange={this.onChangeGender.bind(this)}
              />

              <SelectField
                placeholder='Estado'
                options={STATUS}
                label='Estado'
                value={this.state.status}
                onChange={this.onChangeStatus.bind(this)}
              />

              <TextField
                label='Notas'
                value={this.state.notes}
                onChange={this.onChangeNotes.bind(this)}
              />

      </Modal>
    )
  }

  render () {
    return (

        {this.renderNewButton()}
        {this.renderFilters()}
        {this.renderTable()}
        {this.renderModal()}

    )
  }
}
<commit_msg>Add default para crear personas<commit_after>import React, { Component } from 'react'
import { browserHistory } from 'react-router'
import update from 'react-addons-update'
import _pickBy from 'lodash/pickBy'

import API from './api'
import Button from './button'
import TextField from './textField'
import SelectField from './selectField'
import Modal from './modal'

const STATUS = [
  {id: 'Desaparecido', label: 'Desaparecido'},
  {id: 'Encontrado', label: 'Encontrado'},
  {id: 'Fallecido', label: 'Fallecido'}
]

const GENDER = [
  {id: '', label: 'Otro / No especificado'},
  {id: 'm', label: 'Hombre'},
  {id: 'f', label: 'Mujer'}
]

export default class People extends Component {
  constructor () {
    super()
    this.data = {
      people: [],
      filters: {
        nombre: '',
        sexo: '',
        edad: '',
        estado: ''
      },
      modalOpen: false,
      reqInProg: false,
      name: '',
      gender: '',
      age: '',
      status: 'Desaparecido',
      notes: '',
      id: ''
    }
    this.state = Object.assign({}, this.data)
  }

  componentDidMount () {
    this.loadData()
  }

  onChangeFiltersName (e) {
    this.setState({filters: update(this.state.filters, {nombre: {$set: e.target.value}})})
  }

  onChangeFiltersGender (e) {
    this.setState({filters: update(this.state.filters, {sexo: {$set: e.target.value}})})
  }

  onChangeFiltersAge (e) {
    this.setState({filters: update(this.state.filters, {edad: {$set: e.target.value}})})
  }

  onChangeFiltersStatus (e) {
    this.setState({filters: update(this.state.filters, {estado: {$set: e.target.value}})})
  }

  onChangeName (e) {
    this.setState({name: e.target.value})
  }

  onChangeAge (e) {
    this.setState({age: e.target.value})
  }

  onChangeGender (e) {
    this.setState({gender: e.target.value})
  }

  onChangeStatus (e) {
    this.setState({status: e.target.value})
  }

  onChangeNotes (e) {
    this.setState({notes: e.target.value})
  }

  onCleanFilters () {
    this.setState({filters: this.data.filters}, this.onFilter)
  }

  toggleModal () {
    this.setState({modalOpen: !this.state.modalOpen})
  }

  onFilter () {
    browserHistory.push('/personas')
    this.loadData()
  }

  resetState () {
    this.setState({
      id: '',
      name: '',
      age: '',
      gender: '',
      status: '',
      notes: ''
    })
  }

  setPerson (person) {
    this.setState({
      name: person.nombre,
      age: person.edad,
      gender: person.sexo,
      status: person.estado,
      notes: person.notas,
      id: person.id
    }, this.toggleModal)
  }

  onSubmit (id = '') {
    let { name, age, gender, status, notes, people } = this.state
    let data = {
      nombre: name,
      edad: age,
      sexo: gender,
      estado: status,
      notas: notes
    }
    if (id) {
      API.People.Update(id, data)
        .then(response => {
          let updatedPerson = response.persona
          people = people.map(person => person.id === updatedPerson.id ? updatedPerson : person)
          this.setState({ people }, this.resetState)
        })
    } else {
      API.People.SendNewds(data)
        .then(response => {
          people.push(response.persona)
          this.setState({ people })
        })
    }
    this.toggleModal()
  }

  // Get clients
  loadData () {
    let { filters, currentPage, sort } = this.state
    let _filters = _pickBy(filters, filter => filter.length > 0)
    // let page = currentPage > 1 ? {page: currentPage} : {}
    let params = Object.assign({}, _filters)
    this.setState({reqInProg: true})
    API.People.GetList(params)
      .then(response => {
        this.setState({people: response.personas, reqInProg: false})
      })
  }

  renderNewButton () {
    return (

        <Button
          className='is-pulled-right'
          buttonStyle='primary'
          onClick={this.toggleModal.bind(this)}
          icon='plus'
        >
          Nuevo Reporte de Persona
        </Button>

    )
  }

  renderFilters () {
    return (

          <TextField
            onChange={this.onChangeFiltersName.bind(this)}
            placeholder='Nombre'
            value={this.state.filters.nombre}
            onEnter={this.onFilter.bind(this)}
          />

          <SelectField
            options={GENDER}
            onChange={this.onChangeFiltersGender.bind(this)}
            placeholder='Sexo'
            value={this.state.filters.sexo}
          />

          <TextField
            onChange={this.onChangeFiltersAge.bind(this)}
            placeholder='Edad'
            value={this.state.filters.edad}
            onEnter={this.onFilter.bind(this)}
          />

          <SelectField
            onChange={this.onChangeFiltersStatus.bind(this)}
            placeholder='Estado'
            value={this.state.filters.estado}
            options={STATUS}
          />

              <Button
                className='is-fullwidth'
                onClick={this.onCleanFilters.bind(this)}
                icon='close-circle-outline'
              >Limpiar</Button>

              <Button
                className='is-fullwidth'
                buttonStyle='info is-outlined'
                onClick={this.onFilter.bind(this)}
                icon='magnify'
              >Filtrar</Button>

    )
  }

  renderTable () {
    let { people, reqInProg } = this.state
    if (reqInProg) return
Cargando...

    let table =
No hay resultados...

    if (people.length > 0) {
      let peopleList = people.map(person => {
        let gender = 'Otro / no especificado'
        if (person.sexo === 'm') gender = 'Hombre'
        if (person.sexo === 'f') gender = 'Mujer'
        return (
          <tr
            key={`people-${person.id}`}
            onClick={this.setPerson.bind(this, person)}
          >
            {person.nombre}
            {person.edad}
            {gender}
            {person.estado}
            {person.notas}

        )
      })
      table = (

                Nombre
                Edad
                Sexo
                Estado
                Notas

              {peopleList}

      )
    }
    return table
  }

  renderModal () {
    return (
      <Modal
        title='Nuevo Reporte de Persona'
        isActive={this.state.modalOpen}
        toggleModal={this.toggleModal.bind(this)}
        onSubmit={this.onSubmit.bind(this, this.state.id)}
      >

              <TextField
                label='Nombre'
                value={this.state.name}
                onChange={this.onChangeName.bind(this)}
              />

              <TextField
                label='Edad'
                type='number'
                value={this.state.age}
                onChange={this.onChangeAge.bind(this)}
              />

              <SelectField
                placeholder='Sexo'
                options={GENDER}
                label='Sexo'
                value={this.state.gender}
                onChange={this.onChangeGender.bind(this)}
              />

              <SelectField
                placeholder='Estado'
                options={STATUS}
                label='Estado'
                value={this.state.status}
                onChange={this.onChangeStatus.bind(this)}
              />

              <TextField
                label='Notas'
                value={this.state.notes}
                onChange={this.onChangeNotes.bind(this)}
              />

      </Modal>
    )
  }

  render () {
    return (

        {this.renderNewButton()}
        {this.renderFilters()}
        {this.renderTable()}
        {this.renderModal()}

    )
  }
}
<|endoftext|>


<commit_before>/*
 *
 *
 *
 */

// Utility
if ( typeof Object.create !== 'function' ) {
	Object.create = function( obj ) {
		function F() {};
		F.prototype = obj;
		return new F();
	};
}

;(function($) {

    // an object for keeping track of the whole system
    $.jmolTools = {
        neighborhood : false,
        stereo: false,
        models : {}, // all model objects, both loaded and not
        numModels: 0 // number of loaded models
    };

    // an object for keeping track of each individual model's state
    var jmolModel = {

        init: function (options, elem) {
			var self = this; // each element
			self.elem = elem;
			self.$elem = $( elem );

            self.modelNumber = null;

            self.loaded       = false;
            self.neighborhood = false;
            self.superimposed = false;
            self.styled       = false;
            self.checked      = false;
            self.hidden       = false;

			self.bindEvents();
        },

        bindEvents: function() {
            var self = this;
            self.$elem.on('click', self.jmolToggle );
        },

        loadData: function() {

            var self = this;
            if ( self.loaded ) { return; }

            $.ajax({
                url: $.fn.jmolTools.options.serverUrl,
                type: 'POST',
                data: {'coord' : self.$elem.data($.fn.jmolTools.options.dataAttribute)}
            }).done(function(data) {
                self.appendData(data);
                if ( self.loaded ) {
                    self.updateModelCounts();
                    self.superimpose();
                    self.styleModel();
                    self.show();
                }
            });
        },

        appendData: function(data) {
            var self = this;
            if ( data.indexOf('MODEL') > -1 ) {
                jmolScriptWait("load DATA \"append structure\"\n" + data + 'end "append structure";');
                self.loaded = true;
            } else {
                console.error('Server returned: ' + data);
            }
        },

        updateModelCounts: function() {
            this.modelNumber = ++$.jmolTools.numModels;
        },

		// superimpose this model onto the first one using phosphate atoms
		superimpose: function() {
		    var self = this;
		    if ( self.superimposed ) { return; }
            var m = self.modelNumber;
            if ( m < 2 ) { return; } // m == 1; nothing to superimpose on

                for (var i = 0; i < 3; i++) {
                // if the same number of phosphates, try to superimpose,
                // otherwise take the first four phosphates
                var command = 'if ({*.P/' + m + '.1}.length == {*.P/1.1}) ' +
                              '{x=compare({*.P/' + m + '.1},{*.P/1.1});}' +
                              'else {x=compare({(*.P/' + m + '.1)[1][4]},{(*.P/1.1)[1][4]});};' +
                              'select ' + m + '.1,' + m + '.2; rotate selected @{x};';
                jmolScript(command);
                }

            self.superimposed = true;
		},

        styleModel: function() {
            if ( this.styled ) { return; }
            var self = this;
            var m = self.modelNumber;
            command = 'select [U]/' + m + '.1; color navy;' +
                      'select [G]/' + m + '.1; color chartreuse;' +
                      'select [C]/' + m + '.1; color gold;' +
                      'select [A]/' + m + '.1; color red;' +
                      'select nucleic and ' + m + '.2; color grey;' +
                      'select protein and ' + m + '.2; color purple;' +
                      'select hetero  and ' + m + '.2; color pink;' +
                      'select ' + m + '.2; color translucent 0.8;' +
                      'select ' + m + '.1,' + m + '.2;' +
                      'spacefill off;' +
                      'center ' + m + '.1;' +
                      'zoom {'  + m + '.1} 0;';
            jmolScript(command);
            self.styled = true;
        },

        show: function() {
            var self = this;
            var m = self.modelNumber;

            if ( $.fn.jmolTools.options.mutuallyExclusive ) {
                self.hideAll();
            }

            if (self.neighborhood) {
                command = 'frame *;display displayed or ' + m + '.1,' + m + '.2; center ' + m + '.1;';
            } else {
                command = 'frame *;display displayed or '      + m + '.1;' +
                          'frame *;display displayed and not ' + m + '.2;' +
                          'center ' + m + '.1;';
            }
            jmolScript(command);
            self.hidden = false;
            self.toggleCheckbox();
        },

		hide: function () {
		    var self = this;
		    m = self.modelNumber;
		    if ( self.loaded ) {
                jmolScript('frame *;display displayed and not ' + m + '.1,' + m + '.2;');
                self.hidden  = true;
                self.toggleCheckbox();
            }
		},

        hideAll: function() {
            jmolScript('hide *');
            $.each($.jmolTools.models, function() {
                this.hidden = true;
                this.toggleCheckbox();
            });
        },

        jmolToggle: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else {
                if ( self.hidden ) {
                    self.show();
                } else {
                    self.hide();
                }
            }
        },

        jmolShow: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else if ( self.hidden ) {
                self.show();
            }
        },

        jmolHide: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else if ( !self.hidden ) {
                self.hide();
            }
        },

		toggleCheckbox: function() {
		    if ( !$.fn.jmolTools.options.toggleCheckbox ) { return; }
            this.$elem.prop('checked', !this.hidden);
		},

		toggleNeighborhood: function() {
		    var self = this;
		    self.neighborhood = !self.neighborhood;
		    if ( !self.hidden && self.loaded ) {
                self.show();
            }
		}

    };

    var Helpers = {

        toggleStereo: function() {
            $.jmolTools.stereo
                ? jmolScript('stereo off;')
                : jmolScript('stereo on;')
            $.jmolTools.stereo = !$.jmolTools.stereo;
        },

        toggleNumbers: function() {
            console.log(this);
            if ( $(this).is(':checked') ) {
                jmolScript('select {*.P},{*.CA};label %[sequence]%[resno];color labels black;');
            } else {
                jmolScript('label off;');
            }
        },

        toggleNeighborhood: function() {
            // update button text
            if ($.jmolTools.neighborhood) {
                this.value = 'Show neighborhood';
            } else {
                this.value = 'Hide neighborhood';
            }
            $.jmolTools.neighborhood = !$.jmolTools.neighborhood;

            $.each($.jmolTools.models, function(ind, model) {
                model.toggleNeighborhood();
            });
        },

        showAll: function() {
            $.each($.jmolTools.models, function(ind, model) {
                if ( ! model.loaded ) {
                    model.loadData();
                } else {
                    model.show();
                }
                model.toggleCheckbox();
            });
        },

        hideAll: function() {
            $.jmolTools.models[$.fn.jmolTools.elems[0].id].hideAll();
        },

        showNext: function() {
            var elems = $($.jmolTools.selector), // can't use cache because the element order can change
                last = elems.length - 1,
                indToCheck = new Array();

            // figure out which ones should be checked
            for (var i = 0; i < elems.length-1; i++) {
                if ( elems[i].checked ) {
                    indToCheck.push(i+1); // the next one should be checked
                    $.jmolTools.models[elems[i].id].jmolToggle.apply(elems[i]); // toggle this model
                }
            }

            // analyze the last one
            if ( elems[last].checked ) {
                $.jmolTools.models[elems[last].id].jmolToggle.apply(elems[last]);
            }

            // uncheck all
            elems.filter(':checked').prop('checked', false);

            // check only the right ones
            $.each(indToCheck, function(ind, id) {
                elems[id].checked = true;
                $.jmolTools.models[elems[id].id].jmolToggle.apply(elems[id]);
            });

            // keep the first one checked if all are unchecked
            if ( elems.filter(':checked').length == 0 ) {
                elems[0].checked = true;
                $.jmolTools.models[elems[0].id].jmolToggle.apply(elems[0]);
            }
        },

        showPrev: function() {
            var elems = $($.jmolTools.selector), // can't use cache because the element order can change
                last = elems.length - 1,
                indToCheck = new Array();

            // loop over all checkboxes except for the first one
            for (var i = elems.length-1; i >= 1; i--) {
                if ( elems[i].checked ) {
                    indToCheck.push(i-1);
                    $.jmolTools.models[elems[i].id].jmolToggle.apply(elems[i]); // toggle this model
                }
            }
            // separate handling of the first checkbox
            if ( elems[0].checked ) {
                indToCheck.push(elems.length-1);
                $.jmolTools.models[elems[0].id].jmolToggle.apply(elems[0]);
            }

            // temporarily uncheck everything
            elems.filter(':checked').prop('checked', false);

            // check only the right ones
            $.each(indToCheck, function(ind, id) {
                elems[indToCheck[i]].checked = true;
                $.jmolTools.models[elems[id].id].jmolToggle.apply(elems[id]);
            });
            // keep the last checkbox checked if all others are unchecked
            if ( elems.filter(':checked').length == 0 ) {
                elems[last].checked = true;
                $.jmolTools.models[elems[last].id].jmolToggle.apply(elems[last]);
            }
        },

        reportLoadingBegan: function() {
            jmolScript('set echo top left; color echo green; echo Loading...;');
        },

        reportLoadingComplete: function() {
            jmolScript('set echo top left; color echo green; echo Done;');
        },

        reportClear: function() {
            jmolScript('set echo top left; echo ;');
        },

        bindEvents: function() {
            $('#' + $.fn.jmolTools.options.showStereoId).on('click', Helpers.toggleStereo);
            $('#' + $.fn.jmolTools.options.showNeighborhoodId).on('click', Helpers.toggleNeighborhood);
            $('#' + $.fn.jmolTools.options.showNumbersId).on('click', Helpers.toggleNumbers);
            $('#' + $.fn.jmolTools.options.showAllId)
                    .toggle(Helpers.showAll, Helpers.hideAll)
                    .toggle(
                function() {
                    $(this).val('Hide all');
                },
                function() {
                    $(this).val('Show all');
                }
            );
            $('#' + $.fn.jmolTools.options.showNextId).on('click', Helpers.showNext);
            $('#' + $.fn.jmolTools.options.showPrevId).on('click', Helpers.showPrev);
            $('#' + $.fn.jmolTools.options.clearId).on('click', Helpers.hideAll);

            $(document).ajaxSend(function() {
                Helpers.reportLoadingBegan();
            });

            $(document).ajaxStop(function() {
                Helpers.reportLoadingComplete();
                setTimeout(Helpers.reportClear, 1200);
            });
        },

        setMutuallyExclusiveProperty: function() {
            if ( $.fn.jmolTools.options.mutuallyExclusive ||
                 $.fn.jmolTools.elems.is('input[type="radio"]') ) {
                $.fn.jmolTools.options.mutuallyExclusive = true;
            }
        }

    }

    // plugin initialization
    $.fn.jmolTools = function ( options ) {

        $.jmolTools.selector = $(this).selector;

        $.fn.jmolTools.options = $.extend( {}, $.fn.jmolTools.options, options );

        // bind events
        Helpers.bindEvents();

        // initialize model state for each element
        $.fn.jmolTools.elems = this.each( function() {
            // create a new object to keep track of state
            var jmdb = Object.create( jmolModel );
            jmdb.init( options, this );
            // store the object
            $.jmolTools.models[this.id] = jmdb;
        });

        // add convenience methods to toggle structures
        $.fn.jmolToggle = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolToggle.apply(this);
            });
        }
        $.fn.jmolShow = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolShow.apply(this);
            });
        }
        $.fn.jmolHide = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolHide.apply(this);
            });
        }

        //
        Helpers.setMutuallyExclusiveProperty();

        // return elements for chaining
        return $.fn.jmolTools.elems;
    }

    var env = window.location.href.split('/')[3]; // rna3dhub or rna3dhub_dev
    if ( env != 'rna3dhub' && env != 'rna3dhub_dev' ) {
        env = 'rna3dhub';
    }

    // default options
	$.fn.jmolTools.options = {
        serverUrl   : 'http://rna.bgsu.edu/' + env + '/rest/getCoordinates',
        dataAttribute: 'coord',
        toggleCheckbox: true,      // by default each model will monitor the checked state of its corresponding checkbox
        mutuallyExclusive:  false, // by default will set to false for checkboxes and false for radiobuttons
        showNeighborhoodId: false,
        showNextId:         false,
        showPrevId:         false,
        showAllId:          false,
        showNumbersId:      false,
        showStereoId:       false,
        clearId:            false
	};

})(jQuery);
<commit_msg>Fix incorrect hide behavior<commit_after>/*
 *
 *
 *
 */

// Utility
if ( typeof Object.create !== 'function' ) {
	Object.create = function( obj ) {
		function F() {};
		F.prototype = obj;
		return new F();
	};
}

;(function($) {

    // an object for keeping track of the whole system
    $.jmolTools = {
        neighborhood : false,
        stereo: false,
        models : {}, // all model objects, both loaded and not
        numModels: 0 // number of loaded models
    };

    // an object for keeping track of each individual model's state
    var jmolModel = {

        init: function (options, elem) {
			var self = this; // each element
			self.elem = elem;
			self.$elem = $( elem );

            self.modelNumber = null;

            self.loaded       = false;
            self.neighborhood = false;
            self.superimposed = false;
            self.styled       = false;
            self.checked      = false;
            self.hidden       = false;

			self.bindEvents();
        },

        bindEvents: function() {
            var self = this;
            self.$elem.on('click', self.jmolToggle );
        },

        loadData: function() {

            var self = this;
            if ( self.loaded ) { return; }

            $.ajax({
                url: $.fn.jmolTools.options.serverUrl,
                type: 'POST',
                data: {'coord' : self.$elem.data($.fn.jmolTools.options.dataAttribute)}
            }).done(function(data) {
                self.appendData(data);
                if ( self.loaded ) {
                    self.updateModelCounts();
                    self.superimpose();
                    self.styleModel();
                    self.show();
                }
            });
        },

        appendData: function(data) {
            var self = this;
            if ( data.indexOf('MODEL') > -1 ) {
                jmolScriptWait("load DATA \"append structure\"\n" + data + 'end "append structure";');
                self.loaded = true;
            } else {
                console.error('Server returned: ' + data);
            }
        },

        updateModelCounts: function() {
            this.modelNumber = ++$.jmolTools.numModels;
        },

		// superimpose this model onto the first one using phosphate atoms
		superimpose: function() {
		    var self = this;
		    if ( self.superimposed ) { return; }
            var m = self.modelNumber;
            if ( m < 2 ) { return; } // m == 1; nothing to superimpose on

                for (var i = 0; i < 3; i++) {
                // if the same number of phosphates, try to superimpose,
                // otherwise take the first four phosphates
                var command = 'if ({*.P/' + m + '.1}.length == {*.P/1.1}) ' +
                              '{x=compare({*.P/' + m + '.1},{*.P/1.1});}' +
                              'else {x=compare({(*.P/' + m + '.1)[1][4]},{(*.P/1.1)[1][4]});};' +
                              'select ' + m + '.1,' + m + '.2; rotate selected @{x};';
                jmolScript(command);
                }

            self.superimposed = true;
		},

        styleModel: function() {
            if ( this.styled ) { return; }
            var self = this;
            var m = self.modelNumber;
            command = 'select [U]/' + m + '.1; color navy;' +
                      'select [G]/' + m + '.1; color chartreuse;' +
                      'select [C]/' + m + '.1; color gold;' +
                      'select [A]/' + m + '.1; color red;' +
                      'select nucleic and ' + m + '.2; color grey;' +
                      'select protein and ' + m + '.2; color purple;' +
                      'select hetero  and ' + m + '.2; color pink;' +
                      'select ' + m + '.2; color translucent 0.8;' +
                      'select ' + m + '.1,' + m + '.2;' +
                      'spacefill off;' +
                      'center ' + m + '.1;' +
                      'zoom {'  + m + '.1} 0;';
            jmolScript(command);
            self.styled = true;
        },

        show: function() {
            var self = this;
            var m = self.modelNumber;

            if ( $.fn.jmolTools.options.mutuallyExclusive ) {
                self.hideAll();
            }

            if (self.neighborhood) {
                command = 'frame *;display displayed or ' + m + '.1,' + m + '.2; center ' + m + '.1;';
            } else {
                command = 'frame *;display displayed or '      + m + '.1;' +
                          'frame *;display displayed and not ' + m + '.2;' +
                          'center ' + m + '.1;';
            }
            jmolScript(command);
            self.hidden = false;
            self.toggleCheckbox();
        },

		hide: function () {
		    var self = this;
		    m = self.modelNumber;
		    if ( self.loaded ) {
		        command = 'frame *;display displayed and not ' + m + '.1;' +
		                          'display displayed and not ' + m + '.2;'
                jmolScript(command);
                self.hidden  = true;
                self.toggleCheckbox();
            }
		},

        hideAll: function() {
            jmolScript('hide *');
            $.each($.jmolTools.models, function() {
                this.hidden = true;
                this.toggleCheckbox();
            });
        },

        jmolToggle: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else {
                if ( self.hidden ) {
                    self.show();
                } else {
                    self.hide();
                }
            }
        },

        jmolShow: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else if ( self.hidden ) {
                self.show();
            }
        },

        jmolHide: function() {
            var self = $.jmolTools.models[this.id];

            if ( ! self.loaded ) {
                self.loadData();
            } else if ( !self.hidden ) {
                self.hide();
            }
        },

		toggleCheckbox: function() {
		    if ( !$.fn.jmolTools.options.toggleCheckbox ) { return; }
            this.$elem.prop('checked', !this.hidden);
		},

		toggleNeighborhood: function() {
		    var self = this;
		    self.neighborhood = !self.neighborhood;
		    if ( !self.hidden && self.loaded ) {
                self.show();
            }
		}

    };

    var Helpers = {

        toggleStereo: function() {
            $.jmolTools.stereo
                ? jmolScript('stereo off;')
                : jmolScript('stereo on;')
            $.jmolTools.stereo = !$.jmolTools.stereo;
        },

        toggleNumbers: function() {
            console.log(this);
            if ( $(this).is(':checked') ) {
                jmolScript('select {*.P},{*.CA};label %[sequence]%[resno];color labels black;');
            } else {
                jmolScript('label off;');
            }
        },

        toggleNeighborhood: function() {
            // update button text
            if ($.jmolTools.neighborhood) {
                this.value = 'Show neighborhood';
            } else {
                this.value = 'Hide neighborhood';
            }
            $.jmolTools.neighborhood = !$.jmolTools.neighborhood;

            $.each($.jmolTools.models, function(ind, model) {
                model.toggleNeighborhood();
            });
        },

        showAll: function() {
            $.each($.jmolTools.models, function(ind, model) {
                if ( ! model.loaded ) {
                    model.loadData();
                } else {
                    model.show();
                }
                model.toggleCheckbox();
            });
        },

        hideAll: function() {
            $.jmolTools.models[$.fn.jmolTools.elems[0].id].hideAll();
        },

        showNext: function() {
            var elems = $($.jmolTools.selector), // can't use cache because the element order can change
                last = elems.length - 1,
                indToCheck = new Array();

            // figure out which ones should be checked
            for (var i = 0; i < elems.length-1; i++) {
                if ( elems[i].checked ) {
                    indToCheck.push(i+1); // the next one should be checked
                    $.jmolTools.models[elems[i].id].jmolToggle.apply(elems[i]); // toggle this model
                }
            }

            // analyze the last one
            if ( elems[last].checked ) {
                $.jmolTools.models[elems[last].id].jmolToggle.apply(elems[last]);
            }

            // uncheck all
            elems.filter(':checked').prop('checked', false);

            // check only the right ones
            $.each(indToCheck, function(ind, id) {
                elems[id].checked = true;
                $.jmolTools.models[elems[id].id].jmolToggle.apply(elems[id]);
            });

            // keep the first one checked if all are unchecked
            if ( elems.filter(':checked').length == 0 ) {
                elems[0].checked = true;
                $.jmolTools.models[elems[0].id].jmolToggle.apply(elems[0]);
            }
        },

        showPrev: function() {
            var elems = $($.jmolTools.selector), // can't use cache because the element order can change
                last = elems.length - 1,
                indToCheck = new Array();

            // loop over all checkboxes except for the first one
            for (var i = elems.length-1; i >= 1; i--) {
                if ( elems[i].checked ) {
                    indToCheck.push(i-1);
                    $.jmolTools.models[elems[i].id].jmolToggle.apply(elems[i]); // toggle this model
                }
            }
            // separate handling of the first checkbox
            if ( elems[0].checked ) {
                indToCheck.push(elems.length-1);
                $.jmolTools.models[elems[0].id].jmolToggle.apply(elems[0]);
            }

            // temporarily uncheck everything
            elems.filter(':checked').prop('checked', false);

            // check only the right ones
            $.each(indToCheck, function(ind, id) {
                elems[indToCheck[i]].checked = true;
                $.jmolTools.models[elems[id].id].jmolToggle.apply(elems[id]);
            });
            // keep the last checkbox checked if all others are unchecked
            if ( elems.filter(':checked').length == 0 ) {
                elems[last].checked = true;
                $.jmolTools.models[elems[last].id].jmolToggle.apply(elems[last]);
            }
        },

        reportLoadingBegan: function() {
            jmolScript('set echo top left; color echo green; echo Loading...;');
        },

        reportLoadingComplete: function() {
            jmolScript('set echo top left; color echo green; echo Done;');
        },

        reportClear: function() {
            jmolScript('set echo top left; echo ;');
        },

        bindEvents: function() {
            $('#' + $.fn.jmolTools.options.showStereoId).on('click', Helpers.toggleStereo);
            $('#' + $.fn.jmolTools.options.showNeighborhoodId).on('click', Helpers.toggleNeighborhood);
            $('#' + $.fn.jmolTools.options.showNumbersId).on('click', Helpers.toggleNumbers);
            $('#' + $.fn.jmolTools.options.showAllId)
                    .toggle(Helpers.showAll, Helpers.hideAll)
                    .toggle(
                function() {
                    $(this).val('Hide all');
                },
                function() {
                    $(this).val('Show all');
                }
            );
            $('#' + $.fn.jmolTools.options.showNextId).on('click', Helpers.showNext);
            $('#' + $.fn.jmolTools.options.showPrevId).on('click', Helpers.showPrev);
            $('#' + $.fn.jmolTools.options.clearId).on('click', Helpers.hideAll);

            $(document).ajaxSend(function() {
                Helpers.reportLoadingBegan();
            });

            $(document).ajaxStop(function() {
                Helpers.reportLoadingComplete();
                setTimeout(Helpers.reportClear, 1200);
            });
        },

        setMutuallyExclusiveProperty: function() {
            if ( $.fn.jmolTools.options.mutuallyExclusive ||
                 $.fn.jmolTools.elems.is('input[type="radio"]') ) {
                $.fn.jmolTools.options.mutuallyExclusive = true;
            }
        }

    }

    // plugin initialization
    $.fn.jmolTools = function ( options ) {

        $.jmolTools.selector = $(this).selector;

        $.fn.jmolTools.options = $.extend( {}, $.fn.jmolTools.options, options );

        // bind events
        Helpers.bindEvents();

        // initialize model state for each element
        $.fn.jmolTools.elems = this.each( function() {
            // create a new object to keep track of state
            var jmdb = Object.create( jmolModel );
            jmdb.init( options, this );
            // store the object
            $.jmolTools.models[this.id] = jmdb;
        });

        // add convenience methods to toggle structures
        $.fn.jmolToggle = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolToggle.apply(this);
            });
        }
        $.fn.jmolShow = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolShow.apply(this);
            });
        }
        $.fn.jmolHide = function ( options ) {
            return this.each( function() {
                $.jmolTools.models[this.id].jmolHide.apply(this);
            });
        }

        //
        Helpers.setMutuallyExclusiveProperty();

        // return elements for chaining
        return $.fn.jmolTools.elems;
    }

    var env = window.location.href.split('/')[3]; // rna3dhub or rna3dhub_dev
    if ( env != 'rna3dhub' && env != 'rna3dhub_dev' ) {
        env = 'rna3dhub';
    }

    // default options
	$.fn.jmolTools.options = {
        serverUrl   : 'http://rna.bgsu.edu/' + env + '/rest/getCoordinates',
        dataAttribute: 'coord',
        toggleCheckbox: true,      // by default each model will monitor the checked state of its corresponding checkbox
        mutuallyExclusive:  false, // by default will set to false for checkboxes and false for radiobuttons
        showNeighborhoodId: false,
        showNextId:         false,
        showPrevId:         false,
        showAllId:          false,
        showNumbersId:      false,
        showStereoId:       false,
        clearId:            false
	};

})(jQuery);
<|endoftext|>