<commit_before>define(function() {

  'use strict';

  function VolumeDescriptorView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeDescriptorView.prototype = {
    get typeCode() {
      return this.bytes[0];
    },
    get descriptorType() {
      switch (this.typeCode) {
        case 0: return 'boot';
        case 1: return 'volume'; // primary
        case 2: return 'volume'; // supplementary
        case 3: return 'partition';
        case 255: return 'terminator';
        default: return this.typeCode;
      }
    },
    get isPrimaryVolume() {
      return this.typeCode === 1;
    },
    get signature() {
      return String.fromCharCode(this.bytes[1], this.bytes[2], this.bytes[3], this.bytes[4], this.bytes[5]);
    },
    get hasValidSignature() {
      return this.signature === 'CD001';
    },
    get version() {
      return this.bytes[6];
    },
    get body() {
      var body, buffer = this.dv.buffer, byteOffset = this.dv.byteOffset, byteLength = this.dv.byteLength;
      switch(this.descriptorType) {
        case 'boot': body = new BootRecordView(buffer, byteOffset, byteLength); break;
        case 'volume': body = new VolumeRecordView(buffer, byteOffset, byteLength); break;
        default: body = null; break;
      }
      Object.defineProperty(this, 'body', {value:body});
      return body;
    },
  };

  function readSpacePadded(bytes) {
    return String.fromCharCode.apply(null, bytes).replace(/\s*$/, '');
  }

  function decodeTimeZoneSuffix(tz) {
    tz = (tz - 48) * 15;
    var sign = (tz < 0) ? ('-') : ('+');
    tz = Math.abs(tz);
    return sign + ('0' + Math.floor(tz / 60)).slice(-2) + ':' + ('0' + tz%60).slice(-2);
  }

  function readStringDateTime(bytes, offset) {
    var year = String.fromCharCode(bytes[offset + 0], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
    if (!/^0*[1-9][0-9]*$/.test(year)) return null;
    var month = String.fromCharCode(bytes[offset + 4], bytes[offset + 5]);
    var day = String.fromCharCode(bytes[offset + 6], bytes[offset + 7]);
    var hour = String.fromCharCode(bytes[offset + 8], bytes[offset + 9]);
    var minute = String.fromCharCode(bytes[offset + 10], bytes[offset + 11]);
    var second = String.fromCharCode(bytes[offset + 12], bytes[offset + 13]);
    var hundredths = String.fromCharCode(bytes[offset + 14], bytes[offset + 15]);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 16]);
    var dateString = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second+'.'+hundredths+timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function readBinaryDateTime(bytes, offset) {
    if (bytes[offset + 1] === 0) return null; // month, must be 1-12
    var year = '' + (1900 + bytes[offset]);
    var month = ('0' + bytes[offset + 1]).slice(-2);
    var day = ('0' + bytes[offset + 2]).slice(-2);
    var hour = ('0' + bytes[offset + 3]).slice(-2);
    var minute = ('0' + bytes[offset + 4]).slice(-2);
    var second = ('0' + bytes[offset + 5]).slice(-2);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 6]);
    var dateString = year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function BootRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.bootData = this.bytes.subarray(71);
  }
  BootRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(7, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(39, 64));
    },
  };

  function VolumeRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(8, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(40, 64));
    },
    get blockCount() {
      return this.dv.getUint32(80, true);
    },
    get diskCount() {
      return this.dv.getUint16(120, true);
    },
    get diskNumber() {
      return this.dv.getUint16(124, true);
    },
    get blockByteLength() {
      return this.dv.getUint16(128, true);
    },
    get pathTableByteLength() {
      return this.dv.getUint32(132, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(140, true);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(144, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(148, false);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(152, false);
    },
    get offsetof_rootDirectory() {
      return 156;
    },
    get sizeof_rootDirectory() {
      return 34;
    },
    get rootDirectory() {
      var root = new DirectoryRecordView(this.dv.buffer, this.dv.byteOffset + 156, 34);
      Object.defineProperty(this, 'rootDirectory', {value:root});
      return root;
    },
    get setIdentifier() {
      return readStringPadded(this.bytes.subarray(190, 190 + 128));
    },
    get publisher() {
      return readStringPadded(this.bytes.subarray(318, 318 + 128));
    },
    get dataPreparer() {
      return readStringPadded(this.bytes.subarray(446, 446 + 128));
    },
    get application() {
      return readStringPadded(this.bytes.subarray(574, 574 + 128));
    },
    get copyrightFilename() {
      return readStringPadded(this.bytes.subarray(702, 702 + 38));
    },
    get abstractFilename() {
      return readStringPadded(this.bytes.subarray(740, 740 + 36));
    },
    get bibliographyFilename() {
      return readStringPadded(this.bytes.subarray(776, 776 + 37));
    },
    get createdAt() {
      return readStringDateTime(this.bytes, 813);
    },
    get modifiedAt() {
      return readStringDateTime(this.bytes, 830);
    },
    get becomesObsoleteAt() {
      return readStringDateTime(this.bytes, 847);
    },
    get becomesEffectiveAt() {
      return readStringDateTime(this.bytes, 864);
    },
    get fileStructureVersion() {
      return this.bytes[881];
    },
    get applicationData() {
      var section = this.bytes.subarray(883, 883 + 512);
      Object.defineProperty(this, 'applicationData', {value:section});
      return section;
    },
  };

  function DirectoryRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  DirectoryRecordView.prototype = {
    get length() {
      return this.bytes[0];
    },
    get extendedAttributeRecordLength() {
      return this.bytes[1];
    },
    get dataBlockAddress() {
      return this.dv.getUint32(2, true);
    },
    get dataByteLength() {
      return this.dv.getUint32(10, true);
    },
    get recordedAt() {
      return readBinaryDateTime(this.bytes, 18);
    },
    get flags() {
      return this.bytes[25];
    },
    get isHidden() {
      return !!(this.flags & (1 << 0));
    },
    get isDirectory() {
      return !!(this.flags & (1 << 1));
    },
    get isAssociatedFile() {
      return !!(this.flags & (1 << 2));
    },
    get hasExtendedAttributeInfo() {
      return !!(this.flags & (1 << 3));
    },
    get hasPermissionsInExtendedAttributeInfo() {
      return !!(this.flags & (1 << 4));
    },
    get isPartial() {
      return !!(this.flags & (1 << 7));
    },
    get interleavedUnitSize() {
      return this.bytes[26];
    },
    get interleavedGapSize() {
      return this.bytes[27];
    },
    get volumeNumber() {
      return this.dv.getUint16(28, true);
    },
    get nameAndIdentifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(33, 33 + this.bytes[32]));
    },
    get name() {
      return this.nameAndIdentifier.replace(/;\d+$/, '');
    },
    get identifier() {
      return +(this.nameAndIdentifier.match(/;(\d+)$/) || '')[1];
    },
    get after_identifier() {
      var identifierLength = this.bytes[32];
      return 33 + identifierLength + ((identifierLength + 1) % 2);
    },
    get byteLength() {
      var extendedLength = this.extendedAttributeRecordLength;
      return this.after_identifier + extendedLength + extendedLength % 2;
    },
  };

  function PathTableEntryView(littleEndian, buffer, byteOffset, byteLength) {
    this.littleEndian = littleEndian;
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  PathTableEntryView.prototype = {
    get extendedAttributeLength() {
      return this.bytes[1];
    },
    get extentBlockAddress() {
      return this.dv.getUint32(2, this.littleEndian);
    },
    get parentDirectoryIndex() {
      return this.dv.getUint16(6, this.littleEndian);
    },
    get identifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(8, 8 + this.bytes[0]));
    },
    get byteLength() {
      var idLength = this.bytes[0];
      return 8 + idLength + idLength % 2;
    },
  };

  return {
    getStructView: function(segment) {
      switch (segment.getTypeParameter('which')) {
        case 'volume-descriptor': return VolumeDescriptorView;
        case 'path-table-entry': return PathTableEntryView;
        case 'boot-record': return BootRecordView;
        case 'volume-record': return VolumeRecordView;
        case 'folder': return DirectoryRecordView;
        case 'file': return DirectoryRecordView;
        default: return null;
      }
    },
    PathTableEntryView: PathTableEntryView,
    VolumeDescriptorView: VolumeDescriptorView,
    BootRecordView: BootRecordView,
    VolumeRecordView: VolumeRecordView,
    DirectoryRecordView: DirectoryRecordView,
  };

});
<commit_msg>Update iso-9660.js<commit_after>define(function() {

  'use strict';

  function VolumeDescriptorView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeDescriptorView.prototype = {
    get typeCode() {
      return this.bytes[0];
    },
    get descriptorType() {
      switch (this.typeCode) {
        case 0: return 'boot';
        case 1: return 'volume'; // primary
        case 2: return 'volume'; // supplementary
        case 3: return 'partition';
        case 255: return 'terminator';
        default: return this.typeCode;
      }
    },
    get isPrimaryVolume() {
      return this.typeCode === 1;
    },
    get signature() {
      return String.fromCharCode(this.bytes[1], this.bytes[2], this.bytes[3], this.bytes[4], this.bytes[5]);
    },
    get hasValidSignature() {
      return this.signature === 'CD001';
    },
    get version() {
      return this.bytes[6];
    },
    get body() {
      var body, buffer = this.dv.buffer, byteOffset = this.dv.byteOffset, byteLength = this.dv.byteLength;
      switch(this.descriptorType) {
        case 'boot': body = new BootRecordView(buffer, byteOffset, byteLength); break;
        case 'volume': body = new VolumeRecordView(buffer, byteOffset, byteLength); break;
        default: body = null; break;
      }
      Object.defineProperty(this, 'body', {value:body});
      return body;
    },
  };

  function readSpacePadded(bytes) {
    return String.fromCharCode.apply(null, bytes).replace(/\s*$/, '');
  }

  function decodeTimeZoneSuffix(tz) {
    tz = (tz - 48) * 15;
    var sign = (tz < 0) ? ('-') : ('+');
    tz = Math.abs(tz);
    return sign + ('0' + Math.floor(tz / 60)).slice(-2) + ':' + ('0' + tz%60).slice(-2);
  }

  function readStringDateTime(bytes, offset) {
    var year = String.fromCharCode(bytes[offset + 0], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
    if (!/^0*[1-9][0-9]*$/.test(year)) return null;
    var month = String.fromCharCode(bytes[offset + 4], bytes[offset + 5]);
    var day = String.fromCharCode(bytes[offset + 6], bytes[offset + 7]);
    var hour = String.fromCharCode(bytes[offset + 8], bytes[offset + 9]);
    var minute = String.fromCharCode(bytes[offset + 10], bytes[offset + 11]);
    var second = String.fromCharCode(bytes[offset + 12], bytes[offset + 13]);
    var hundredths = String.fromCharCode(bytes[offset + 14], bytes[offset + 15]);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 16]);
    var dateString = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second+'.'+hundredths+timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function readBinaryDateTime(bytes, offset) {
    if (bytes[offset + 1] === 0) return null; // month, must be 1-12
    var year = '' + (1900 + bytes[offset]);
    var month = ('0' + bytes[offset + 1]).slice(-2);
    var day = ('0' + bytes[offset + 2]).slice(-2);
    var hour = ('0' + bytes[offset + 3]).slice(-2);
    var minute = ('0' + bytes[offset + 4]).slice(-2);
    var second = ('0' + bytes[offset + 5]).slice(-2);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 6]);
    var dateString = year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function BootRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.bootData = this.bytes.subarray(71);
  }
  BootRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(7, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(39, 64));
    },
  };

  function VolumeRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(8, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(40, 64));
    },
    get blockCount() {
      return this.dv.getUint32(80, true);
    },
    get diskCount() {
      return this.dv.getUint16(120, true);
    },
    get diskNumber() {
      return this.dv.getUint16(124, true);
    },
    get blockByteLength() {
      return this.dv.getUint16(128, true);
    },
    get pathTableByteLength() {
      return this.dv.getUint32(132, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(140, true);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(144, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(148, false);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(152, false);
    },
    get offsetof_rootDirectory() {
      return 156;
    },
    get sizeof_rootDirectory() {
      return 34;
    },
    get rootDirectory() {
      var root = new DirectoryRecordView(this.dv.buffer, this.dv.byteOffset + 156, 34);
      Object.defineProperty(this, 'rootDirectory', {value:root});
      return root;
    },
    get setIdentifier() {
      return readStringPadded(this.bytes.subarray(190, 190 + 128));
    },
    get publisher() {
      return readStringPadded(this.bytes.subarray(318, 318 + 128));
    },
    get dataPreparer() {
      return readStringPadded(this.bytes.subarray(446, 446 + 128));
    },
    get application() {
      return readStringPadded(this.bytes.subarray(574, 574 + 128));
    },
    get copyrightFilename() {
      return readStringPadded(this.bytes.subarray(702, 702 + 38));
    },
    get abstractFilename() {
      return readStringPadded(this.bytes.subarray(740, 740 + 36));
    },
    get bibliographyFilename() {
      return readStringPadded(this.bytes.subarray(776, 776 + 37));
    },
    get createdAt() {
      return readStringDateTime(this.bytes, 813);
    },
    get modifiedAt() {
      return readStringDateTime(this.bytes, 830);
    },
    get becomesObsoleteAt() {
      return readStringDateTime(this.bytes, 847);
    },
    get becomesEffectiveAt() {
      return readStringDateTime(this.bytes, 864);
    },
    get fileStructureVersion() {
      return this.bytes[881];
    },
    get applicationData() {
      var section = this.bytes.subarray(883, 883 + 512);
      Object.defineProperty(this, 'applicationData', {value:section});
      return section;
    },
  };

  function DirectoryRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  DirectoryRecordView.prototype = {
    get length() {
      return this.bytes[0];
    },
    get extendedAttributeRecordLength() {
      return this.bytes[1];
    },
    get dataBlockAddress() {
      return this.dv.getUint32(2, true);
    },
    get dataByteLength() {
      return this.dv.getUint32(10, true);
    },
    get recordedAt() {
      return readBinaryDateTime(this.bytes, 18);
    },
    get flags() {
      return this.bytes[25];
    },
    get isHidden() {
      return !!(this.flags & (1 << 0));
    },
    get isDirectory() {
      return !!(this.flags & (1 << 1));
    },
    get isAssociatedFile() {
      return !!(this.flags & (1 << 2));
    },
    get hasExtendedAttributeInfo() {
      return !!(this.flags & (1 << 3));
    },
    get hasPermissionsInExtendedAttributeInfo() {
      return !!(this.flags & (1 << 4));
    },
    get isPartial() {
      return !!(this.flags & (1 << 7));
    },
    get interleavedUnitSize() {
      return this.bytes[26];
    },
    get interleavedGapSize() {
      return this.bytes[27];
    },
    get volumeNumber() {
      return this.dv.getUint16(28, true);
    },
    get nameAndIdentifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(33, 33 + this.bytes[32]));
    },
    get name() {
      return this.nameAndIdentifier.replace(/;\d+$/, '');
    },
    get identifier() {
      return +(this.nameAndIdentifier.match(/;(\d+)$/) || '')[1];
    },
    get after_identifier() {
      var identifierLength = this.bytes[32];
      return 33 + identifierLength + ((identifierLength + 1) % 2);
    },
    get byteLength() {
      var extendedLength = this.extendedAttributeRecordLength;
      return this.after_identifier + extendedLength + extendedLength % 2;
    },
  };

  function PathTableEntryView(littleEndian, buffer, byteOffset, byteLength) {
    this.littleEndian = littleEndian;
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  PathTableEntryView.prototype = {
    get extendedAttributeLength() {
      return this.bytes[1];
    },
    get extentBlockAddress() {
      return this.dv.getUint32(2, this.littleEndian);
    },
    get parentDirectoryIndex() {
      return this.dv.getUint16(6, this.littleEndian);
    },
    get identifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(8, 8 + this.bytes[0]));
    },
    get byteLength() {
      var idLength = this.bytes[0];
      return 8 + idLength + idLength % 2;
    },
  };

  return {
    getStructView: function(segment) {
      switch (segment.format.parameters['which']) {
        case 'volume-descriptor': return VolumeDescriptorView;
        case 'path-table-entry': return PathTableEntryView;
        case 'boot-record': return BootRecordView;
        case 'volume-record': return VolumeRecordView;
        case 'folder': return DirectoryRecordView;
        case 'file': return DirectoryRecordView;
        default: return null;
      }
    },
    PathTableEntryView: PathTableEntryView,
    VolumeDescriptorView: VolumeDescriptorView,
    BootRecordView: BootRecordView,
    VolumeRecordView: VolumeRecordView,
    DirectoryRecordView: DirectoryRecordView,
  };

});
<|endoftext|>


<commit_before>angular.module('yds').directive('ydsBar', ['Data', 'CountrySelectionService', function(Data, CountrySelectionService){
    return {
        restrict: 'E',
        scope: {
            projectId: '@',     //id of the project that the data belong
            viewType: '@',     //name of the array that contains the visualised data
            lang: '@',          //lang of the visualised data

            useCountriesService: '@',  // if true will use selected countries service to load data instead of API

            titleX: '@',        //the text of the X-axis title
            titleY: '@',        //the text of the Y-axis title
            showLabelsX: '@',   //show or hide the X-axis label
            showLabelsY: '@',   //show or hide the Y-axis label
            showLegend: '@',    //enable or disable the chart's legend
            exporting: '@',     //enable or disable the export of the chart
            elementH: '@',      //set the height of the component
            titleSize: '@',     //the size of the chart's main title

            addToBasket: '@',   //enable or disable "add to basket" functionality, values: true, false
            basketBtnX: '@',    //x-axis position of the basket button
            basketBtnY: '@',    //y-axis position of the basket button

            embeddable: '@',    //enable or disabled the embedding of the component
            embedBtnX: '@',     //x-axis position of the embed button
            embedBtnY: '@',     //y-axis position of the embed button
            popoverPos: '@'     //the side of the embed button from which the embed information window will appear
        },
        templateUrl: ((typeof Drupal != 'undefined')? Drupal.settings.basePath  + Drupal.settings.yds_project.modulePath  +'/' :'') + 'templates/bar.html',
        link: function (scope, element, attrs) {
            var barContainer = angular.element(element[0].querySelector('.bar-container'));

            //create a random id for the element that will render the chart
            var elementId = "bar" + Data.createRandomId();
            barContainer[0].id = elementId;

            var projectId = scope.projectId;
            var viewType = scope.viewType;
            var lang = scope.lang;
            var useCountriesService = scope.useCountriesService;
            var titleX = scope.titleX;
            var titleY = scope.titleY;
            var showLabelsX = scope.showLabelsX;
            var showLabelsY = scope.showLabelsY;
            var showLegend = scope.showLegend;
            var exporting = scope.exporting;
            var elementH = scope.elementH;
            var titleSize = scope.titleSize;

            //check if the projectId and the viewType attr is defined, else stop the process
            if (useCountriesService != "true" && (_.isUndefined(projectId) || projectId.trim()=="")) {
                scope.ydsAlert = "The YDS component is not properly configured. " +
                    "Please check the corresponding documentation section.";
                return false;
            }

            //check if view-type attribute is empty and assign the default value
            if(_.isUndefined(viewType) || viewType.trim()=="")
                viewType = "default";

            //check if the language attr is defined, else assign default value
            if(_.isUndefined(lang) || lang.trim()=="")
                lang = "en";

            //check if the useCountriesService attr is defined, else assign default value
            if (_.isUndefined(useCountriesService) || useCountriesService.trim()=="")
                useCountriesService = "false";

            //check if the x-axis title attr is defined, else assign the default value
            if(_.isUndefined(titleX) || titleX.length==0)
                titleX = "";

            //check if the y-axis title attr is defined, else assign the default value
            if(_.isUndefined(titleY) || titleY.length==0)
                titleY = "";

            //check if the x-axis showLabels attr is defined, else assign default value
            if(_.isUndefined(showLabelsX) || (showLabelsX!="true" && showLabelsX!="false"))
                showLabelsX = "true";

            //check if the y-axis showLabels attr is defined, else assign default value
            if(_.isUndefined(showLabelsY) || (showLabelsY!="true" && showLabelsY!="false"))
                showLabelsY = "true";

            //check if the showLegend attr is defined, else assign default value
            if(_.isUndefined(showLegend) || (showLegend!="true" && showLegend!="false"))
                showLegend = "true";

            //check if the exporting attr is defined, else assign default value
            if(_.isUndefined(exporting) || (exporting!="true" && exporting!="false"))
                exporting = "true";

            //check if the component's height attr is defined, else assign default value
            if(_.isUndefined(elementH) || _.isNaN(elementH))
                elementH = 200;

            //check if the component's title size attr is defined, else assign default value
            if(_.isUndefined(titleSize) || _.isNaN(titleSize))
                titleSize = 18;

            //set the height of the chart
            barContainer[0].style.height = elementH + 'px';

            var chart = {};

            var visualizeBar = function (response) {
                var barData = response.data.data;
                var barCategories = response.data.categories;
                var barTitleAttr = _.first(response.view).attribute;
                var barTitle = Data.deepObjSearch(response.data, barTitleAttr);

                //check if the component is properly rendered
                if (_.isUndefined(barData) || !_.isArray(barData) || _.isUndefined(barCategories)) {
                    scope.ydsAlert = "The YDS component is not properly configured. " +
                        "Please check the corresponding documentation section.";
                    return false;
                }

                var options = {
                    chart: {
                        type: 'column',
                        renderTo: elementId
                    },
                    title: {
                        text: barTitle,
                        style: {
                            fontSize: titleSize + "px"
                        }
                    },
                    xAxis: {
                        categories: barCategories,
                        crosshair: true,
                        title : { text: titleX },
                        labels: { enabled: (showLabelsX === "true") }
                    },
                    yAxis: {
                        title : { text: titleY },
                        labels: { enabled: (showLabelsY === "true") }
                    },
                    legend: { enabled: (showLegend === "true") },
                    exporting: { enabled: (exporting === "true") },
                    tooltip: {
                        headerFormat: '{point.key}
',
                        pointFormat: '
{series.name}: 	' +
                        '{point.y:.0f}
',
                        footerFormat: '
',
                        shared: true,
                        useHTML: true
                    },
                    plotOptions: {
                        column: {
                            pointPadding: 0.2,
                            borderWidth: 0
                        }
                    },
                    series: barData
                };

                if (!_.isEmpty(chart) && useCountriesService == "true") {
                    // Chart exists, update its data
                    if (_.isEmpty(barCategories)) {
                        // New data is empty, destroy the chart
                        chart.destroy();
                    } else {
                        // New data is not empty, update the bar chart
                        chart.xAxis[0].setCategories(barCategories);
                        chart.series[0].setData(barData[0].data);
                    }
                } else {
                    // Chart is being created for the first time, create normally
                    chart = new Highcharts.Chart(options);
                }
            };

            var visualizeBarError = function (error) {
                if (error==null || _.isUndefined(error) || _.isUndefined(error.message))
                    scope.ydsAlert = "An error was occurred, please check the configuration of the component";
                else
                    scope.ydsAlert = error.message;
            };

            /**
             * Gets selected countries from the CountrySelectionService and formats them like a server response
             * from the API so that visualizePie() can read it correctly
             * @returns {{data: {data: *, series: string, title: string}, view: *[]}}
             */
            var getCountrySelectionServiceData = function() {
                var data = CountrySelectionService.getCountries();

                return {
                    data: {
                        data: [{
                            name: "Value",
                            data: _.pluck(data, "value")
                        }],
                        categories: _.pluck(data, "name"),
                        title: null
                    },
                    view: [{
                        attribute: "title"
                    }]
                };
            };

            if (useCountriesService == "true") {
                // Create chart with data from country service
                var selectedCountryData = getCountrySelectionServiceData();
                if (!_.isEmpty(selectedCountryData.data.data)) {
                    visualizeBar(selectedCountryData);
                }

                // Subscribe to be notified of country selection changes to update chart
                CountrySelectionService.subscribe(scope, function() {
                    visualizeBar(getCountrySelectionServiceData());
                });
            } else {
                Data.getProjectVis("bar", projectId, viewType, lang)
                    .then(visualizeBar, visualizeBarError);
            }
        }
    };
}]);<commit_msg>Prevent bar chart creating the chart with empty data in Dashboard<commit_after>angular.module('yds').directive('ydsBar', ['Data', 'CountrySelectionService', function(Data, CountrySelectionService){
    return {
        restrict: 'E',
        scope: {
            projectId: '@',     //id of the project that the data belong
            viewType: '@',     //name of the array that contains the visualised data
            lang: '@',          //lang of the visualised data

            useCountriesService: '@',  // if true will use selected countries service to load data instead of API

            titleX: '@',        //the text of the X-axis title
            titleY: '@',        //the text of the Y-axis title
            showLabelsX: '@',   //show or hide the X-axis label
            showLabelsY: '@',   //show or hide the Y-axis label
            showLegend: '@',    //enable or disable the chart's legend
            exporting: '@',     //enable or disable the export of the chart
            elementH: '@',      //set the height of the component
            titleSize: '@',     //the size of the chart's main title

            addToBasket: '@',   //enable or disable "add to basket" functionality, values: true, false
            basketBtnX: '@',    //x-axis position of the basket button
            basketBtnY: '@',    //y-axis position of the basket button

            embeddable: '@',    //enable or disabled the embedding of the component
            embedBtnX: '@',     //x-axis position of the embed button
            embedBtnY: '@',     //y-axis position of the embed button
            popoverPos: '@'     //the side of the embed button from which the embed information window will appear
        },
        templateUrl: ((typeof Drupal != 'undefined')? Drupal.settings.basePath  + Drupal.settings.yds_project.modulePath  +'/' :'') + 'templates/bar.html',
        link: function (scope, element, attrs) {
            var barContainer = angular.element(element[0].querySelector('.bar-container'));

            //create a random id for the element that will render the chart
            var elementId = "bar" + Data.createRandomId();
            barContainer[0].id = elementId;

            var projectId = scope.projectId;
            var viewType = scope.viewType;
            var lang = scope.lang;
            var useCountriesService = scope.useCountriesService;
            var titleX = scope.titleX;
            var titleY = scope.titleY;
            var showLabelsX = scope.showLabelsX;
            var showLabelsY = scope.showLabelsY;
            var showLegend = scope.showLegend;
            var exporting = scope.exporting;
            var elementH = scope.elementH;
            var titleSize = scope.titleSize;

            //check if the projectId and the viewType attr is defined, else stop the process
            if (useCountriesService != "true" && (_.isUndefined(projectId) || projectId.trim()=="")) {
                scope.ydsAlert = "The YDS component is not properly configured. " +
                    "Please check the corresponding documentation section.";
                return false;
            }

            //check if view-type attribute is empty and assign the default value
            if(_.isUndefined(viewType) || viewType.trim()=="")
                viewType = "default";

            //check if the language attr is defined, else assign default value
            if(_.isUndefined(lang) || lang.trim()=="")
                lang = "en";

            //check if the useCountriesService attr is defined, else assign default value
            if (_.isUndefined(useCountriesService) || useCountriesService.trim()=="")
                useCountriesService = "false";

            //check if the x-axis title attr is defined, else assign the default value
            if(_.isUndefined(titleX) || titleX.length==0)
                titleX = "";

            //check if the y-axis title attr is defined, else assign the default value
            if(_.isUndefined(titleY) || titleY.length==0)
                titleY = "";

            //check if the x-axis showLabels attr is defined, else assign default value
            if(_.isUndefined(showLabelsX) || (showLabelsX!="true" && showLabelsX!="false"))
                showLabelsX = "true";

            //check if the y-axis showLabels attr is defined, else assign default value
            if(_.isUndefined(showLabelsY) || (showLabelsY!="true" && showLabelsY!="false"))
                showLabelsY = "true";

            //check if the showLegend attr is defined, else assign default value
            if(_.isUndefined(showLegend) || (showLegend!="true" && showLegend!="false"))
                showLegend = "true";

            //check if the exporting attr is defined, else assign default value
            if(_.isUndefined(exporting) || (exporting!="true" && exporting!="false"))
                exporting = "true";

            //check if the component's height attr is defined, else assign default value
            if(_.isUndefined(elementH) || _.isNaN(elementH))
                elementH = 200;

            //check if the component's title size attr is defined, else assign default value
            if(_.isUndefined(titleSize) || _.isNaN(titleSize))
                titleSize = 18;

            //set the height of the chart
            barContainer[0].style.height = elementH + 'px';

            var chart = {};

            var visualizeBar = function (response) {
                var barData = response.data.data;
                var barCategories = response.data.categories;
                var barTitleAttr = _.first(response.view).attribute;
                var barTitle = Data.deepObjSearch(response.data, barTitleAttr);

                //check if the component is properly rendered
                if (_.isUndefined(barData) || !_.isArray(barData) || _.isUndefined(barCategories)) {
                    scope.ydsAlert = "The YDS component is not properly configured. " +
                        "Please check the corresponding documentation section.";
                    return false;
                }

                var options = {
                    chart: {
                        type: 'column',
                        renderTo: elementId
                    },
                    title: {
                        text: barTitle,
                        style: {
                            fontSize: titleSize + "px"
                        }
                    },
                    xAxis: {
                        categories: barCategories,
                        crosshair: true,
                        title : { text: titleX },
                        labels: { enabled: (showLabelsX === "true") }
                    },
                    yAxis: {
                        title : { text: titleY },
                        labels: { enabled: (showLabelsY === "true") }
                    },
                    legend: { enabled: (showLegend === "true") },
                    exporting: { enabled: (exporting === "true") },
                    tooltip: {
                        headerFormat: '{point.key}
',
                        pointFormat: '
{series.name}: 	' +
                        '{point.y:.0f}
',
                        footerFormat: '
',
                        shared: true,
                        useHTML: true
                    },
                    plotOptions: {
                        column: {
                            pointPadding: 0.2,
                            borderWidth: 0
                        }
                    },
                    series: barData
                };

                if (!_.isEmpty(chart) && useCountriesService == "true") {
                    // Chart exists, update its data
                    if (_.isEmpty(barCategories)) {
                        // New data is empty, destroy the chart
                        chart.destroy();
                    } else {
                        // New data is not empty, update the bar chart
                        chart.xAxis[0].setCategories(barCategories);
                        chart.series[0].setData(barData[0].data);
                    }
                } else {
                    // Chart is being created for the first time, create normally
                    chart = new Highcharts.Chart(options);
                }
            };

            var visualizeBarError = function (error) {
                if (error==null || _.isUndefined(error) || _.isUndefined(error.message))
                    scope.ydsAlert = "An error was occurred, please check the configuration of the component";
                else
                    scope.ydsAlert = error.message;
            };

            /**
             * Gets selected countries from the CountrySelectionService and formats them like a server response
             * from the API so that visualizePie() can read it correctly
             * @returns {{data: {data: *, series: string, title: string}, view: *[]}}
             */
            var getCountrySelectionServiceData = function() {
                var data = CountrySelectionService.getCountries();

                return {
                    data: {
                        data: [{
                            name: "Value",
                            data: _.pluck(data, "value")
                        }],
                        categories: _.pluck(data, "name"),
                        title: null
                    },
                    view: [{
                        attribute: "title"
                    }]
                };
            };

            if (useCountriesService == "true") {
                // Create chart with data from country service
                var selectedCountryData = getCountrySelectionServiceData();
                if (!_.isEmpty(selectedCountryData.data.categories)) {
                    visualizeBar(selectedCountryData);
                }

                // Subscribe to be notified of country selection changes to update chart
                CountrySelectionService.subscribe(scope, function() {
                    visualizeBar(getCountrySelectionServiceData());
                });
            } else {
                Data.getProjectVis("bar", projectId, viewType, lang)
                    .then(visualizeBar, visualizeBarError);
            }
        }
    };
}]);<|endoftext|>


<commit_before>angular.module("omniControllers")
	.controller("ExchangePendingController",["$scope", "$http", "$q", "hashExplorer",
		function ExchangePendingController($scope, $http, $q, hashExplorer) {
		  $scope.setHashExplorer = hashExplorer.setHash.bind(hashExplorer)
		  //$scope.selectedAddress = $scope.wallet.addresses[ $scope.wallet.addresses.length-1 ].address;
		  $scope.currencyUnit = 'stom'
		  $scope.pendingThinking = true
		  $scope.hasAddressesWithPrivkey = $scope.wallet.addresses.filter(function(address){
		    return address.privkey && address.privkey.length == 58
		  }).map(function(e){
		          return e.address;
		        });
		  $scope.selectedAddress = $scope.hasAddressesWithPrivkey[0];
		  $scope.wallet.assets.filter(function(currency){
		       return currency.tradable;
		  }).forEach(function(coin){
		    if(coin.symbol=='BTC'){
		      $scope.selectedCoin = coin;
		    }
		  });

		  //Get All data
		  $scope.timeNow = Date.now();
		  $scope.selectedTimeframe = $scope.timeNow - 1394834400000;
		  //$scope.selectedTimeframe = "604800"
		  $scope.filterData = function(time) {
		    var orderbook = JSON.parse($scope.orderBookStorage);

		    var now = Date.now()
		    var filtered_transaction_data = orderbook.filter(function(item) {
		      console.log('time2', +item.tx_time, '>= ?', (now - (+time)))
		      return true //(+item.tx_time) <= (now - (+time) )
		    });
		    $scope.orderbook = filtered_transaction_data;
		  }
		  $scope.getData = function(time) {
		    $scope.orderbook = []
		    var transaction_data = []
		    var postData = {
		      type: 'ADDRESS',
		      currencyType: 'BOTH',
		      address: JSON.stringify($scope.hasAddressesWithPrivkey),
		      offerType: 'BOTH'
		    };
		    $http.post('/v1/exchange/offers', postData).success(function(offerSuccess) {
		      console.log(offerSuccess, ' ofsec');

		      //capture data
		      var nestedData = offerSuccess.data,
		        nestedLevels = 0,
		        capturedData = [];
		      while (typeof nestedData == 'object' && nestedLevels < 5) {
		        var savedData = []
		        if (nestedData instanceof Object && !(nestedData instanceof Array)) { //DEBUG console.log('got obj', nestedData);
		          var data_keys = Object.keys(nestedData)
		          data_keys.forEach(function(key) {
		            savedData = savedData.concat(nestedData[key])
		          });
		        }
		        if (nestedData instanceof Array) { //DEBUG console.log('got arr', nestedData);
		          var arrayOfObjects = []
		          nestedData.forEach(function(elem) {
		            if (elem instanceof Array || !(elem instanceof Object))
		              capturedData.push(elem)
		            else if (elem instanceof Object && !(elem instanceof Array)) { //DEBUG console.log('got obj', elem);
		              var elem_keys = Object.keys(elem)
		              elem_keys.forEach(function(key) { //DEBUG console.log('got item', typeof elem[key])
		                if (typeof elem[key] == 'object' && key != 'invalid')
		                  arrayOfObjects = arrayOfObjects.concat(elem[key])
		              });
		              //DEBUG console.log('check len', arrayOfObjects.length)
		              if (arrayOfObjects.length == 0)
		                capturedData.push(elem)
		            }
		          });
		          savedData = arrayOfObjects
		        }
		        //console.log('nesteddata orig', nestedData, 'data saved', savedData)
		        nestedData = savedData
		        nestedLevels++
		      }

		      transaction_data = capturedData;
		      transaction_data.forEach(function(tx) {
		        if (tx != "ADDRESS_NOT_FOUND") {
		          transaction_data_keys = ['formatted_amount', 'formatted_amount_available',
		            'formatted_bitcoin_amount_desired', 'formatted_fee_required', 'formatted_price_per_coin', 'bitcoin_required'];
		          transaction_data_keys.forEach(function(key) {
		            tx[key] = tx[key];
		          });
		        }
		      });

		      var filtered_transaction_data = transaction_data.filter(function(item) {
		        //console.log('stf', item, typeof item != 'string', 'inv', item.invalid == false && item.invalid.length == undefined)
		        return (typeof item == 'object' && (item.invalid == false && item.invalid.length == undefined))
		      });

		      //DEBUG console.log(filtered_transaction_data, 'tettst')
		      //DEBUG console.log('filtered tx data, pending offers',filtered_transaction_data)

		      $scope.filtered_buys = filtered_transaction_data.filter(function(item) {
		        var orderType = item.tx_type_str.toLowerCase()
		        var orderStatus = item.status ? item.status.toLowerCase() : undefined;
		        //DEBUG console.log(item.tx_type_str, item.status, orderStatus)
		        return (orderType == 'sell accept') && (orderStatus != 'expired') && (orderStatus != 'closed')
		      });

		      $scope.filtered_sells = filtered_transaction_data.filter(function(item) {
		        var orderType = item.tx_type_str.toLowerCase()
		        var orderStatus = item.color.match(/(bgc-done|expired|invalid)/gi) || []
		        //DEBUG console.log(orderStatus, item.color)
		        return (orderType == 'sell offer') && (orderStatus.length == 0)
		      });

		      angular.forEach(filtered_transaction_data, function(transaction, index) {
		        //DEBUG console.log(new Date(Number(transaction.tx_time)))
		        filtered_transaction_data[index].tx_hash_concat = transaction.tx_hash.substring(0, 22) + '...';
		      });

		      transaction_data = filtered_transaction_data;
		      //if null, then append simple message
		      $scope.orderbook = transaction_data.length != 0 ? transaction_data : [{
		            tx_hash: 'No offers/bids found for this timeframe'
		          }];

		      //store around for filtering
		      $scope.orderBookStorage = JSON.stringify($scope.orderbook);
		    });
		  };
		  $scope.purchaseCoin = function(tx) {
		    $scope.pendingThinking = false;
		    $scope.buyTransaction = tx;
		    $scope.sendTo = tx.to_address;
		    $scope.sendAmount = tx.bitcoin_required;
		    $scope.selectedAddress = $scope.wallet.getAddress(tx.from_address);
		    $scope.selectedAsset = $scope.wallet.getAsset(0);
		    $scope.minersFee= new Big(tx.formatted_fee_required);
		    $http.get('/v1/transaction/tx/' + tx.sell_offer_txid + '.json').success(function(data) {
		      var sell_tx = data[0];
		      $http.post('/v1/blocks/getlast',{origin:"blockchain"}).success(function(block){
		        $scope.remainingBlocks = sell_tx.formatted_block_time_limit - (block.height - tx.block);
		      });
		    });
		  };

		  $scope.isCancel=true;
		  $scope.confirmCancel = function(tx) {
		    $scope.selectedAddress = tx.from_address;
		    $scope.selectedCoin_extra = (+tx.currencyId) == 1 ? 'MSC' : 'TMSC';
		    $scope.cancelTrig=!$scope.cancelTrig;
		  }
		}])<commit_msg>Fix missmatched property name<commit_after>angular.module("omniControllers")
	.controller("ExchangePendingController",["$scope", "$http", "$q", "hashExplorer",
		function ExchangePendingController($scope, $http, $q, hashExplorer) {
		  $scope.setHashExplorer = hashExplorer.setHash.bind(hashExplorer)
		  //$scope.selectedAddress = $scope.wallet.addresses[ $scope.wallet.addresses.length-1 ].address;
		  $scope.currencyUnit = 'stom'
		  $scope.pendingThinking = true
		  $scope.hasAddressesWithPrivkey = $scope.wallet.addresses.filter(function(address){
		    return address.privkey && address.privkey.length == 58
		  }).map(function(e){
		          return e.hash;
		        });
		  $scope.selectedAddress = $scope.hasAddressesWithPrivkey[0];
		  $scope.wallet.assets.filter(function(currency){
		       return currency.tradable;
		  }).forEach(function(coin){
		    if(coin.symbol=='BTC'){
		      $scope.selectedCoin = coin;
		    }
		  });

		  //Get All data
		  $scope.timeNow = Date.now();
		  $scope.selectedTimeframe = $scope.timeNow - 1394834400000;
		  //$scope.selectedTimeframe = "604800"
		  $scope.filterData = function(time) {
		    var orderbook = JSON.parse($scope.orderBookStorage);

		    var now = Date.now()
		    var filtered_transaction_data = orderbook.filter(function(item) {
		      console.log('time2', +item.tx_time, '>= ?', (now - (+time)))
		      return true //(+item.tx_time) <= (now - (+time) )
		    });
		    $scope.orderbook = filtered_transaction_data;
		  }
		  $scope.getData = function(time) {
		    $scope.orderbook = []
		    var transaction_data = []
		    var postData = {
		      type: 'ADDRESS',
		      currencyType: 'BOTH',
		      address: JSON.stringify($scope.hasAddressesWithPrivkey),
		      offerType: 'BOTH'
		    };
		    $http.post('/v1/exchange/offers', postData).success(function(offerSuccess) {
		      console.log(offerSuccess, ' ofsec');

		      //capture data
		      var nestedData = offerSuccess.data,
		        nestedLevels = 0,
		        capturedData = [];
		      while (typeof nestedData == 'object' && nestedLevels < 5) {
		        var savedData = []
		        if (nestedData instanceof Object && !(nestedData instanceof Array)) { //DEBUG console.log('got obj', nestedData);
		          var data_keys = Object.keys(nestedData)
		          data_keys.forEach(function(key) {
		            savedData = savedData.concat(nestedData[key])
		          });
		        }
		        if (nestedData instanceof Array) { //DEBUG console.log('got arr', nestedData);
		          var arrayOfObjects = []
		          nestedData.forEach(function(elem) {
		            if (elem instanceof Array || !(elem instanceof Object))
		              capturedData.push(elem)
		            else if (elem instanceof Object && !(elem instanceof Array)) { //DEBUG console.log('got obj', elem);
		              var elem_keys = Object.keys(elem)
		              elem_keys.forEach(function(key) { //DEBUG console.log('got item', typeof elem[key])
		                if (typeof elem[key] == 'object' && key != 'invalid')
		                  arrayOfObjects = arrayOfObjects.concat(elem[key])
		              });
		              //DEBUG console.log('check len', arrayOfObjects.length)
		              if (arrayOfObjects.length == 0)
		                capturedData.push(elem)
		            }
		          });
		          savedData = arrayOfObjects
		        }
		        //console.log('nesteddata orig', nestedData, 'data saved', savedData)
		        nestedData = savedData
		        nestedLevels++
		      }

		      transaction_data = capturedData;
		      transaction_data.forEach(function(tx) {
		        if (tx != "ADDRESS_NOT_FOUND") {
		          transaction_data_keys = ['formatted_amount', 'formatted_amount_available',
		            'formatted_bitcoin_amount_desired', 'formatted_fee_required', 'formatted_price_per_coin', 'bitcoin_required'];
		          transaction_data_keys.forEach(function(key) {
		            tx[key] = tx[key];
		          });
		        }
		      });

		      var filtered_transaction_data = transaction_data.filter(function(item) {
		        //console.log('stf', item, typeof item != 'string', 'inv', item.invalid == false && item.invalid.length == undefined)
		        return (typeof item == 'object' && (item.invalid == false && item.invalid.length == undefined))
		      });

		      //DEBUG console.log(filtered_transaction_data, 'tettst')
		      //DEBUG console.log('filtered tx data, pending offers',filtered_transaction_data)

		      $scope.filtered_buys = filtered_transaction_data.filter(function(item) {
		        var orderType = item.tx_type_str.toLowerCase()
		        var orderStatus = item.status ? item.status.toLowerCase() : undefined;
		        //DEBUG console.log(item.tx_type_str, item.status, orderStatus)
		        return (orderType == 'sell accept') && (orderStatus != 'expired') && (orderStatus != 'closed')
		      });

		      $scope.filtered_sells = filtered_transaction_data.filter(function(item) {
		        var orderType = item.tx_type_str.toLowerCase()
		        var orderStatus = item.color.match(/(bgc-done|expired|invalid)/gi) || []
		        //DEBUG console.log(orderStatus, item.color)
		        return (orderType == 'sell offer') && (orderStatus.length == 0)
		      });

		      angular.forEach(filtered_transaction_data, function(transaction, index) {
		        //DEBUG console.log(new Date(Number(transaction.tx_time)))
		        filtered_transaction_data[index].tx_hash_concat = transaction.tx_hash.substring(0, 22) + '...';
		      });

		      transaction_data = filtered_transaction_data;
		      //if null, then append simple message
		      $scope.orderbook = transaction_data.length != 0 ? transaction_data : [{
		            tx_hash: 'No offers/bids found for this timeframe'
		          }];

		      //store around for filtering
		      $scope.orderBookStorage = JSON.stringify($scope.orderbook);
		    });
		  };
		  $scope.purchaseCoin = function(tx) {
		    $scope.pendingThinking = false;
		    $scope.buyTransaction = tx;
		    $scope.sendTo = tx.to_address;
		    $scope.sendAmount = tx.bitcoin_required;
		    $scope.selectedAddress = $scope.wallet.getAddress(tx.from_address);
		    $scope.selectedAsset = $scope.wallet.getAsset(0);
		    $scope.minersFee= new Big(tx.formatted_fee_required);
		    $http.get('/v1/transaction/tx/' + tx.sell_offer_txid + '.json').success(function(data) {
		      var sell_tx = data[0];
		      $http.post('/v1/blocks/getlast',{origin:"blockchain"}).success(function(block){
		        $scope.remainingBlocks = sell_tx.formatted_block_time_limit - (block.height - tx.block);
		      });
		    });
		  };

		  $scope.isCancel=true;
		  $scope.confirmCancel = function(tx) {
		    $scope.selectedAddress = tx.from_address;
		    $scope.selectedCoin_extra = (+tx.currencyId) == 1 ? 'MSC' : 'TMSC';
		    $scope.cancelTrig=!$scope.cancelTrig;
		  }
		}])<|endoftext|>


<commit_before>String.toLocaleString({
	"en": {
		"%title": "English - l10n.js demo",
		"%info": "You are viewing an English localization of this page."
	},
		"en-US": {
			"%title": "American English - l10n.js demo",
			"%info": "You are viewing an American English localization of this page."
		},
			"en-US-x-Hixie": {
				"%title": "American Hixie English - l10n.js demo",
				"%info": "You are viewing an American Hixie English localization of this page."
			},
		"en-GB": {
			"%title": "British English - l10n.js demo",
			"%info": "You are viewing a British English localisation of this page."
		},
			"en-GB-x-Hixie": {
				"%title": "British Hixie English - l10n.js demo",
				"%info": "You are viewing a British Hixie English localisation of this page."
			},
		"en-CA": {
			"%title": "Canadian English - l10n.js demo",
			"%info": "You are viewing a Canadian English localization of this page."
		},
			"en-CA-x-Hixie": {
					"%title": "Canadian Hixie English - l10n.js demo",
					"%info": "You are viewing a Canadian Hixie English localization of this page."
			},
		"en-AU": {
			"%title": "Australian English - l10n.js demo",
			"%info": "You are viewing an Australian English localisation of this page."
		},
			"en-AU-x-Hixie": {
				"%title": "Australian Hixie English - l10n.js demo",
				"%info": "You are viewing an Australian Hixie English localisation of this page."
			},
	"pt": {
		"%title": "Português - Demo do l10n.js",
		"%info": "Você está vendo uma localização em português desta página."
	},
	"es": {
		"%title": "Español - l10n.js demo",
		"%info": "Usted está viendo una versión en español de esta página."
	},
	"fr": {
		"%title": "Français - Démo de l10n.js",
		"%info": "Vous lisez une localisation en français de cette page."
	},
	"nl": {
		"%title": "Nederlands - Demo van l10n.js",
		"%info": "U ziet nu een Nederlandse lokalisatie van deze pagina."
	},
	"de": {
		"%title": "Deutsch - l10n.js Demo",
		"%info": "Sie sehen hier die deutsche Lokalisierung dieser Seite."
	},
	"fi": {
		"%title": "Suomen kieli - l10n.js demo",
		"%info": "Katselet Suomeksi käännettyä versiota tästä sivusta"
	},
	"vi": {
		"%title": "Tiếng Việt - l10n.js demo",
		"%info": "Bạn đang xem trang bằng phiên bản tiếng Việt."
	},
	"it": {
		"%title": "Italiano - Demo di l10n.js",
		"%info": "Stai leggendo una localizzazione in Italiano di questa pagina."
	},
	"no": {
		"%title": "Norsk - Demo av l10n.js",
		"%info": "Du ser den norske oversettelsen av denne siden."
	},
	"ru": {
		"%title": "Русский - l10n.js демо",
		"%info": "Вы просматриваете Русскую версию этой страницы."
	},
	"jbo": {
		"%title": "la'o cme. l10n.js .cme mupli bau le jbobau",
		"%info": ".i do ca viska lo jbobau xe fanva be lo ti judrysni"
	},
	"da": {
		"%title": "Dansk. Demo af l10n.js",
		"%info": "Du ser den Danske oversættelse af denne side"
	},
	"he": {
		"%locale.dir": "rtl",
		"%title": "עברית - Demo do l10n.js",
		"%info": "אתה צופה בלוקליזציה לעברית של עמוד זה."
	},
	"bg": {
		"%title": "Български - демо на l10n.js",
		"%info": "В момента виждате българската версия на тази страница."
	},
	"zh": {
		"%title": "中文---l10n.js 演示",
		"%info": "你在浏览本页面的中文本地化版本。"
	},
	"se": {
		"%title": "Svenska - Demo av l10n.js",
		"%info": "Du tittar på den svenska översättningen av denna sida"
	}
});
<commit_msg>Removed Hixie English demo localizations<commit_after>String.toLocaleString({
	"en": {
		"%title": "English - l10n.js demo",
		"%info": "You are viewing an English localization of this page."
	},
		"en-US": {
			"%title": "American English - l10n.js demo",
			"%info": "You are viewing an American English localization of this page."
		},
		"en-GB": {
			"%title": "British English - l10n.js demo",
			"%info": "You are viewing a British English localisation of this page."
		},
		"en-CA": {
			"%title": "Canadian English - l10n.js demo",
			"%info": "You are viewing a Canadian English localization of this page."
		},
		"en-AU": {
			"%title": "Australian English - l10n.js demo",
			"%info": "You are viewing an Australian English localisation of this page."
		},
	"pt": {
		"%title": "Português - Demo do l10n.js",
		"%info": "Você está vendo uma localização em português desta página."
	},
	"es": {
		"%title": "Español - l10n.js demo",
		"%info": "Usted está viendo una versión en español de esta página."
	},
	"fr": {
		"%title": "Français - Démo de l10n.js",
		"%info": "Vous lisez une localisation en français de cette page."
	},
	"nl": {
		"%title": "Nederlands - Demo van l10n.js",
		"%info": "U ziet nu een Nederlandse lokalisatie van deze pagina."
	},
	"de": {
		"%title": "Deutsch - l10n.js Demo",
		"%info": "Sie sehen hier die deutsche Lokalisierung dieser Seite."
	},
	"fi": {
		"%title": "Suomen kieli - l10n.js demo",
		"%info": "Katselet Suomeksi käännettyä versiota tästä sivusta"
	},
	"vi": {
		"%title": "Tiếng Việt - l10n.js demo",
		"%info": "Bạn đang xem trang bằng phiên bản tiếng Việt."
	},
	"it": {
		"%title": "Italiano - Demo di l10n.js",
		"%info": "Stai leggendo una localizzazione in Italiano di questa pagina."
	},
	"no": {
		"%title": "Norsk - Demo av l10n.js",
		"%info": "Du ser den norske oversettelsen av denne siden."
	},
	"ru": {
		"%title": "Русский - l10n.js демо",
		"%info": "Вы просматриваете Русскую версию этой страницы."
	},
	"jbo": {
		"%title": "la'o cme. l10n.js .cme mupli bau le jbobau",
		"%info": ".i do ca viska lo jbobau xe fanva be lo ti judrysni"
	},
	"da": {
		"%title": "Dansk. Demo af l10n.js",
		"%info": "Du ser den Danske oversættelse af denne side"
	},
	"he": {
		"%locale.dir": "rtl",
		"%title": "עברית - Demo do l10n.js",
		"%info": "אתה צופה בלוקליזציה לעברית של עמוד זה."
	},
	"bg": {
		"%title": "Български - демо на l10n.js",
		"%info": "В момента виждате българската версия на тази страница."
	},
	"zh": {
		"%title": "中文---l10n.js 演示",
		"%info": "你在浏览本页面的中文本地化版本。"
	},
	"se": {
		"%title": "Svenska - Demo av l10n.js",
		"%info": "Du tittar på den svenska översättningen av denna sida"
	}
});
<|endoftext|>


<commit_before>// Set the Authorization header if we have an access token
module.exports = function(client, request, next){
  if(!request.headers['Authorization'] && client.accessToken){
    request.headers['Authorization'] = 'Bearer ' + client.accessToken;
  }
  next();
};<commit_msg>fix auth bug<commit_after>// Set the Authorization header if we have an access token
module.exports = function(client, request, next){
  if(!request.headers['Authorization'] && client.accessToken && request.isPlatform()){
    request.headers['Authorization'] = 'Bearer ' + client.accessToken;
  }
  next();
};<|endoftext|>


<commit_before>const bio = {
	name: 'David Villarreal',
	role: 'Software Engineer',
	email: 'steadypathapp@gmail.com',
	location: {city: 'Zapopan', state: 'Jalisco', country: 'Mexico'},

	profiles: {
		github: 'https://github.com/Phaze1D',
		codefights: 'https://codefights.com/profile/playssss',
		stackoverflow: 'http://stackoverflow.com/story/davidstory',
		linkedin: 'https://www.linkedin.com/in/david-villarreal-720ab5134/',
	},

	about: `
	Since I was a kid I have always loved to do 2 things, create and solve. I go into computers the moment my dad got one for his work and I immediately wanted to know how it worked in the hopes of building one myself. While research computers I came across the software side of things, which was a perfect fit for me, a way I could create and solve.
	`,

	images: ['https://avatars0.githubusercontent.com/u/8495952?v=3'],
}

export default function (command) {

	return bio
}
<commit_msg>Fixed bio grammar<commit_after>// TODO: Add a new section called personality talk about leading skills and ethics/values
const bio = {
	name: 'David Villarreal',
	role: 'Software Engineer',
	email: 'steadypathapp@gmail.com',
	location: {city: 'Zapopan', state: 'Jalisco', country: 'Mexico'},

	profiles: {
		github: 'https://github.com/Phaze1D',
		codefights: 'https://codefights.com/profile/playssss',
		stackoverflow: 'http://stackoverflow.com/story/davidstory',
		linkedin: 'https://www.linkedin.com/in/david-villarreal-720ab5134/',
	},

	about: `
	Since I was a kid I have always loved to do 2 things, create and solve. I got into computers the moment my dad bought one for his work and I immediately wanted to know how they worked in the hopes of building one myself. While researching computers I came across the software side of things, which was a perfect fit for me, a way I could create and solve.
	`,

	images: ['https://avatars0.githubusercontent.com/u/8495952?v=3'],
}

export default function (command) {

	return bio
}
<|endoftext|>


<commit_before>(function ( $ ) {
	$.fn.urlClickable = function () {
		var item = $(this);

		if (item.find(".isUrlClickable").length) {
			return this;
		}

		// Make links in citation clickable
		//===================
		var originalText = item.text().trim();
		var newText = originalText;
		var url;

		// Regular expression to find FTP, HTTP(S) and email URLs.
		var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

		var matchArray;
		// Extract the url
		while ((matchArray = regexToken.exec(originalText)) !== null) {
			if (matchArray[0].slice(-1) === "." || matchArray[0].slice(-1) === ",") {
				url = matchArray[0].slice(0, -1);
			}
			else
				url = matchArray[0];

			newText = newText.replace(url, "" + url + "")
		}
		$(this).html(newText);
	}
})( jQuery );

$(document).ready(function() {
	// Search box toggle
	// =================
	$('#search-btn').on('click', function() {
		$("#search-icon").toggleClass('fa-times margin-2');
		$("#search-box").toggleClass('display-block animated fadeInUp');
	});

	// Smooth scrolling for UI elements page
	// =====================================
	$(document).ready(function(){
	   $('a[href*=#buttons],a[href*=#panels], a[href*=#info-boards], a[href*=#navs], a[href*=#alerts], a[href*=#thumbnails], a[href*=#social], a[href*=#section-header],a[href*=#page-tip], a[href*=#block-header]').bind("click", function(e){
		  var anchor = $(this);
		  $('html, body').stop().animate({
			 scrollTop: $(anchor.attr('href')).offset().top
		  }, 1000);
		  e.preventDefault();
	   });
	   return false;
	});

	// 404 error page
	// ====================
	$('#search-404').on('click', function() {
		$("#smile").removeClass("fa-meh-o");
		$("#smile").addClass("fa-smile-o");
	});

	// Sign up popovers
	// ================
	$(function(){
		$('#exampleInputName1').popover();
	});

	$(function(){
		$('#exampleInputUsername1').popover();
	});

	$(function(){
		$('#exampleInputEmail1').popover();
	});

	$(function(){
		$('#exampleInputPassword1').popover();
	});

	$(function(){
		$('#exampleInputPassword2').popover();
	});

	// Profile - Status Update
	// =======================

	$('#update-status').on('click', function() {
		$(".user-status > p").toggleClass("show hidden");
		$(".user-status > form").toggleClass("hidden show");
		return false;
	});

	$('.user-status > form > button').on('click', function() {
		$(".user-status > p").toggleClass("show hidden");
		$(".user-status > form").toggleClass("hidden show");
		return false;
	});

	// Lost password form
	//===================

	$('.pwd-lost > .pwd-lost-q > a').on('click', function() {
		$(".pwd-lost > .pwd-lost-q").toggleClass("show hidden");
		$(".pwd-lost > .pwd-lost-f").toggleClass("hidden show");
		return false;
	});

    // Restyle keywords field
	//===================
    var keywords = $("#keywords").text().split(",");
    var list = $("#list-keywords");
    for (var i = 0; i < keywords.length; i++){
        if (keywords[i]){
           var li = $("

");
            li.find('a').text(keywords[i]);
            list.append(li);
        }
    }

    $("#keywords").remove();

	$(".url-clickable").each(function () {
		$(this).urlClickable();
	});

    // if ($("#citation-text").length > 0){
    //     // Make links in citation clickable
    //     //===================
    //     var oriCitationText = $("#citation-text").text();
    //     var newCitationText = oriCitationText;
    //     var citationUrl;
    //
    //     // Regular expression to find FTP, HTTP(S) and email URLs.
    //     var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;
    //
    //     var matchArray;
    //     // Extract the url
    //     while( (matchArray = regexToken.exec(oriCitationText)) !== null ){
    //         if (matchArray[0].slice(-1) === "." || matchArray[0].slice(-1) === ",") {
    //             citationUrl = matchArray[0].slice(0, -1);
    //         }
    //         else
    //             citationUrl = matchArray[0];
    //
    //         newCitationText = newCitationText.replace(citationUrl, "" + citationUrl + "")
    //     }
    //     $("#citation-text").html(newCitationText);
    // }

    // Make apps link open in new tab
    $('a[href^="https://appsdev.hydroshare.org/apps"]').attr('target', '_blank');
});
<commit_msg>code cleanup<commit_after>(function ( $ ) {
	$.fn.urlClickable = function () {
		var item = $(this);

		if (item.find(".isUrlClickable").length) {
			return this;
		}

		// Make links in citation clickable
		//===================
		var originalText = item.text().trim();
		var newText = originalText;
		var url;

		// Regular expression to find FTP, HTTP(S) and email URLs.
		var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

		var matchArray;
		// Extract the url
		while ((matchArray = regexToken.exec(originalText)) !== null) {
			if (matchArray[0].slice(-1) === "." || matchArray[0].slice(-1) === ",") {
				url = matchArray[0].slice(0, -1);
			}
			else
				url = matchArray[0];

			newText = newText.replace(url, "" + url + "")
		}
		$(this).html(newText);
	}
})( jQuery );

$(document).ready(function() {
	// Search box toggle
	// =================
	$('#search-btn').on('click', function() {
		$("#search-icon").toggleClass('fa-times margin-2');
		$("#search-box").toggleClass('display-block animated fadeInUp');
	});

	// Smooth scrolling for UI elements page
	// =====================================
	$(document).ready(function(){
	   $('a[href*=#buttons],a[href*=#panels], a[href*=#info-boards], a[href*=#navs], a[href*=#alerts], a[href*=#thumbnails], a[href*=#social], a[href*=#section-header],a[href*=#page-tip], a[href*=#block-header]').bind("click", function(e){
		  var anchor = $(this);
		  $('html, body').stop().animate({
			 scrollTop: $(anchor.attr('href')).offset().top
		  }, 1000);
		  e.preventDefault();
	   });
	   return false;
	});

	// 404 error page
	// ====================
	$('#search-404').on('click', function() {
		$("#smile").removeClass("fa-meh-o");
		$("#smile").addClass("fa-smile-o");
	});

	// Sign up popovers
	// ================
	$(function(){
		$('#exampleInputName1').popover();
	});

	$(function(){
		$('#exampleInputUsername1').popover();
	});

	$(function(){
		$('#exampleInputEmail1').popover();
	});

	$(function(){
		$('#exampleInputPassword1').popover();
	});

	$(function(){
		$('#exampleInputPassword2').popover();
	});

	// Profile - Status Update
	// =======================

	$('#update-status').on('click', function() {
		$(".user-status > p").toggleClass("show hidden");
		$(".user-status > form").toggleClass("hidden show");
		return false;
	});

	$('.user-status > form > button').on('click', function() {
		$(".user-status > p").toggleClass("show hidden");
		$(".user-status > form").toggleClass("hidden show");
		return false;
	});

	// Lost password form
	//===================

	$('.pwd-lost > .pwd-lost-q > a').on('click', function() {
		$(".pwd-lost > .pwd-lost-q").toggleClass("show hidden");
		$(".pwd-lost > .pwd-lost-f").toggleClass("hidden show");
		return false;
	});

    // Restyle keywords field
	//===================
    var keywords = $("#keywords").text().split(",");
    var list = $("#list-keywords");
    for (var i = 0; i < keywords.length; i++){
        if (keywords[i]){
           var li = $("

");
            li.find('a').text(keywords[i]);
            list.append(li);
        }
    }

    $("#keywords").remove();

	// Make URLs inside text clickable
	$(".url-clickable").each(function () {
		$(this).urlClickable();
	});

    // Make apps link open in new tab
    $('a[href^="https://appsdev.hydroshare.org/apps"]').attr('target', '_blank');
});
<|endoftext|>


<commit_before>var app = angular.module('object-table', ['messages']);

/**
  * Initiate object table data for the controller.
 */
function get_object_table() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/get_object_table').then(
    function (response) {

      //Store data in constant called items
      app.constant('items', response.data);

      //Init the controller
      angular.bootstrap(document, ['object-table']);
    }
  );
}

app.controller('ObjectTableCtrl', function ($scope, $http, items, MessagesHandler) {

  //This function is called after angular.element is finished.
  $scope.folders = items.folders;
  $scope.objects = items.objects;
  $scope.container = items.container;

  $scope.$on('onRepeatLast', function () {
    app.applyTableEvents();
  });

  function refreshObjectTable() {
    $http.get('/get_object_table').then(
      function (response) {
        $scope.folders = response.data.folders;
      }
    );
  }
  $scope.refreshObjectTable = refreshObjectTable;

  // Provide upload_form.js access to internal function
  $scope.$on("refreshObjectTable", function () {
    refreshObjectTable();
  });

  // Provide upload_form.js access to internal function
  $scope.MessagesHandler = MessagesHandler;

})

  //Controller for new folder form.
  .controller('CreateFolderCtrl', function ($scope, $http, $rootScope, items) {

    $scope.showForm = 1; /* Variable for toggling the form after submission. */
    $scope.showLoader = 0; /* Variable for toggling the loader. */
    $scope.formData = {}; /* Holder for form data. */
    var create_folder_url = "/create_pseudofolder/" + items.container + "/";

    //Add prefix for new folders that will be in existing folders.
    if (items.folder_prefix) {
      create_folder_url += items.folder_prefix;
    }

    //Handler for submiting new folder form.
    $scope.createFolder = function () {

      //Display loading image
      $scope.showForm = 0;
      $scope.showLoader = 1;

      //Submit the form
      $http({
        method  : 'POST',
        url     : create_folder_url,
        data    : $.param($scope.formData),  // pass in data as strings
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
      })
        .success(function () {

          $('#pseudoContainer').foundation('reveal', 'close');
          $rootScope.$broadcast('refreshObjectTable');
          $scope.showForm = 1;
          $scope.showLoader = 0;
          $scope.formData.foldername = "";
        })
        .error(function () {
          //TODO: Display error message
          console.log($scope.formData);
        });
    };
  })

  //Filter to display the file size in a compact way. Ex. 3GB or 100Bytes
  .filter('formatByte', function () {
    'use strict';

    return function (size) {
      var exp = Math.log(size) / Math.log(1024);
      if (exp < 1) {
        exp = 0;
      }
      return (size / Math.pow(1024, exp)).toFixed(1) + ' ' +
        ((exp > 0) ? 'KMGTPEZY'[exp - 1] + 'B' : 'Bytes');
    };
  })

  /*
  Format the pseudo folder:
    from "folder/name/"
    to "name"
  */
  .filter('formatPseudoFolder', function () {
    'use strict';

    return function (string) {

      var stripped = string.substring(0, string.length - 1);
      var split = stripped.split("/");
      return split[split.length - 1];
    };
  })

  //Event for when last row in object table has been rendered.
  .directive('onLastRepeat', function () {
    return function (scope, element, attrs) {
      if (scope.$last) {
        setTimeout(function () {
          scope.$emit('onRepeatLast', element, attrs);
        }, 1);
      }
    };
  })

  .directive('ngUpdateHidden', function () {
    return function (scope, el, attr) {
      var model = attr.ngModel;
      scope.$watch(model, function (nv) {
        el.val(nv);
      });
    };
  });

/* Added in for CSRF support. */
app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.post['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();
});

angular.element(document).ready(get_object_table);

/*
TODO: replace with loader angular logic
    Display the loader in the object table.
*/
function showLoader() {

  $('#objecttable').html(
    '
' +
      '
Loading...
' +
      '
'
  );
}

/*
    After a table is loaded, new events need to be applied to the page.
*/
app.applyTableEvents = function () {

  //Re-apply foundation
  $(document).foundation();

  //Reapply dismiss of alert boxes
  $(".alert-box").click(function () {
    $(this).slideUp();
  });

  //Delete object binding.
  $("a.delete-object").on("click", function (e) {
    //Prompt user to confirm.
    /*global confirm: true*/
    if (confirm("Are you sure you want to delete " + $(this).attr("data-name") + "?")) {
      showLoader();
      $("#progress").show();
    } else {
      e.preventDefault();
    }
  });

  //Delete folder binding.
  $("a.delete-folder").on("click", function (e) {

    if (confirm("Are you sure you want to delete " + $(this).attr("data-name") + "?")) {
      if (confirm("This will delete " + $(this).attr("data-name") + " and all it's contents. Are you sure?")) {
        showLoader();
        $("#progress").show();
      } else {
        e.preventDefault();
      }
    } else {
      e.preventDefault();
    }
  });
};
<commit_msg>Refresh objects on succcessful uploads.<commit_after>var app = angular.module('object-table', ['messages']);

/**
  * Initiate object table data for the controller.
 */
function get_object_table() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/get_object_table').then(
    function (response) {

      //Store data in constant called items
      app.constant('items', response.data);

      //Init the controller
      angular.bootstrap(document, ['object-table']);
    }
  );
}

app.controller('ObjectTableCtrl', function ($scope, $http, items, MessagesHandler) {

  //This function is called after angular.element is finished.
  $scope.folders = items.folders;
  $scope.objects = items.objects;
  $scope.container = items.container;

  $scope.$on('onRepeatLast', function () {
    app.applyTableEvents();
  });

  function refreshObjectTable() {
    $http.get('/get_object_table').then(
      function (response) {
        $scope.folders = response.data.folders;
        $scope.objects = response.data.objects;
      }
    );
  }
  $scope.refreshObjectTable = refreshObjectTable;

  // Provide upload_form.js access to internal function
  $scope.$on("refreshObjectTable", function () {
    refreshObjectTable();
  });

  // Provide upload_form.js access to internal function
  $scope.MessagesHandler = MessagesHandler;

})

  //Controller for new folder form.
  .controller('CreateFolderCtrl', function ($scope, $http, $rootScope, items) {

    $scope.showForm = 1; /* Variable for toggling the form after submission. */
    $scope.showLoader = 0; /* Variable for toggling the loader. */
    $scope.formData = {}; /* Holder for form data. */
    var create_folder_url = "/create_pseudofolder/" + items.container + "/";

    //Add prefix for new folders that will be in existing folders.
    if (items.folder_prefix) {
      create_folder_url += items.folder_prefix;
    }

    //Handler for submiting new folder form.
    $scope.createFolder = function () {

      //Display loading image
      $scope.showForm = 0;
      $scope.showLoader = 1;

      //Submit the form
      $http({
        method  : 'POST',
        url     : create_folder_url,
        data    : $.param($scope.formData),  // pass in data as strings
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
      })
        .success(function () {

          $('#pseudoContainer').foundation('reveal', 'close');
          $rootScope.$broadcast('refreshObjectTable');
          $scope.showForm = 1;
          $scope.showLoader = 0;
          $scope.formData.foldername = "";
        })
        .error(function () {
          //TODO: Display error message
          console.log($scope.formData);
        });
    };
  })

  //Filter to display the file size in a compact way. Ex. 3GB or 100Bytes
  .filter('formatByte', function () {
    'use strict';

    return function (size) {
      var exp = Math.log(size) / Math.log(1024);
      if (exp < 1) {
        exp = 0;
      }
      return (size / Math.pow(1024, exp)).toFixed(1) + ' ' +
        ((exp > 0) ? 'KMGTPEZY'[exp - 1] + 'B' : 'Bytes');
    };
  })

  /*
  Format the pseudo folder:
    from "folder/name/"
    to "name"
  */
  .filter('formatPseudoFolder', function () {
    'use strict';

    return function (string) {

      var stripped = string.substring(0, string.length - 1);
      var split = stripped.split("/");
      return split[split.length - 1];
    };
  })

  //Event for when last row in object table has been rendered.
  .directive('onLastRepeat', function () {
    return function (scope, element, attrs) {
      if (scope.$last) {
        setTimeout(function () {
          scope.$emit('onRepeatLast', element, attrs);
        }, 1);
      }
    };
  })

  .directive('ngUpdateHidden', function () {
    return function (scope, el, attr) {
      var model = attr.ngModel;
      scope.$watch(model, function (nv) {
        el.val(nv);
      });
    };
  });

/* Added in for CSRF support. */
app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.post['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();
});

angular.element(document).ready(get_object_table);

/*
TODO: replace with loader angular logic
    Display the loader in the object table.
*/
function showLoader() {

  $('#objecttable').html(
    '
' +
      '
Loading...
' +
      '
'
  );
}

/*
    After a table is loaded, new events need to be applied to the page.
*/
app.applyTableEvents = function () {

  //Re-apply foundation
  $(document).foundation();

  //Reapply dismiss of alert boxes
  $(".alert-box").click(function () {
    $(this).slideUp();
  });

  //Delete object binding.
  $("a.delete-object").on("click", function (e) {
    //Prompt user to confirm.
    /*global confirm: true*/
    if (confirm("Are you sure you want to delete " + $(this).attr("data-name") + "?")) {
      showLoader();
      $("#progress").show();
    } else {
      e.preventDefault();
    }
  });

  //Delete folder binding.
  $("a.delete-folder").on("click", function (e) {

    if (confirm("Are you sure you want to delete " + $(this).attr("data-name") + "?")) {
      if (confirm("This will delete " + $(this).attr("data-name") + " and all it's contents. Are you sure?")) {
        showLoader();
        $("#progress").show();
      } else {
        e.preventDefault();
      }
    } else {
      e.preventDefault();
    }
  });
};
<|endoftext|>


<commit_before>import './BaseCommand'

import { FS } from 'grind-support'
import { InputOption } from 'grind-cli'

const crypto = require('crypto')
const path = require('path')
const Ignore = require('ignore')

export class PublishCommand extends BaseCommand {

	name = 'assets:publish'
	description = 'Compies and publishes all assets'

	assets = { }
	oldAssets = { }
	factory = null
	publishedBaseUrl = null
	topLevel = false

	options = [
		new InputOption('published-base-url', InputOption.VALUE_OPTIONAL, 'Specify the base URL for published assets.'),
	]

	ready() {
		this.factory = this.app.assets
		this.topLevel = this.app.config.get('assets.top_level') === true

		return super.ready()
	}

	async run() {
		this.oldAssets = await this.loadOldAssets()

		if(this.oldAssets.isNil) {
			this.oldAssets = { }
		}

		this.factory.published = { }

		const publishedBaseUrl = this.option('published-base-url', this.app.config.get('assets.publish.base_url'))

		if(typeof publishedBaseUrl === 'string' && publishedBaseUrl.length > 0) {
			this.publishedBaseUrl = publishedBaseUrl.replace(/\/$/g, '')
			this.assets.__base_url = `${this.publishedBaseUrl}/`
		} else {
			this.publishedBaseUrl = path.join('/', path.relative(this.app.paths.public('/'), this.publishPath))
		}

		if(!this.oldAssets.__base_url.isNil) {
			const length = this.oldAssets.__base_url.length
			delete this.oldAssets.__base_url

			for(const key of Object.keys(this.oldAssets)) {
				this.oldAssets[key] = this.oldAssets[key].substring(length)
			}
		}

		await this.compile()

		await this.writeConfig(this.assets)
		await this.removeAssets(this.oldAssets)
	}

	async compile() {
		const assets = await this.findAssets(this.sourcePath)

		for(const asset of assets) {
			let content = null

			try {
				this.comment('Compiling', path.relative(this.app.paths.base(), asset.path))
				content = await asset.compile()
			} catch(err) {
				let message = err.message || 'Unknown error'

				if(!err.file.isNil) {
					message += `\n --> File: ${err.file}`
				}

				if(!err.line.isNil) {
					message += `\n --> Line: ${err.line}`
				}

				if(!err.column.isNil) {
					message += `\n --> Column: ${err.column}`
				}

				throw new Error(message)
			}

			let storePath = path.relative(this.sourcePath, asset.path)

			if(!this.topLevel) {
				storePath = path.join(asset.type, storePath.substr(storePath.indexOf('/')))
			}

			let name = path.basename(storePath, path.extname(storePath))

			if(asset.compiler.wantsHashSuffixOnPublish) {
				const sha1 = crypto.createHash('md5')
				sha1.update(content)
				name += `-${sha1.digest('hex').substring(0, 8)}`
			}

			name += `.${asset.extension}`
			await this.storeAsset(asset, path.join(this.publishPath, path.dirname(storePath), name), content)
		}
	}

	async findAssets(pathname) {
		const files = await FS.recursiveReaddir(pathname)
		const ignoreFiles = files.filter(file => path.basename(file) === '.assetsignore')
		const ignoreRules = Ignore().add([ '**/_*', '**/.*', path.join(path.relative(this.sourcePath, this.publishPath), '/') ])

		for(const ignoreFile of ignoreFiles) {
			const content = await FS.readFile(ignoreFile).then(content => content.toString())
			const dirname = path.relative(pathname, path.dirname(ignoreFile))

			const rules = content.split(/[\n\r]+/).filter(line => {
				line = line.trim()
				return line.length > 0 && line.substring(0, 1) !== '#'
			}).map(line => {
				if(line.substring(0, 1) === '!') {
					return `!${path.join(dirname, line.substring(1))}`
				}

				return path.join(dirname, line)
			})

			ignoreRules.add(rules)
		}

		return files.filter(file => {
			if(ignoreRules.filter([ path.relative(pathname, file) ]).length !== 1) {
				return false
			}

			if(!this.factory.isPathSupported(file)) {
				this.comment('Skipping unsupported asset', path.relative(this.app.paths.base(), file))
				return false
			}

			return true
		}).map(file => this.factory.make(file)).sort((a, b) => b.compareKind(a))
	}

	loadOldAssets() {
		return this.app.config.get('assets-published')
	}

	async storeAsset(asset, file, contents) {
		await FS.mkdirp(path.dirname(file))

		if(!(contents instanceof Buffer)) {
			contents = Buffer.from(contents)
		}

		contents = await this.postProcess(asset, file, contents)

		await FS.writeFile(file, contents)
		const lastModified = await asset.lastModified()

		if(!lastModified.isNil) {
			await FS.touch(file, lastModified)
		}

		const src = path.relative(this.sourcePath, asset.path)
		const dest = `${this.publishedBaseUrl}/${path.relative(this.publishPath, file)}`
		this.assets[src] = dest
		this.factory.published[src] = dest

		if(this.oldAssets[src] === dest) {
			delete this.oldAssets[src]
		}
	}

	async postProcess(asset, file, contents) {
		const postProcessors = this.factory.getPostProcessorsFromPath(file)

		if(postProcessors.length === 0) {
			return contents
		}

		for(const postProcessor of postProcessors) {
			this.comment(`Applying ${postProcessor.constructor.name}`, path.relative(this.app.paths.base(), asset.path))
			contents = await postProcessor.process(asset.path, file, contents)

			if(!(contents instanceof Buffer)) {
				contents = Buffer.from(contents)
			}
		}

		return contents
	}

	async removeAssets(assets) {
		for(const key of Object.keys(assets)) {
			await this.removeAsset(assets[key])
		}
	}

	async writeConfig(config) {
		await FS.writeFile(
			this.app.paths.config('assets-published.json'),
			JSON.stringify(config, null, ' ')
		)
	}

}
<commit_msg>Fixed a bug where locally published assets would start with a double forward slash<commit_after>import './BaseCommand'

import { FS } from 'grind-support'
import { InputOption } from 'grind-cli'

const crypto = require('crypto')
const path = require('path')
const Ignore = require('ignore')

export class PublishCommand extends BaseCommand {

	name = 'assets:publish'
	description = 'Compies and publishes all assets'

	assets = { }
	oldAssets = { }
	factory = null
	publishedBaseUrl = null
	topLevel = false

	options = [
		new InputOption('published-base-url', InputOption.VALUE_OPTIONAL, 'Specify the base URL for published assets.'),
	]

	ready() {
		this.factory = this.app.assets
		this.topLevel = this.app.config.get('assets.top_level') === true

		return super.ready()
	}

	async run() {
		this.oldAssets = await this.loadOldAssets()

		if(this.oldAssets.isNil) {
			this.oldAssets = { }
		}

		this.factory.published = { }

		const publishedBaseUrl = this.option('published-base-url', this.app.config.get('assets.publish.base_url'))

		if(typeof publishedBaseUrl === 'string' && publishedBaseUrl.length > 0) {
			this.publishedBaseUrl = publishedBaseUrl
			this.assets.__base_url = `${this.publishedBaseUrl}/`
		} else {
			this.publishedBaseUrl = path.join('/', path.relative(this.app.paths.public('/'), this.publishPath))
		}

		this.publishedBaseUrl = this.publishedBaseUrl.replace(/\/$/g, '')

		if(!this.oldAssets.__base_url.isNil) {
			const length = this.oldAssets.__base_url.length
			delete this.oldAssets.__base_url

			for(const key of Object.keys(this.oldAssets)) {
				this.oldAssets[key] = this.oldAssets[key].substring(length)
			}
		}

		await this.compile()

		await this.writeConfig(this.assets)
		await this.removeAssets(this.oldAssets)
	}

	async compile() {
		const assets = await this.findAssets(this.sourcePath)

		for(const asset of assets) {
			let content = null

			try {
				this.comment('Compiling', path.relative(this.app.paths.base(), asset.path))
				content = await asset.compile()
			} catch(err) {
				let message = err.message || 'Unknown error'

				if(!err.file.isNil) {
					message += `\n --> File: ${err.file}`
				}

				if(!err.line.isNil) {
					message += `\n --> Line: ${err.line}`
				}

				if(!err.column.isNil) {
					message += `\n --> Column: ${err.column}`
				}

				throw new Error(message)
			}

			let storePath = path.relative(this.sourcePath, asset.path)

			if(!this.topLevel) {
				storePath = path.join(asset.type, storePath.substr(storePath.indexOf('/')))
			}

			let name = path.basename(storePath, path.extname(storePath))

			if(asset.compiler.wantsHashSuffixOnPublish) {
				const sha1 = crypto.createHash('md5')
				sha1.update(content)
				name += `-${sha1.digest('hex').substring(0, 8)}`
			}

			name += `.${asset.extension}`
			await this.storeAsset(asset, path.join(this.publishPath, path.dirname(storePath), name), content)
		}
	}

	async findAssets(pathname) {
		const files = await FS.recursiveReaddir(pathname)
		const ignoreFiles = files.filter(file => path.basename(file) === '.assetsignore')
		const ignoreRules = Ignore().add([ '**/_*', '**/.*', path.join(path.relative(this.sourcePath, this.publishPath), '/') ])

		for(const ignoreFile of ignoreFiles) {
			const content = await FS.readFile(ignoreFile).then(content => content.toString())
			const dirname = path.relative(pathname, path.dirname(ignoreFile))

			const rules = content.split(/[\n\r]+/).filter(line => {
				line = line.trim()
				return line.length > 0 && line.substring(0, 1) !== '#'
			}).map(line => {
				if(line.substring(0, 1) === '!') {
					return `!${path.join(dirname, line.substring(1))}`
				}

				return path.join(dirname, line)
			})

			ignoreRules.add(rules)
		}

		return files.filter(file => {
			if(ignoreRules.filter([ path.relative(pathname, file) ]).length !== 1) {
				return false
			}

			if(!this.factory.isPathSupported(file)) {
				this.comment('Skipping unsupported asset', path.relative(this.app.paths.base(), file))
				return false
			}

			return true
		}).map(file => this.factory.make(file)).sort((a, b) => b.compareKind(a))
	}

	loadOldAssets() {
		return this.app.config.get('assets-published')
	}

	async storeAsset(asset, file, contents) {
		await FS.mkdirp(path.dirname(file))

		if(!(contents instanceof Buffer)) {
			contents = Buffer.from(contents)
		}

		contents = await this.postProcess(asset, file, contents)

		await FS.writeFile(file, contents)
		const lastModified = await asset.lastModified()

		if(!lastModified.isNil) {
			await FS.touch(file, lastModified)
		}

		const src = path.relative(this.sourcePath, asset.path)
		const dest = `${this.publishedBaseUrl}/${path.relative(this.publishPath, file)}`
		this.assets[src] = dest
		this.factory.published[src] = dest

		if(this.oldAssets[src] === dest) {
			delete this.oldAssets[src]
		}
	}

	async postProcess(asset, file, contents) {
		const postProcessors = this.factory.getPostProcessorsFromPath(file)

		if(postProcessors.length === 0) {
			return contents
		}

		for(const postProcessor of postProcessors) {
			this.comment(`Applying ${postProcessor.constructor.name}`, path.relative(this.app.paths.base(), asset.path))
			contents = await postProcessor.process(asset.path, file, contents)

			if(!(contents instanceof Buffer)) {
				contents = Buffer.from(contents)
			}
		}

		return contents
	}

	async removeAssets(assets) {
		for(const key of Object.keys(assets)) {
			await this.removeAsset(assets[key])
		}
	}

	async writeConfig(config) {
		await FS.writeFile(
			this.app.paths.config('assets-published.json'),
			JSON.stringify(config, null, ' ')
		)
	}

}
<|endoftext|>