<commit_before>(function () {
    'use strict';

    var templates = {};
    var acceptedTypes = ["tech", "sexism", "realism"];

    if (!isSupportedBrowser()) {
        document.getElementById('unsupported').style.display = 'block';
        return;
    }

    $(initPage);

    function initPage () {
        initTemplates();
        initControls();
    }

    function initTemplates () {
        $('[data-template]').each(function () {
            var name = this.getAttribute('data-template');
            var template = Hogan.compile(this.innerHTML, {
                delimiters: '{ }'
            });
            templates[name] = template;
        });
    }

    function initControls () {
        cuff.controls.postInput = postInputControl;
        cuff.controls.countOutput = countOutputControl;
        cuff.controls.summaryOutput = summaryOutputControl;
        cuff.controls.contextOutput = contextOutputControl;
        cuff.controls.errorTooltip = errorTooltipControl;
        cuff.controls.infoTooltip = infoTooltipControl;
        cuff();
    };

    function postInputControl (element) {
        var $document = $(document);
        var $element = $(element);
        var lastLintId;
        $element.on('keyup', function () {
            var inputValue = element.value.replace(/\n/g, "
");
            var results = joblint(inputValue);
            results.readingLevel = buildReadingLevel(element.value);
            var lintId = generateLintId(results);
            saveSession(element.value);
            $document.trigger('lint-results', results);
        });
        var session = loadSession();
        if (session) {
            element.value = loadSession();
            setTimeout(function () {
                $element.trigger('keyup');
            }, 1);
        }
    };

    function contextOutputControl (element) {

      var typeTranslation = {
        tech: "jargon",
        sexism: "gender",
        realism: "expectations"
      }

      $(document).on('lint-results', function( event, results) {
          var inputElement = $(document).find('#post-input')[0];
          var baseText = inputElement.value.replace(/\n/g, "
");

          // sort array by the position of the issue
          var issues = _.sortBy(results.issues, function(issue) {
              return issue.position;
          });
          issues.reverse(); // now the issues are sorted by last to first

          issues.forEach(function(issue) {

            _.forEach(acceptedTypes, function(acceptedType) { // iterate through potentially defined issue types
                if(_.has(issue.increment, acceptedType)) { // if we're supposed to increment one of these
                  issue.type = acceptedType; // create new property with that type
                  issue.typeTranslation = typeTranslation[acceptedType];
                  return false; // exit loop
                }
            });

            var occuranceLength = issue.occurance.length;

            var beginning = baseText.slice(0, issue.position);
            var end = baseText.slice(issue.position + occuranceLength);

            var highlight = templates.highlight.render(issue, templates);
            baseText = beginning + highlight + end;
          });

          element.innerHTML = baseText;
          cuff(element); // only apply bindings for children of this element
      });
    };

    function calculateOffset(element) {
      var parent = $(element).parent();
      var parentOffset = parent.offset();
      var parentWidth = parent.width();
      var documentWidth = $(document).width();

      var tooltipOffset = {
        top : parentOffset.top + 30
      };

      var tooltipWidth = 300;

      if(parentOffset.left + parentWidth + tooltipWidth > documentWidth) { // if the tooltip will go over the edge
        tooltipOffset.left = parentOffset.left - tooltipWidth + parentWidth / 2;
      } else { // if it's fine
        tooltipOffset.left = parentOffset.left;
      }

      return tooltipOffset;
    }

    function errorTooltipControl (element) {
      var parent = $(element).parent();
      parent.hover(
        function() { showTooltip(element) },
        function() { hideTooltip(element) }
      );

      var tooltipOffset = calculateOffset(element);
      $(element).offset(tooltipOffset);

      parent.parent().scroll(element, tooltipScroll);
    }

    function tooltipScroll(event) {
      var element = event.data;
      var tooltipOffset = calculateOffset(element);
      $(element).offset(tooltipOffset);
    }

    function infoTooltipControl(element) {
        var parent = $(element).parent();

        parent.hover(
            function() { showTooltip(element); },
            function() { hideTooltip(element); }
        );

        var tooltipOffset = calculateOffset(element);
        $(element).offset(tooltipOffset);
    }

    function showTooltip(element) {
      $(element).addClass("tooltip-show");
    }

    function hideTooltip(element) {
      $(element).removeClass("tooltip-show");
    }

    function issuesOutputControl (element) {
        $(document).on('lint-results', function (event, results) {
            results.issues.forEach(function (issue) {
                var occuranceHtml = templates.occurance.render(issue);
                issue.contextHtml = issue.context.replace('{{occurance}}', occuranceHtml);
            });
            element.innerHTML = templates.issues.render(results, templates);
        });
    }

    function countOutputControl (element) {
        var counters = {};
        var countersArray = [];
        $(element).find('[data-role=count]').each(function () {
            var type = this.getAttribute('data-type');
            var count = {
                circle: this.querySelector('[data-role=circle]'),
                number: this.querySelector('[data-role=number]')
            }
            counters[type] = count;
            countersArray.push(count);
        });

        $(document).on('lint-results', function (event, results) {
            countersArray.forEach(function (count) {
                count.number.innerHTML = 0;
            });

            _.forEach(acceptedTypes, function(acceptedType) {
              results.counts[acceptedType] = results.counts[acceptedType] || 0;
            });

            Object.keys(results.counts).forEach(function (type) {
                if (counters[type]) {
                    counters[type].number.innerHTML = results.counts[type];
                    $(counters[type].circle).addClass("circle-" + type);
                }
            });
        });
    };

    function summaryOutputControl(element) {
        $(document).on('lint-results', function (event, results) {
            var tooHigh = results.readingLevel >= 9;
            var readingLevelSummary = {
              "readingLevel": results.readingLevel,
              "tooHigh": tooHigh,
              "level": tooHigh ? "error-highlight" : "info-highlight"
            };
            element.innerHTML = templates.readingLevel.render(readingLevelSummary);
            cuff(element);
        });
    }

    function generateLintId (results) {
        return JSON.stringify(results);
    }

    function saveSession (postContent) {
        if (typeof window.localStorage !== 'undefined') {
            localStorage.setItem('post', postContent);
        }
    }

    function loadSession () {
        if (typeof window.localStorage !== 'undefined') {
            return localStorage.getItem('post');
        }
    }

    function isSupportedBrowser () {
        var supports = {
            events: (typeof document.addEventListener !== 'undefined'),
            querySelector: (typeof document.querySelectorAll !== 'undefined'),
            forEach: (typeof Array.prototype.forEach !== 'undefined')
        };
        return (supports.events && supports.querySelector && supports.forEach);
    }

    function buildReadingLevel (text) {
        var ts = textstatistics(text);
        var gradeLevel = ts.fleschKincaidGradeLevel();
        return gradeLevel;
    }

}());
<commit_msg>only highlight pre-defined types<commit_after>(function () {
    'use strict';

    var templates = {};
    var acceptedTypes = ["tech", "sexism", "realism"];

    if (!isSupportedBrowser()) {
        document.getElementById('unsupported').style.display = 'block';
        return;
    }

    $(initPage);

    function initPage () {
        initTemplates();
        initControls();
    }

    function initTemplates () {
        $('[data-template]').each(function () {
            var name = this.getAttribute('data-template');
            var template = Hogan.compile(this.innerHTML, {
                delimiters: '{ }'
            });
            templates[name] = template;
        });
    }

    function initControls () {
        cuff.controls.postInput = postInputControl;
        cuff.controls.countOutput = countOutputControl;
        cuff.controls.summaryOutput = summaryOutputControl;
        cuff.controls.contextOutput = contextOutputControl;
        cuff.controls.errorTooltip = errorTooltipControl;
        cuff.controls.infoTooltip = infoTooltipControl;
        cuff();
    };

    function postInputControl (element) {
        var $document = $(document);
        var $element = $(element);
        var lastLintId;
        $element.on('keyup', function () {
            var inputValue = element.value.replace(/\n/g, "
");
            var results = joblint(inputValue);
            results.readingLevel = buildReadingLevel(element.value);
            var lintId = generateLintId(results);
            saveSession(element.value);
            $document.trigger('lint-results', results);
        });
        var session = loadSession();
        if (session) {
            element.value = loadSession();
            setTimeout(function () {
                $element.trigger('keyup');
            }, 1);
        }
    };

    function contextOutputControl (element) {

      var typeTranslation = {
        tech: "jargon",
        sexism: "gender",
        realism: "expectations"
      }

      $(document).on('lint-results', function( event, results) {
          var inputElement = $(document).find('#post-input')[0];
          var baseText = inputElement.value.replace(/\n/g, "
");

          // sort array by the position of the issue
          var issues = _.sortBy(results.issues, function(issue) {
              return issue.position;
          });
          issues.reverse(); // now the issues are sorted by last to first

          issues.forEach(function(issue) {

            _.forEach(acceptedTypes, function(acceptedType) { // iterate through potentially defined issue types
                if(_.has(issue.increment, acceptedType)) { // if we're supposed to increment one of these
                  issue.type = acceptedType; // create new property with that type
                  issue.typeTranslation = typeTranslation[acceptedType];
                  return false; // exit loop
                }
            });

            if(issue.type) {
              var occuranceLength = issue.occurance.length;

              var beginning = baseText.slice(0, issue.position);
              var end = baseText.slice(issue.position + occuranceLength);

              var highlight = templates.highlight.render(issue, templates);
              baseText = beginning + highlight + end;
            }
          });

          element.innerHTML = baseText;
          cuff(element); // only apply bindings for children of this element
      });
    };

    function calculateOffset(element) {
      var parent = $(element).parent();
      var parentOffset = parent.offset();
      var parentWidth = parent.width();
      var documentWidth = $(document).width();

      var tooltipOffset = {
        top : parentOffset.top + 30
      };

      var tooltipWidth = 300;

      if(parentOffset.left + parentWidth + tooltipWidth > documentWidth) { // if the tooltip will go over the edge
        tooltipOffset.left = parentOffset.left - tooltipWidth + parentWidth / 2;
      } else { // if it's fine
        tooltipOffset.left = parentOffset.left;
      }

      return tooltipOffset;
    }

    function errorTooltipControl (element) {
      var parent = $(element).parent();
      parent.hover(
        function() { showTooltip(element) },
        function() { hideTooltip(element) }
      );

      var tooltipOffset = calculateOffset(element);
      $(element).offset(tooltipOffset);

      parent.parent().scroll(element, tooltipScroll);
    }

    function tooltipScroll(event) {
      var element = event.data;
      var tooltipOffset = calculateOffset(element);
      $(element).offset(tooltipOffset);
    }

    function infoTooltipControl(element) {
        var parent = $(element).parent();

        parent.hover(
            function() { showTooltip(element); },
            function() { hideTooltip(element); }
        );

        var tooltipOffset = calculateOffset(element);
        $(element).offset(tooltipOffset);
    }

    function showTooltip(element) {
      $(element).addClass("tooltip-show");
    }

    function hideTooltip(element) {
      $(element).removeClass("tooltip-show");
    }

    function issuesOutputControl (element) {
        $(document).on('lint-results', function (event, results) {
            results.issues.forEach(function (issue) {
                var occuranceHtml = templates.occurance.render(issue);
                issue.contextHtml = issue.context.replace('{{occurance}}', occuranceHtml);
            });
            element.innerHTML = templates.issues.render(results, templates);
        });
    }

    function countOutputControl (element) {
        var counters = {};
        var countersArray = [];
        $(element).find('[data-role=count]').each(function () {
            var type = this.getAttribute('data-type');
            var count = {
                circle: this.querySelector('[data-role=circle]'),
                number: this.querySelector('[data-role=number]')
            }
            counters[type] = count;
            countersArray.push(count);
        });

        $(document).on('lint-results', function (event, results) {
            countersArray.forEach(function (count) {
                count.number.innerHTML = 0;
            });

            _.forEach(acceptedTypes, function(acceptedType) {
              results.counts[acceptedType] = results.counts[acceptedType] || 0;
            });

            Object.keys(results.counts).forEach(function (type) {
                if (counters[type]) {
                    counters[type].number.innerHTML = results.counts[type];
                    $(counters[type].circle).addClass("circle-" + type);
                }
            });
        });
    };

    function summaryOutputControl(element) {
        $(document).on('lint-results', function (event, results) {
            var tooHigh = results.readingLevel >= 9;
            var readingLevelSummary = {
              "readingLevel": results.readingLevel,
              "tooHigh": tooHigh,
              "level": tooHigh ? "error-highlight" : "info-highlight"
            };
            element.innerHTML = templates.readingLevel.render(readingLevelSummary);
            cuff(element);
        });
    }

    function generateLintId (results) {
        return JSON.stringify(results);
    }

    function saveSession (postContent) {
        if (typeof window.localStorage !== 'undefined') {
            localStorage.setItem('post', postContent);
        }
    }

    function loadSession () {
        if (typeof window.localStorage !== 'undefined') {
            return localStorage.getItem('post');
        }
    }

    function isSupportedBrowser () {
        var supports = {
            events: (typeof document.addEventListener !== 'undefined'),
            querySelector: (typeof document.querySelectorAll !== 'undefined'),
            forEach: (typeof Array.prototype.forEach !== 'undefined')
        };
        return (supports.events && supports.querySelector && supports.forEach);
    }

    function buildReadingLevel (text) {
        var ts = textstatistics(text);
        var gradeLevel = ts.fleschKincaidGradeLevel();
        return gradeLevel;
    }

}());
<|endoftext|>


<commit_before>hqDefine("m4change/javascripts/main", function () {
    var initialPageData = hqImport("hqwebapp/js/initial_page_data");
    $(function () {
        var OPTIONS = {
            users: initialPageData.get("users"),
            groups: initialPageData.get("groups"),
            receiverUrl: initialPageData.reverse('receiver_secure_post'),
            enddate: initialPageData.get("end_date"),
            webUserID: initialPageData.get("user_id"),
            domain: initialPageData.get("domain"),
        };

        var managementModel = new McctProjectReviewPageManagement(OPTIONS);
        function applyBindings() {
            var $mcctProjectReviewPageManagement = $('#mcct_project_review_page_management');
            var element = $mcctProjectReviewPageManagement[0];
            element.koApplyBindings(managementModel);

            $mcctProjectReviewPageManagement.find('a.select-all').click(function () {
                $mcctProjectReviewPageManagement.find('input.selected-element').prop('checked', true).change();
                return false;
            });

            $mcctProjectReviewPageManagement.find('a.select-none').click(function() {selectNone(); return false;});
            $mcctProjectReviewPageManagement.find('.dataTables_paginate a').mouseup(selectNone);
            $mcctProjectReviewPageManagement.find('.dataTables_length select').change(selectNone);

            function selectNone() {
                $mcctProjectReviewPageManagement.find('input.selected-element:checked').prop('checked', false).change();
            }
        }

        function applyCheckboxListeners() {
             $('input.selected-element', '#mcct_project_review_page_management').on('change', function(event) {
                 managementModel.updateSelection({}, event);
             });
        }

        // Initialize page once it's ready
        var keepTrying = setInterval(function () {
            if (window.reportTables !== undefined) {
                clearInterval(keepTrying);
                applyBindings();
                applyCheckboxListeners();
                window.reportTables.fnDrawCallback = applyCheckboxListeners;
            }
        }, 1000);

        // Initialize help templates
        $('.hq-help-template').each(function () {
            hqImport("hqwebapp/js/main").transformHelpTemplate($(this), true);
        });

        // Initialize date range
        var $datespan = $('#filter_range');
        if ($datespan.length) {
            var separator = $datespan.data('separator');
            var report_labels = $datespan.data("report-labels");
            var standardHQReport = hqImport("reports/js/standard_hq_report").getStandardHQReport();

            $('#filter_range').createDateRangePicker(report_labels, separator);
            $('#filter_range').on('apply', function(ev, picker) {
                var dates = $(this).val().split(separator);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
            });
        }
    });
});
<commit_msg>Moved js logic from document ready handler to ajaxComplete handler<commit_after>hqDefine("m4change/javascripts/main", function () {
    var initialPageData = hqImport("hqwebapp/js/initial_page_data");
    $(document).on("ajaxComplete", function (e, xhr, options) {
        var fragment = "async/",
            pageUrl = window.location.href.split('?')[0],
            ajaxUrl = options.url.split('?')[0];
        if (ajaxUrl.indexOf(fragment) === -1 || !pageUrl.endsWith(ajaxUrl.replace(fragment, ''))) {
            return;
        }
        var OPTIONS = {
            users: initialPageData.get("users"),
            groups: initialPageData.get("groups"),
            receiverUrl: initialPageData.reverse('receiver_secure_post'),
            enddate: initialPageData.get("end_date"),
            webUserID: initialPageData.get("user_id"),
            domain: initialPageData.get("domain"),
        };

        var managementModel = new McctProjectReviewPageManagement(OPTIONS);
        function applyBindings() {
            var $mcctProjectReviewPageManagement = $('#mcct_project_review_page_management');
            var element = $mcctProjectReviewPageManagement[0];
            element.koApplyBindings(managementModel);

            $mcctProjectReviewPageManagement.find('a.select-all').click(function () {
                $mcctProjectReviewPageManagement.find('input.selected-element').prop('checked', true).change();
                return false;
            });

            $mcctProjectReviewPageManagement.find('a.select-none').click(function() {selectNone(); return false;});
            $mcctProjectReviewPageManagement.find('.dataTables_paginate a').mouseup(selectNone);
            $mcctProjectReviewPageManagement.find('.dataTables_length select').change(selectNone);

            function selectNone() {
                $mcctProjectReviewPageManagement.find('input.selected-element:checked').prop('checked', false).change();
            }
        }

        function applyCheckboxListeners() {
             $('input.selected-element', '#mcct_project_review_page_management').on('change', function(event) {
                 managementModel.updateSelection({}, event);
             });
        }

        // Initialize page once it's ready
        var keepTrying = setInterval(function () {
            if (window.reportTables !== undefined) {
                clearInterval(keepTrying);
                applyBindings();
                applyCheckboxListeners();
                window.reportTables.fnDrawCallback = applyCheckboxListeners;
            }
        }, 1000);

        // Initialize help templates
        $('.hq-help-template').each(function () {
            hqImport("hqwebapp/js/main").transformHelpTemplate($(this), true);
        });

        // Initialize date range
        var $datespan = $('#filter_range');
        if ($datespan.length) {
            var separator = $datespan.data('separator');
            var report_labels = $datespan.data("report-labels");
            var standardHQReport = hqImport("reports/js/standard_hq_report").getStandardHQReport();

            $('#filter_range').createDateRangePicker(report_labels, separator);
            $('#filter_range').on('apply', function(ev, picker) {
                var dates = $(this).val().split(separator);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
            });
        }
    });
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  var exec = require('child_process').exec,
      fs = require('fs'),
      gzip = require('zlib').gzip;

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('closure-compiler', 'Minify JS files using Closure Compiler.', function() {

    // Check for env var.
    if (process.env.CLOSURE_PATH === undefined) {
      grunt.log.error('' +
          '/!\\'.red +
          ' Set an environment variable called ' +
          'CLOSURE_PATH'.red +
          ' and\nmake it point to your root install of Closure Compiler.' +
          '\n');

      // Return an error and stop grunt.
      return false;
    }

    var closureCompilerDir = process.env.CLOSURE_PATH,
        command = 'java -jar ' + closureCompilerDir + '/build/compiler.jar',
        reportFile = '',
        data = this.data,
        done = this.async();

    if (data.externs == undefined) {
      data.externs = [];
    }

    data.js = grunt.file.expandFiles(data.js);
    data.externs = grunt.file.expandFiles(data.externs);

    // Sanitize options passed.
    if (!data.js.length) {
      // This task requires a minima an input file.
      grunt.warn('Missing js property.');
      return false;
    }

    // Build command line.
    command += ' --js ' + data.js.join(' --js ');
    command += ' --externs ' + data.externs.join(' --externs ');

    if (data.jsOutputFile) {
      command += ' --js_output_file ' + data.jsOutputFile;
      reportFile = data.jsOutputFile + '.report.txt';
    }

    for (var directive in data.options) {
      if (Array.isArray(data.options[directive])) {
        command += ' --' + directive + ' ' + data.options[directive].join(' --' + directive + ' ');
      } else {
        command += ' --' + directive + ' ' + String(data.options[directive]);
      }
    }

    // Minify WebGraph class.
    exec(command, function(err, stdout, stderr) {
      if (err) {
        grunt.warn(err);
        done(false);
      }

      if (stdout) {
        grunt.log.writeln(stdout);
      }

      // If OK, calculate gzipped file size.
      if (data.jsOutputFile) {
        var min = fs.readFileSync(data.jsOutputFile, 'utf8');
        grunt.helper('min_info', min, function(err) {
          if (err) {
            grunt.warn(err);
            done(false);
          }

          // Write compile report to a file.
          fs.writeFile(reportFile, stderr, function(err) {
            if (err) {
              grunt.warn(err);
              done(false);
            }

            grunt.log.writeln('A report is saved in ' + reportFile + '.');
            done();
          });

        });
      }

    });

  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================
  // Output some size info about a file.
  grunt.registerHelper('min_info', function(min, onComplete) {
    gzip(min, function(err, buffer) {
      if (err) {
        onComplete.call(this, err);
      }

      var gzipSize = buffer.toString().length;
      grunt.log.writeln('Compressed size: ' + String((gzipSize / 1024).toFixed(2)).green + ' kb gzipped (' + String(gzipSize).green + ' bytes).');

      onComplete.call(this, null);
    });
  });

};
<commit_msg>If there are no externs specified via options, the task breaks. The generated command should not look like this: $ java -jar /path/to/closure-compiler/build/compiler.jar --js file1.js --js file2.js --externs This change skips adding the --externs flag if no externs have been specified.<commit_after>module.exports = function(grunt) {

  var exec = require('child_process').exec,
      fs = require('fs'),
      gzip = require('zlib').gzip;

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('closure-compiler', 'Minify JS files using Closure Compiler.', function() {

    // Check for env var.
    if (process.env.CLOSURE_PATH === undefined) {
      grunt.log.error('' +
          '/!\\'.red +
          ' Set an environment variable called ' +
          'CLOSURE_PATH'.red +
          ' and\nmake it point to your root install of Closure Compiler.' +
          '\n');

      // Return an error and stop grunt.
      return false;
    }

    var closureCompilerDir = process.env.CLOSURE_PATH,
        command = 'java -jar ' + closureCompilerDir + '/build/compiler.jar',
        reportFile = '',
        data = this.data,
        done = this.async();

    if (data.externs == undefined) {
      data.externs = [];
    }

    data.js = grunt.file.expandFiles(data.js);
    data.externs = grunt.file.expandFiles(data.externs);

    // Sanitize options passed.
    if (!data.js.length) {
      // This task requires a minima an input file.
      grunt.warn('Missing js property.');
      return false;
    }

    // Build command line.
    command += ' --js ' + data.js.join(' --js ');

    if (data.js.length) {
      // Add --externs flag only if valid externs are present.
      command += ' --externs ' + data.externs.join(' --externs ');
    }

    if (data.jsOutputFile) {
      command += ' --js_output_file ' + data.jsOutputFile;
      reportFile = data.jsOutputFile + '.report.txt';
    }

    for (var directive in data.options) {
      if (Array.isArray(data.options[directive])) {
        command += ' --' + directive + ' ' + data.options[directive].join(' --' + directive + ' ');
      } else {
        command += ' --' + directive + ' ' + String(data.options[directive]);
      }
    }

    // Minify WebGraph class.
    exec(command, function(err, stdout, stderr) {
      if (err) {
        grunt.warn(err);
        done(false);
      }

      if (stdout) {
        grunt.log.writeln(stdout);
      }

      // If OK, calculate gzipped file size.
      if (data.jsOutputFile) {
        var min = fs.readFileSync(data.jsOutputFile, 'utf8');
        grunt.helper('min_info', min, function(err) {
          if (err) {
            grunt.warn(err);
            done(false);
          }

          // Write compile report to a file.
          fs.writeFile(reportFile, stderr, function(err) {
            if (err) {
              grunt.warn(err);
              done(false);
            }

            grunt.log.writeln('A report is saved in ' + reportFile + '.');
            done();
          });

        });
      }

    });

  });

  // ==========================================================================
  // HELPERS
  // ==========================================================================
  // Output some size info about a file.
  grunt.registerHelper('min_info', function(min, onComplete) {
    gzip(min, function(err, buffer) {
      if (err) {
        onComplete.call(this, err);
      }

      var gzipSize = buffer.toString().length;
      grunt.log.writeln('Compressed size: ' + String((gzipSize / 1024).toFixed(2)).green + ' kb gzipped (' + String(gzipSize).green + ' bytes).');

      onComplete.call(this, null);
    });
  });

};
<|endoftext|>


<commit_before>// d3.v3
// http:/www.thepaper.cn,
// date 2021-01
// By The Paper data news team

//margin
var margin = {
    top: 50,
    right: 60,
    bottom: 50,
    left: 60
};

//size
var width = root.clientWidth - margin.left - margin.right;
var height = root.clientHeight - margin.top - margin.bottom;
var radius = Math.min(width, height) * 0.4;
var innerRadius = 0;
var outerRadius = Math.min(width, height) / 2;

d3.csv("data.csv", function (error, data) {
    update(data);
});

function update(data) {

    d3.select(root).selectAll('*').remove();

    for (var i = 0; i < data.length; i++) {
        var arrTitle = Object.keys(data[0]);//获取数据当表头
    }

    // console.log(arrTitle)

    var svg = d3.select(root).append('svg')
        .attr({
            width: root.clientWidth,
            height: root.clientHeight
        });

    g = svg.append("g").attr("transform", "translate(" + (width / 2 + margin.left) + "," + (height/2+margin.top) + ")");

    var dataIntermediate = arrTitle.slice(1).map(function (c) {
        return data.map(function (d) {
            return {x: d[arrTitle[0]], y: Number(d[c])};
        });
    });

    var dataStackLayout = d3.layout.stack()(dataIntermediate);

    var color = d3.scale.ordinal()
    .domain(arrTitle.slice(1))
    .range(["#4e79a7","#f28e2c","#e15759","#76b7b2","#59a14f","#edc949","#af7aa1","#ff9da7","#9c755f","#bab0ab"])

    // console.log(arrTitle)

    var x = d3.scale.ordinal()
        .domain(dataStackLayout[0].map(function (d) {
            return d.x;
        }))
        .rangeBands([0, 2 * Math.PI], 0.05);

    var y = d3.scale.radial()
        .domain([0,
            d3.max(dataStackLayout[dataStackLayout.length - 1],
                    function (d) { return d.y0 + d.y;})
            ])
        .nice()
        .range([innerRadius, outerRadius]);

    var label = g.append("g")
        .attr("class", "x_Tick")
        .selectAll("g")
        .data(data)
        .enter()
        .append("g")
        .attr("text-anchor", "middle")
        .attr("transform", function(d) { return "rotate(" + ((x(d.key) + x.rangeBand() / 2) * 180 / Math.PI - 90) + ")translate(" + outerRadius + ",0)"; });

    label.append("line")
        .attr("x2", -outerRadius)
        .attr("stroke", "#ccc")
        .attr("stroke-opacity", 0.5);

    label.append("text")
        .attr("transform", function(d) { return (x(d.key) + x.rangeBand() / 2 + Math.PI / 2) % (2 * Math.PI) < Math.PI ? "rotate(90)translate(0,-9)" : "rotate(-90)translate(0,18)"; })
        .text(function(d) {
            return d.key; });

    var arc = d3.svg.arc()
            .innerRadius(function(d) { return y(d.y0); })
            .outerRadius(function(d) { return y(d.y+d.y0); })
            .startAngle(function(d) { return x(d.x); })
            .endAngle(function(d) { return x(d.x) + x.rangeBand(); })
            .padAngle(0.01)
            .padRadius(innerRadius);

    // console.log(dataStackLayout)
    var layer = g.selectAll(".layer")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "layer")
        .style("fill", function (d, i) {
            return color(arrTitle[i+1]);
        });

    layer.selectAll("path")
        .data(function (d) {
            return d;
        })
        .enter()
        .append("path")
        .attr("d", arc);

    //参考线
    var yAxis = g.append("g")
        .attr("class", "y_Tick")
      .attr("text-anchor", "middle");

    var yTick = yAxis
        .selectAll("g")
        .data(y.ticks(10).slice(1))
        .enter().append("g");

    yTick.append("circle")
        .attr("fill", "none")
        .attr("stroke", "#ccc")
        .attr("stroke-opacity", 0.5)
        .attr("r", y);

    yTick.append("text")
        .attr("y", function(d) { return -y(d); })
        .attr("dy", "0.35em")
        .attr("fill", "none")
        .attr("stroke", "#fff")
        .attr("stroke-linejoin", "round")
        .attr("stroke-width", 3)
        .text(y.tickFormat(10, "s"));

    yTick.append("text")
        .attr("y", function(d) { return -y(d); })
        .attr("dy", "0.35em")
        .text(y.tickFormat(10, "s"));

    var legend = svg.selectAll(".title_legend")
      .data(arrTitle.slice(1))
        .enter().append("g")
        .attr("class", "title_legend")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
        .attr("x", root.clientWidth - 10 - 18)
        .attr("y", 10)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", function(d,i){
            return color(d)
        });

    legend.append("text")
        .attr("x", root.clientWidth - 10 - 24)
        .attr("y", 9+10)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) { return d; });

}
<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>/*
 * deployment tasks
 *
 * contains tasks for AWS S3 invalidation and publishing
 *
 * */

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var cloudfront = require('gulp-invalidate-cloudfront');

var path = require('path');
var fs = require('fs');
var argv = require('yargs').argv;
var merge = require('merge-stream');

var config = {
  dist: 'dist',
  applications: 'applications',
  elements: 'elements',
  dependencies: 'bower_components',
  resources: 'resources',
  demo: 'elements/demo'
};

/**
 * Command line param:
 *    --path {INVALIDATION_PATH}
 *
 * If no bucket path passed will invalidate production subdir
 */
gulp.task('invalidate', function () {
  var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));

  var invalidatePath = '';

  if (argv.path) {
    invalidatePath = argv.path + '/*';
  } else {
    invalidatePath += '/reusable-components/*';
  }

  $.util.log('Invalidation path: ' + invalidatePath);

  var invalidationBatch = {
    CallerReference: new Date().toString(),
    Paths: {
      Quantity: 1,
      Items: [
        invalidatePath
      ]
    }
  };

  var awsSettings = {
    credentials: {
      accessKeyId: awsConfig.accessKeyId,
      secretAccessKey: awsConfig.secretAccessKey
    },
    distributionId: awsConfig.params.distribution,
    region: awsConfig.params.region
  };

  return gulp.src([
    config.applications + '/*',
    config.elements + '/*',
    config.dependencies + '/*',
    config.resources + '/*'
  ]).pipe(cloudfront(invalidationBatch, awsSettings));
});

// upload package to S3
gulp.task('publish', ['copy:aws'], function () {

  // create a new publisher using S3 options
  var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
  var publisher = $.awspublish.create(awsConfig);

  // define custom headers
  var headers = {
    'Cache-Control': 'max-age=315360000, no-transform, public'
  };

  return gulp.src('./' + config.dist + '/**')
      .pipe($.rename(function (path) {
        path.dirname = awsConfig.params.bucketSubDir + '/' + path.dirname;
      }))
      // gzip, Set Content-Encoding headers
      .pipe($.awspublish.gzip())

      // publisher will add Content-Length, Content-Type and headers specified above
      // If not specified it will set x-amz-acl to public-read by default
      .pipe(publisher.publish(headers))

      // create a cache file to speed up consecutive uploads
      .pipe(publisher.cache())

      // print upload updates to console
      .pipe($.awspublish.reporter());
});

// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:aws', function () {

  var apps = gulp.src([config.applications + '/**/*.*',
    '!' + config.applications + '/**/*.scss',
    '!' + config.applications + '/**/*.json'])
      .pipe(gulp.dest(config.dist + '/applications'));

  var vulcanized = gulp.src([config.elements + '/elements.vulcanized.*'])
      .pipe(gulp.dest(config.dist));

  var vulcanized2elements = gulp.src([config.elements + '/elements.vulcanized.*'])
      .pipe(gulp.dest(config.dist + '/elements'));

  var dependencies = gulp.src([config.dependencies + '/webcomponentsjs/**/webcomponents*.js'])
      .pipe(gulp.dest(config.dist + '/webcomponentsjs'));

  var resources = gulp.src([config.resources + '/**/*'])
      .pipe(gulp.dest(config.dist + '/resources'));

  var demo = gulp.src([config.demo + '/**/*'])
      .pipe(gulp.dest(config.dist + '/elements/demo'));

  var mock_data = gulp.src([config.dependencies + '/uqlibrary-api/mock/**/*'])
      .pipe(gulp.dest(config.dist + '/bower_components/uqlibrary-api/mock'));

  var jsonData = gulp.src([config.dependencies + '/uqlibrary-api/data/contacts.json'])
      .pipe(gulp.dest(config.dist + '/bower_components/uqlibrary-api/data'));

  return merge(vulcanized, dependencies, resources, demo, mock_data, vulcanized2elements, jsonData)
      .pipe($.size({title: 'copy'}));
});<commit_msg>fixed dist structure<commit_after>/*
 * deployment tasks
 *
 * contains tasks for AWS S3 invalidation and publishing
 *
 * */

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var cloudfront = require('gulp-invalidate-cloudfront');

var path = require('path');
var fs = require('fs');
var argv = require('yargs').argv;
var merge = require('merge-stream');

var config = {
  dist: 'dist',
  applications: 'applications',
  elements: 'elements',
  dependencies: 'bower_components',
  resources: 'resources',
  demo: 'elements/demo'
};

/**
 * Command line param:
 *    --path {INVALIDATION_PATH}
 *
 * If no bucket path passed will invalidate production subdir
 */
gulp.task('invalidate', function () {
  var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));

  var invalidatePath = '';

  if (argv.path) {
    invalidatePath = argv.path + '/*';
  } else {
    invalidatePath += '/reusable-components/*';
  }

  $.util.log('Invalidation path: ' + invalidatePath);

  var invalidationBatch = {
    CallerReference: new Date().toString(),
    Paths: {
      Quantity: 1,
      Items: [
        invalidatePath
      ]
    }
  };

  var awsSettings = {
    credentials: {
      accessKeyId: awsConfig.accessKeyId,
      secretAccessKey: awsConfig.secretAccessKey
    },
    distributionId: awsConfig.params.distribution,
    region: awsConfig.params.region
  };

  return gulp.src([
    config.applications + '/*',
    config.elements + '/*',
    config.dependencies + '/*',
    config.resources + '/*'
  ]).pipe(cloudfront(invalidationBatch, awsSettings));
});

// upload package to S3
gulp.task('publish', ['copy:aws'], function () {

  // create a new publisher using S3 options
  var awsConfig = JSON.parse(fs.readFileSync('./aws.json'));
  var publisher = $.awspublish.create(awsConfig);

  // define custom headers
  var headers = {
    'Cache-Control': 'max-age=315360000, no-transform, public'
  };

  return gulp.src('./' + config.dist + '/**')
      .pipe($.rename(function (path) {
        path.dirname = awsConfig.params.bucketSubDir + '/' + path.dirname;
      }))
      // gzip, Set Content-Encoding headers
      .pipe($.awspublish.gzip())

      // publisher will add Content-Length, Content-Type and headers specified above
      // If not specified it will set x-amz-acl to public-read by default
      .pipe(publisher.publish(headers))

      // create a cache file to speed up consecutive uploads
      .pipe(publisher.cache())

      // print upload updates to console
      .pipe($.awspublish.reporter());
});

// copy and rename elements.html to elements.vulcanized.html
gulp.task('copy:aws', function () {

  var apps = gulp.src([config.applications + '/**/*.*',
    '!' + config.applications + '/**/*.scss',
    '!' + config.applications + '/**/*.json'])
      .pipe(gulp.dest(config.dist));

  var vulcanized = gulp.src([config.elements + '/elements.vulcanized.*'])
      .pipe(gulp.dest(config.dist));

  var vulcanized2elements = gulp.src([config.elements + '/elements.vulcanized.*'])
      .pipe(gulp.dest(config.dist + '/elements'));

  var dependencies = gulp.src([config.dependencies + '/webcomponentsjs/**/webcomponents*.js'])
      .pipe(gulp.dest(config.dist + '/webcomponentsjs'));

  var resources = gulp.src([config.resources + '/**/*'])
      .pipe(gulp.dest(config.dist + '/resources'));

  var demo = gulp.src([config.demo + '/**/*'])
      .pipe(gulp.dest(config.dist + '/elements/demo'));

  var mock_data = gulp.src([config.dependencies + '/uqlibrary-api/mock/**/*'])
      .pipe(gulp.dest(config.dist + '/bower_components/uqlibrary-api/mock'));

  var jsonData = gulp.src([config.dependencies + '/uqlibrary-api/data/contacts.json'])
      .pipe(gulp.dest(config.dist + '/bower_components/uqlibrary-api/data'));

  return merge(vulcanized, dependencies, resources, demo, mock_data, vulcanized2elements, jsonData)
      .pipe($.size({title: 'copy'}));
});<|endoftext|>


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

import {login, randomString, checkResults, waitTableResults} from "../plugins/utils.js";

context("5 - Case Portal", () => {
    before(() => {
        login();
    });

    it("5.1 - check query results", () => {
        cy.get("a[data-id=clinicalAnalysisPortal]", {timeout: 60000}).click({force: true});
        cy.get("div.page-title h2", {timeout: 60000}).should("be.visible").and("contain", "Case Portal");

        checkResults("opencga-clinical-analysis-grid");

        cy.get("div[data-cy='form-priority'] button").click();
        cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("URGENT").click({force: true});
        cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("HIGH").click({force: true});
        cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("MEDIUM").click({force: true});
        cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("LOW").click({force: true});
        cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("UNKNOWN").click({force: true});

        //waitTableResults("opencga-clinical-analysis-grid");
        checkResults("opencga-clinical-analysis-grid");

        // reading from the first row the case Id, the proband Id, and the Family Id and use them as filters
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000})
            .find("td:nth-child(1) a[data-cy='case-id']")
            .then($a => {
                const caseId = $a.text().trim();
                cy.get("div[data-cy='form-case'] button").click();
                cy.get("div[data-cy='form-case'] input").type(caseId + "{enter}", {force: true});
                checkResults("opencga-clinical-analysis-grid");

            })

            .find("td:nth-child(2) span[data-cy='proband-id']")
            .then($div => {
                const probandId = $div.text().trim();
                console.log("probandId", probandId);
                cy.get("div[data-cy='form-proband'] button").click();
                cy.get("div[data-cy='form-proband'] input").type(probandId + "{enter}", {force: true});
                checkResults("opencga-clinical-analysis-grid");

            });

        // cy.get("opencga-clinical-review-cases .rhs button", {timeout: 60000}).should("be.visible").and("contain", "Clear").click()
        cy.get("button[data-cy='filter-button']").click({force: true});
        cy.get(".saved-filter-wrapper a").contains("Clear").click({force: true});

    });

    it("5.2 - check Columns togglability", () => {
        cy.get("a[data-id=clinicalAnalysisPortal]", {timeout: 60000}).click({force: true});
        cy.get("div.page-title h2", {timeout: 60000}).should("be.visible").and("contain", "Case Portal");

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper button").should("be.visible").and("contain", "Columns").click();
        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li").should("have.length.gt", 1);

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li a").click({multiple: true, timeout: 60000}); // deactivate all the columns
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000}).find("td", {timeout: 60000}).should("have.lengthOf", 1);

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li a").click({multiple: true, timeout: 60000}); // reactivate all the columns
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000}).find("td", {timeout: 60000}).should("have.length.gt", 1);

    });

});

/* cy.get("variant-browser-grid .columns-toggle-wrapper ul li a").each(($li, index, $lis) => {
    //Cypress.$("a", $li)
});*/
<commit_msg>005-opencga-case-portal.spec.js priority test removed #214, #219<commit_after>/**
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {login, randomString, checkResults, waitTableResults} from "../plugins/utils.js";

context("5 - Case Portal", () => {
    before(() => {
        login();
    });

    it("5.1 - check query results", () => {
        cy.get("a[data-id=clinicalAnalysisPortal]", {timeout: 60000}).click({force: true});
        cy.get("div.page-title h2", {timeout: 60000}).should("be.visible").and("contain", "Case Portal");

        checkResults("opencga-clinical-analysis-grid");

        // check if priority filter is enabled and visible first, then it tests the filter itself
        // TODO bugfix
        /*cy.get("div.lhs", {timeout: 5000})
            .should("satisfy", $els => {
                const priority = Cypress.$("div[data-cy='form-priority'] button");
                if (priority.length) {
                    cy.get("div[data-cy='form-priority'] button").click();
                    cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("URGENT").click({force: true});
                    cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("HIGH").click({force: true});
                    cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("MEDIUM").click({force: true});
                    cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("LOW").click({force: true});
                    cy.get("div[data-cy='form-priority'] ul.dropdown-menu li").contains("UNKNOWN").click({force: true});
                    //waitTableResults("opencga-clinical-analysis-grid");
                    checkResults("opencga-clinical-analysis-grid");
                } else {
                    return true;
                }
            });*/

        // reading from the first row the case Id, the proband Id, and the Family Id and use them as filters
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000})
            .find("td:nth-child(1) a[data-cy='case-id']")
            .then($a => {
                const caseId = $a.text().trim();
                cy.get("div[data-cy='form-case'] button").click();
                cy.get("div[data-cy='form-case'] input").type(caseId + "{enter}", {force: true});
                checkResults("opencga-clinical-analysis-grid");

            })

            .find("td:nth-child(2) span[data-cy='proband-id']")
            .then($div => {
                const probandId = $div.text().trim();
                console.log("probandId", probandId);
                cy.get("div[data-cy='form-proband'] button").click();
                cy.get("div[data-cy='form-proband'] input").type(probandId + "{enter}", {force: true});
                checkResults("opencga-clinical-analysis-grid");

            });

        // cy.get("opencga-clinical-review-cases .rhs button", {timeout: 60000}).should("be.visible").and("contain", "Clear").click()
        cy.get("button[data-cy='filter-button']").click({force: true});
        cy.get(".saved-filter-wrapper a").contains("Clear").click({force: true});

    });

    it("5.2 - check Columns togglability", () => {
        cy.get("a[data-id=clinicalAnalysisPortal]", {timeout: 60000}).click({force: true});
        cy.get("div.page-title h2", {timeout: 60000}).should("be.visible").and("contain", "Case Portal");

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper button").should("be.visible").and("contain", "Columns").click();
        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li").should("have.length.gt", 1);

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li a").click({multiple: true, timeout: 60000}); // deactivate all the columns
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000}).find("td", {timeout: 60000}).should("have.lengthOf", 1);

        cy.get("opencga-clinical-analysis-grid .columns-toggle-wrapper ul li a").click({multiple: true, timeout: 60000}); // reactivate all the columns
        cy.get("opencga-clinical-analysis-grid .bootstrap-table .fixed-table-container tr[data-index=0]", {timeout: 60000}).find("td", {timeout: 60000}).should("have.length.gt", 1);

    });

});

/* cy.get("variant-browser-grid .columns-toggle-wrapper ul li a").each(($li, index, $lis) => {
    //Cypress.$("a", $li)
});*/
<|endoftext|>


<commit_before>/*
*   create by vinc 31 Dec 2016
*   canvas tiny process
*   @core   def extend 暴露合并api
*   @cache  缓存对象 参数:str/array/obj/REG str缓存图片 array缓存图片队列 obj缓存自建对象并初始化对象池 REG正则对象替换路径
*   @events maps初始化命中表
*   @draw   主线程循环
*   @await  异步流程控制
*
*/

( function() {

    //Util 公共方法
    var util = {
        //判断是否数组
        isArray : function(v){
                    return toString.apply(v) === '[object Array]';
        }

    }

    //判断是用函数创建的还是用new创建的
    //Meg(config) 或者  new Meg(config)
    function Meg(options) {
      if ( !(this instanceof Meg) )   return new Meg(options);

        //参数合并
        this._init(options);
        //暴露合并接口
        this.options = this.extend({},options);
    }

    var mg = Meg.prototype;

    //初始化
    mg._init = function(options){
        options = options || {};
        this.methods = {};
        this.maps = {};
        this.cache = {};

        var defaults = {
            root: './',         // 根节点
            maps: {},           // 初始化命中表
            debug: false,       // 如果开启debug模式，则进入自动检索当前目录文件模式
            cache: true,        // 是否使用缓存
            noop: true,         // 是否创建对象池
            sprit: true,        // 是否创建精灵图
            diffMatrix: true,   // 是否开启二值化像素矩阵

            useCache: false,    // 如果设为true，则使用http缓存
            maxCacheSize: 0.5   // 小于maxCacheSize的资源将以本地文件内容的md5值作为Etag，单位为MB
        };

        for (var key in defaults) {
            this[key] = options.hasOwnProperty(key) ? options[key] : defaults[key];
        }

        this.handleMap();

        return this;
    }

    mg.raf = (function(){
			return window.requestAnimationFrame ||
                   window.webkitRequestAnimationFrame ||
                   window.mozRequestAnimationFrame ||
                   window.oRequestAnimationFrame ||
                   window.msRequestAnimationFrame ||
                   function (callback) {window.setTimeout(callback, 1000 / 60);
                };
		})();

} )( window, Meg || {} )
<commit_msg>Update meg.js<commit_after>/*
*   create by vinc 31 Dec 2016
*   canvas tiny process
*   @core   def extend 暴露合并api
*   @cache  缓存对象 参数:str/array/obj/REG str缓存图片 array缓存图片队列 obj缓存自建对象并初始化对象池 REG正则对象替换路径
*   @events maps初始化命中表
*   @draw   主线程循环
*   @await  异步流程控制
*
*/

( function() {

    //Util 公共方法
    var util = {
        //判断是否数组
        isArray : function(v){
                    return toString.apply(v) === '[object Array]';
        }

    }

    //Meg(config) || new Meg(config)
    function Meg(options) {
      if ( !(this instanceof Meg) )   return new Meg(options);

        //参数合并
        this._init(options);
        //暴露合并接口
        this.options = this.extend({},options);
    }

    var mg = Meg.prototype;

    //初始化
    mg._init = function(options){
        options = options || {};
        this.methods = {};
        this.maps = {};
        this.cache = {};

        var defaults = {
            root: './',         // 根节点
            maps: {},           // 初始化命中表
            debug: false,       // 如果开启debug模式，则进入自动检索当前目录文件模式
            cache: true,        // 是否使用缓存
            noop: true,         // 是否创建对象池
            sprit: true,        // 是否创建精灵图
            diffMatrix: true,   // 是否开启二值化像素矩阵

            useCache: false,    // 如果设为true，则使用http缓存
            maxCacheSize: 0.5   // 小于maxCacheSize的资源将以本地文件内容的md5值作为Etag，单位为MB
        };

        for (var key in defaults) {
            this[key] = options.hasOwnProperty(key) ? options[key] : defaults[key];
        }

        this.handleMap();

        return this;
    }

    mg.raf = (function(){
			return window.requestAnimationFrame ||
                   window.webkitRequestAnimationFrame ||
                   window.mozRequestAnimationFrame ||
                   window.oRequestAnimationFrame ||
                   window.msRequestAnimationFrame ||
                   function (callback) {window.setTimeout(callback, 1000 / 60);
                };
		})();

} )( window, Meg || {} )
<|endoftext|>


<commit_before><commit_msg>removed verbose console.log(filter.string)<commit_after><|endoftext|>


<commit_before>Ti.include('cocoafish.js');
var Events = {};
/*
 *  <property name="acs-oauth-secret-development" type="string">GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k</property>
 *  <property name="acs-oauth-key-development" type="string">1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld</property>
 *  <property name="acs-api-key-development" type="string">1PlafvOb0KsfJhWw68tWkGiVt3IkhjxR</property>
 */
var sdk = new Cocoafish('1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld','GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k');
Events.create = function(_data){
  var custom_field = {club:_data.club};
  _data.custom_fields = JSON.stringify(custom_field);
  sdk.sendRequest('events/create.json', 'POST', _data, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });

};

Events.queryClub = function(_club,_callback){
  var whereString = JSON.stringify(Util.createSet([_club]));
  var query = {
    where: whereString
  };
  sdk.sendRequest('events/query.json', 'GET', query, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'queryEvents') {
          var events = data.response.events;
          Ti.API.log(events);
          _callback(events);
        }
      }
    }
  });

};

Events.deleteEvent = function(_id){
  var postData = {event_id : _id};
  sdk.sendRequest('events/delete.json', 'DELETE', postData, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });
}

<commit_msg>changed queryclub to take an array of clubs<commit_after>Ti.include('cocoafish.js');
var Events = {};
/*
 *  <property name="acs-oauth-secret-development" type="string">GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k</property>
 *  <property name="acs-oauth-key-development" type="string">1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld</property>
 *  <property name="acs-api-key-development" type="string">1PlafvOb0KsfJhWw68tWkGiVt3IkhjxR</property>
 */
var sdk = new Cocoafish('1iHEqePuYFs3SFXcaVwNIB4nAx3G99Ld','GxvXXCNnjESPojJkCXvGBGdjOJD5kc8k');
Events.create = function(_data){
  var custom_field = {club:_data.club};
  _data.custom_fields = JSON.stringify(custom_field);
  sdk.sendRequest('events/create.json', 'POST', _data, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });

};

Events.queryClub = function(_clubs,_callback){
  var whereString = JSON.stringify(Util.createSet(_clubs));
  var query = {
    where: whereString
  };
  sdk.sendRequest('events/query.json', 'GET', query, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'queryEvents') {
          var events = data.response.events;
          Ti.API.log(events);
          _callback(events);
        }
      }
    }
  });

};

Events.deleteEvent = function(_id){
  var postData = {event_id : _id};
  sdk.sendRequest('events/delete.json', 'DELETE', postData, function(data){
    if(data) {
      if(data.meta) {
        var meta = data.meta;
        if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createEvent') {
      	  Ti.API.log(data.response);
        }
      }
    }
  });
}

<|endoftext|>


<commit_before>/* jshint -W030,-W117 */

/*
 * grunt-EmailBuilder
 * https://github.com/yargalot/Email-Builder
 *
 * Copyright (c) 2013 Steven Miller
 * Licensed under the MIT license.
 */

 // Required modules
var juice     = require('juice'),
    path      = require('path'),
    cheerio   = require('cheerio'),
    async     = require('async'),
    encode    = require('./entityEncode'),
    Litmus    = require('./litmus');

function EmailBuilder(task) {

  this.task     = task;
  this.options  = task.options(EmailBuilder.Defaults);
  this.basepath = process.cwd();

  // Cheerio
  // ---------------
  this.$;
  this.$title;
  this.$doctype;
  this.$styleTags;
  this.$styleLinks;

}

EmailBuilder.taskName         = 'emailBuilder';
EmailBuilder.taskDescription  = 'Compile Files';
EmailBuilder.Defaults         = {};

EmailBuilder.prototype.run = function(grunt) {

  var _that   = this;

  this.task.files.forEach(function(file) {

    var fileData = grunt.file.read(file.src);
    var date     = grunt.template.today('yyyy-mm-dd');

    // Cheerio Init
    $           = cheerio.load(fileData);
    $title      = $('title').text() + date || date;
    $doctype    = $._root.children[0].data;
    $styleTags  = $('style');
    $styleLinks = $('link');

    // Read Css Files
    var srcFiles    = _that.linkTags($styleLinks);
    var embeddedCss = _that.styleTags($styleTags);
    var externalCss = _that.externalCss(srcFiles, file.src);
    var allCss      = embeddedCss + externalCss;

    // Get file output ready
    var output     = allCss ? juice.inlineContent($.html(), allCss) : $.html();

    // Encode special characters if option encodeSpecialChars is true
    if(_that.options.encodeSpecialChars === true) {
      output = encode.htmlEncode(output);
    }

    _that.writeFile(file.dest, output);

  });
};

EmailBuilder.prototype.externalCss = function(files, fileSource) {

  var externalCss = '';
  var grunt = this.task.grunt;

  // Set to target file path to get css
  grunt.file.setBase(path.dirname(fileSource));

  files.forEach(function(srcFile) {
    var css = grunt.file.read(srcFile.file);

    if(srcFile.inline) {
      externalCss += css;
    } else {
      $('head').append('<style>' + css + '</style>');
    }
  });

  // Set cwd back to root folder
  grunt.file.setBase(this.basepath);

  return externalCss;

};

// If doctype options is true, preserve doctype or add HTML5 doctype since jsdom removes it
EmailBuilder.prototype.docType = function(output) {

  var doctyped = '';

  if ( this.options.doctype === true ) {

    if ( $doctype.trim().length ) {
      doctyped = '<' + $doctype + '>' + output;
    } else {
      doctyped = '<!DOCTYPE html>' + output;
    }

  }

  return doctyped;

};

EmailBuilder.prototype.styleTags = function(styleTags) {

  var css = '';

  styleTags.each(function(i, element){
    var $this = $(this);

    if(!$this.attr('data-ignore')) {
      css += $this.text();
      $this.remove();
    }
  });

  return css;

};

EmailBuilder.prototype.linkTags = function(styleLinks) {

  var linkedStyles = [];

  styleLinks.each(function(i, link) {
    var $this = $(this),
        target = $this.attr('href'),
        map = {
          file: target,
          inline: $this.attr('data-ignore') ? false : true
        };

    linkedStyles.push(map);
    $this.remove();
  });

  return linkedStyles;

};

EmailBuilder.prototype.writeFile = function(fileDest, fileData) {

  var grunt     = this.task.grunt;
  var writeData = this.docType(fileData);

  grunt.log.writeln('Writing...'.cyan);
  grunt.file.write(fileDest, writeData);
  grunt.log.writeln('File ' + fileDest.cyan + ' created.');

  if (this.options.litmus) {
    this.litmus(writeData);
  }

};

EmailBuilder.prototype.litmus = function(emailData) {

  var litmus = new Litmus(this.options.litmus);

  // If subject is set but is empty set it to $title
  if(this.options.litmus.subject.trim().length === 0) {
    this.options.litmus.subject = $title;
  }

  litmus.run(emailData, $title);

};

EmailBuilder.registerWithGrunt = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask(EmailBuilder.taskName, EmailBuilder.taskDescription, function() {

    this.grunt = grunt;

    var task = new EmailBuilder(this);

    task.run(grunt);
  });
};

module.exports = EmailBuilder;<commit_msg>Adjusting docType function so that doctype is added by default unless option is set to false<commit_after>/* jshint -W030,-W117 */

/*
 * grunt-EmailBuilder
 * https://github.com/yargalot/Email-Builder
 *
 * Copyright (c) 2013 Steven Miller
 * Licensed under the MIT license.
 */

 // Required modules
var juice     = require('juice'),
    path      = require('path'),
    cheerio   = require('cheerio'),
    async     = require('async'),
    encode    = require('./entityEncode'),
    Litmus    = require('./litmus');

function EmailBuilder(task) {

  this.task     = task;
  this.options  = task.options(EmailBuilder.Defaults);
  this.basepath = process.cwd();

  // Cheerio
  // ---------------
  this.$;
  this.$title;
  this.$doctype;
  this.$styleTags;
  this.$styleLinks;

}

EmailBuilder.taskName         = 'emailBuilder';
EmailBuilder.taskDescription  = 'Compile Files';
EmailBuilder.Defaults         = {};

EmailBuilder.prototype.run = function(grunt) {

  var _that   = this;

  this.task.files.forEach(function(file) {

    var fileData = grunt.file.read(file.src);
    var date     = grunt.template.today('yyyy-mm-dd');

    // Cheerio Init
    $           = cheerio.load(fileData);
    $title      = $('title').text() + date || date;
    $doctype    = $._root.children[0].data;
    $styleTags  = $('style');
    $styleLinks = $('link');

    // Read Css Files
    var srcFiles    = _that.linkTags($styleLinks);
    var embeddedCss = _that.styleTags($styleTags);
    var externalCss = _that.externalCss(srcFiles, file.src);
    var allCss      = embeddedCss + externalCss;

    // Get file output ready
    var output     = allCss ? juice.inlineContent($.html(), allCss) : $.html();

    // Encode special characters if option encodeSpecialChars is true
    if(_that.options.encodeSpecialChars === true) {
      output = encode.htmlEncode(output);
    }

    _that.writeFile(file.dest, output);

  });
};

EmailBuilder.prototype.externalCss = function(files, fileSource) {

  var externalCss = '';
  var grunt = this.task.grunt;

  // Set to target file path to get css
  grunt.file.setBase(path.dirname(fileSource));

  files.forEach(function(srcFile) {
    var css = grunt.file.read(srcFile.file);

    if(srcFile.inline) {
      externalCss += css;
    } else {
      $('head').append('<style>' + css + '</style>');
    }
  });

  // Set cwd back to root folder
  grunt.file.setBase(this.basepath);

  return externalCss;

};

// If doctype options is true, preserve doctype or add HTML5 doctype since jsdom removes it
EmailBuilder.prototype.docType = function(output) {

  var doctyped = '';

  if ( this.options.doctype !== false ) {

    if ( $doctype.trim().length ) {
      doctyped = '<' + $doctype + '>' + output;
    } else {
      doctyped = '<!DOCTYPE html>' + output;
    }

  }else{
    doctyped = output;
  }

  return doctyped;

};

EmailBuilder.prototype.styleTags = function(styleTags) {

  var css = '';

  styleTags.each(function(i, element){
    var $this = $(this);

    if(!$this.attr('data-ignore')) {
      css += $this.text();
      $this.remove();
    }
  });

  return css;

};

EmailBuilder.prototype.linkTags = function(styleLinks) {

  var linkedStyles = [];

  styleLinks.each(function(i, link) {
    var $this = $(this),
        target = $this.attr('href'),
        map = {
          file: target,
          inline: $this.attr('data-ignore') ? false : true
        };

    linkedStyles.push(map);
    $this.remove();
  });

  return linkedStyles;

};

EmailBuilder.prototype.writeFile = function(fileDest, fileData) {

  var grunt     = this.task.grunt;
  var writeData = this.docType(fileData);

  grunt.log.writeln('Writing...'.cyan);
  grunt.file.write(fileDest, writeData);
  grunt.log.writeln('File ' + fileDest.cyan + ' created.');

  if (this.options.litmus) {
    this.litmus(writeData);
  }

};

EmailBuilder.prototype.litmus = function(emailData) {

  var litmus = new Litmus(this.options.litmus);

  // If subject is set but is empty set it to $title
  if(this.options.litmus.subject.trim().length === 0) {
    this.options.litmus.subject = $title;
  }

  litmus.run(emailData, $title);

};

EmailBuilder.registerWithGrunt = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask(EmailBuilder.taskName, EmailBuilder.taskDescription, function() {

    this.grunt = grunt;

    var task = new EmailBuilder(this);

    task.run(grunt);
  });
};

module.exports = EmailBuilder;<|endoftext|>


<commit_before>var inherits = require('util').inherits
  , EventEmitter = require('events').EventEmitter;

var ZipBlocksFactory = module.exports = function () {
  var zipBlocks = new ZipBlocks();
  zipBlocks.on('error', zipBlocks._onError);
  zipBlocks.on('newListener', zipBlocks._syncErrorListener);
  return zipBlocks;
};

function ZipBlocks() {
  'use strict';
  this._BLOCK_SIZE_UNIT = 1000000;  // = 1 million
  this._blockSize = 20;             // = 20 MB for unit of 1 MB
  this._compressionRatio = 1;       // for files with high compression ratio
  this._filesOnly = true;
  this._addOversize = true;

  this._onError = function (err) {
    console.error(err.stack); // defualt error handling
  };
}

inherits(ZipBlocks, EventEmitter);

ZipBlocks.prototype.setCompressionRatio = setCompressionRatio;
ZipBlocks.prototype.zipFilesInDir = zipFilesInDir;
ZipBlocks.prototype._syncErrorListener = _syncErrorListener;

function  _syncErrorListener(event, listener) {
  if (event === 'error') {
    this.removeListener('error', this._onError);
    this._onError = listener;
  }
}

function setCompressionRatio(ratio) {
  var _RATIO_ERROR_STRING = 'Compression ratio must be between 0.01 and 1, inclusive. Using 1.';
  if (ratio < 0.01 || 1 < ratio) {
    this.emit('error', new Error(_RATIO_ERROR_STRING));
    return;
  }
  this._compressionRatio = ratio;
}

function zipFilesInDir(inputDir, outputDir, options) {
  'use strict';
  var fs = require('fs')
    , path = require('path')
    , USAGE_STRING = 'Usage: zipFilesInDir(inputDir, [outputDir], [blockSize]).'
    , filesReady = 0
    , thisZB = this;

  if (arguments.length < 1 || 3 < arguments.length) {
    thisZB.emit('error', new Error(USAGE_STRING));
    return;
  }

  if (typeof outputDir === 'string') {
    if (typeof options === 'object') {
      parseOptions(options);
    }
  } else {
    outputDir = ''; // use empty str if undefined so fs.exists doesn't throw

    if (typeof outputDir === 'object') {
      parseOptions(outputDir);
    }
  }

  fs.exists(outputDir, function (existsOut) {
    if (!existsOut) outputDir = inputDir;
    getListingAndZip();
  });

  function parseOptions(options) {
    for (var key in options) {
      switch (key) {
      case 'blockSize':
        thisZB._blockSize = options[key];
        break;
      case 'compressionRatio':
        thisZB._compressionRatio = options[key];
        break;
      case 'filesOnly':
        thisZB._filesOnly = options[key];
        break;
      case 'addOversize':
        thisZB._addOversize = options[key];
      }
    }
  }

  function getListingAndZip() {
    var du = require('du');

    fs.readdir(inputDir, function (err, listing) {
      var files = {};

      if (err) {
        thisZB.emit('error', err);
        return;
      }
      for (var item in listing) {
        runStat(path.join(inputDir, listing[item]));
      }

      function runStat(filePath) {
        fs.stat(filePath, function (err, stats) {
          var thisFile;

          if (err) {
            thisZB.emit('error', err);
            checkAllStatsCollected();
            return;
          }

          if (stats.isDirectory()) {
            if (!thisZB._filesOnly) {
              thisFile = files[filePath] = {};
              thisFile.isDir = true;
              setDirSize(filePath, thisFile);
            } else {
              checkAllStatsCollected();
            }
          } else if (stats.isFile()) {
            thisFile = files[filePath] = {};
            thisFile.isDir = false;
            thisFile.size = stats.size;
            checkAllStatsCollected();
          }
        });

        function setDirSize(dir, objWithSizeField) {
          du(dir, function (err, size) {
            if (err) {
              thisZB.emit('error', err);
            } else {
              objWithSizeField.size = size;
            }
            checkAllStatsCollected();
          });
        }

        function checkAllStatsCollected() {
          ++filesReady;
          if (filesReady === listing.length) {
            doZip(getBlocks(files));
          }
        }
      }
    });
  }

  function getBlocks(files) {
    var blocks = []
      , total = 0
      , blockNum = 0
      , max = thisZB._blockSize * thisZB._BLOCK_SIZE_UNIT / thisZB._compressionRatio;

    blocks[blockNum] = {};
    for (var key in files) {
      if (files[key].size > max) {
        if (thisZB._addOversize) {
          blocks[blockNum + 1] = blocks[blockNum];
          blocks[blockNum] = {};
          blocks[blockNum][key] = files[key];
          ++blockNum;
        } else {
          thisZB.emit('error', new Error(key + ' is too big for any block - file skipped.'));
        }
        continue;
      }

      total += files[key].size;
      if (total > max) {
        blockNum += 1;
        blocks[blockNum] = {};

        total = files[key].size;
      }
      blocks[blockNum][key] = files[key];
    }
    return blocks;
  }

  function doZip(blocks) {
    var archiver = require('archiver')
      , zip
      , zipFileName
      , outFile
      , thisBlock;

    for (var zipNum in blocks) {
      zipFileName = path.join(outputDir,
                              path.basename(inputDir) + '_' + zipNum + '.zip');
      outFile = fs.createWriteStream(zipFileName);
      zip = archiver('zip');
      zip.on('error', thisZB.emit.bind(thisZB, 'error'));
      zip.pipe(outFile);

      thisBlock = blocks[zipNum];
      for (var key in thisBlock) {
        if (thisBlock[key].isDir) {
          zip.directory(key, path.basename(key));
        } else {
          zip.append(fs.createReadStream(key), { name: path.basename(key) });
        }
      }
      zip.finalize();
    }
  }
}
<commit_msg>Factor out option handling (phase 1). Remove error sync function from zip-blocks obj.<commit_after>var inherits = require('util').inherits
  , EventEmitter = require('events').EventEmitter;

var ZipBlocksFactory = module.exports = function () {
  var zipBlocks = new ZipBlocks();
  zipBlocks.on('error', zipBlocks._onError);
  zipBlocks.on('newListener', syncErrorListener.bind(zipBlocks));
  return zipBlocks;
};

function ZipBlocks() {
  'use strict';
  this._BLOCK_SIZE_UNIT = 1000000;  // = 1 million
  this._blockSize = 20;             // = 20 MB for unit of 1 MB
  this._compressionRatio = 1;       // for files with high compression ratio
  this._filesOnly = true;
  this._addOversize = true;

  this._onError = function (err) {
    console.error(err.stack); // defualt error handling
  };
}

inherits(ZipBlocks, EventEmitter);

ZipBlocks.prototype.setCompressionRatio = setCompressionRatio;
ZipBlocks.prototype.setOptions = setOptions;
ZipBlocks.prototype.zipFilesInDir = zipFilesInDir;

function  syncErrorListener(event, listener) {
  if (event === 'error') {
    this.removeListener('error', this._onError);
    this._onError = listener;
  }
}

function setCompressionRatio(ratio) {
  var _RATIO_ERROR_STRING = 'Compression ratio must be between 0.01 and 1, inclusive. Using 1.';
  if (ratio < 0.01 || 1 < ratio) {
    this.emit('error', new Error(_RATIO_ERROR_STRING));
    return;
  }
  this._compressionRatio = ratio;
}

function setOptions(options) {
  parseOptions.call(this, options);
}

function parseOptions(options) {
  for (var key in options) {
    switch (key) {
    case 'blockSize':
      this._blockSize = options[key];
      break;
    case 'compressionRatio':
      setCompressionRatio.call(this, options[key])
      break;
    case 'filesOnly':
      this._filesOnly = options[key];
      break;
    case 'addOversize':
      this._addOversize = options[key];
    }
  }
}

function zipFilesInDir(inputDir, outputDir, options) {
  'use strict';
  var fs = require('fs')
    , path = require('path')
    , USAGE_STRING = 'Usage: zipFilesInDir(inputDir, [outputDir], [blockSize]).'
    , filesReady = 0
    , thisZB = this;

  if (arguments.length < 1 || 3 < arguments.length) {
    thisZB.emit('error', new Error(USAGE_STRING));
    return;
  }

  if (typeof outputDir === 'string') {
    if (typeof options === 'object') {
      parseOptions.call(this, options);
    }
  } else {
    outputDir = ''; // use empty str if undefined so fs.exists doesn't throw

    if (typeof outputDir === 'object') {
      parseOptions.call(this, outputDir);
    }
  }

  fs.exists(outputDir, function (existsOut) {
    if (!existsOut) outputDir = inputDir;
    getListingAndZip();
  });

  function getListingAndZip() {
    var du = require('du');

    fs.readdir(inputDir, function (err, listing) {
      var files = {};

      if (err) {
        thisZB.emit('error', err);
        return;
      }
      for (var item in listing) {
        runStat(path.join(inputDir, listing[item]));
      }

      function runStat(filePath) {
        fs.stat(filePath, function (err, stats) {
          var thisFile;

          if (err) {
            thisZB.emit('error', err);
            checkAllStatsCollected();
            return;
          }

          if (stats.isDirectory()) {
            if (!thisZB._filesOnly) {
              thisFile = files[filePath] = {};
              thisFile.isDir = true;
              setDirSize(filePath, thisFile);
            } else {
              checkAllStatsCollected();
            }
          } else if (stats.isFile()) {
            thisFile = files[filePath] = {};
            thisFile.isDir = false;
            thisFile.size = stats.size;
            checkAllStatsCollected();
          }
        });

        function setDirSize(dir, objWithSizeField) {
          du(dir, function (err, size) {
            if (err) {
              thisZB.emit('error', err);
            } else {
              objWithSizeField.size = size;
            }
            checkAllStatsCollected();
          });
        }

        function checkAllStatsCollected() {
          ++filesReady;
          if (filesReady === listing.length) {
            doZip(getBlocks(files));
          }
        }
      }
    });
  }

  function getBlocks(files) {
    var blocks = []
      , total = 0
      , blockNum = 0
      , max = thisZB._blockSize * thisZB._BLOCK_SIZE_UNIT / thisZB._compressionRatio;

    blocks[blockNum] = {};
    for (var key in files) {
      if (files[key].size > max) {
        if (thisZB._addOversize) {
          blocks[blockNum + 1] = blocks[blockNum];
          blocks[blockNum] = {};
          blocks[blockNum][key] = files[key];
          ++blockNum;
        } else {
          thisZB.emit('error', new Error(key + ' is too big for any block - file skipped.'));
        }
        continue;
      }

      total += files[key].size;
      if (total > max) {
        blockNum += 1;
        blocks[blockNum] = {};

        total = files[key].size;
      }
      blocks[blockNum][key] = files[key];
    }
    return blocks;
  }

  function doZip(blocks) {
    var archiver = require('archiver')
      , zip
      , zipFileName
      , outFile
      , thisBlock;

    for (var zipNum in blocks) {
      zipFileName = path.join(outputDir,
                              path.basename(inputDir) + '_' + zipNum + '.zip');
      outFile = fs.createWriteStream(zipFileName);
      zip = archiver('zip');
      zip.on('error', thisZB.emit.bind(thisZB, 'error'));
      zip.pipe(outFile);

      thisBlock = blocks[zipNum];
      for (var key in thisBlock) {
        if (thisBlock[key].isDir) {
          zip.directory(key, path.basename(key));
        } else {
          zip.append(fs.createReadStream(key), { name: path.basename(key) });
        }
      }
      zip.finalize();
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Created by ameyapandilwar on 2/17/16.
 */

(function () {
    "use strict";
    angular
        .module("FormBuilderApp")
        .controller("SidebarController", SidebarController);

    function SidebarController($scope, $location) {

    }
}());<commit_msg>Update sidebar view and controller<commit_after>/**
 * Created by ameyapandilwar on 2/17/16.
 */

(function () {
    "use strict";
    angular
        .module("FormBuilderApp")
        .controller("SidebarController", SidebarController);

    function SidebarController($location) {

    }
}());<|endoftext|>