<commit_before>$(function() {
    // Ajax Setup
    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        var token;
        if (! options.crossDomain) {
            token = $('meta[name="token"]').attr('content');
            if (token) {
                jqXHR.setRequestHeader('X-CSRF-Token', token);
            }
        }

        return jqXHR;
    });

    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Accept', 'application/json');
            // xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        },
        statusCode: {
            401: function () {
                window.location.href = '/';
            },
            403: function () {
                window.location.href = '/';
            }
        }
    });

    // Prevent double form submission
    $('form').submit(function() {
        var $form = $(this);
        $form.find(':submit').prop('disabled', true);
    });

    // Autosizing of textareas.
    autosize($('textarea.autosize'));

    // Mock the DELETE form requests.
    $('[data-method]').not(".disabled").append(function() {
        var methodForm = "\n";
        methodForm    += "<form action='" + $(this).attr('href') + "' method='POST' style='display:none'>\n";
        methodForm    += " <input type='hidden' name='_method' value='" + $(this).attr('data-method') + "'>\n";
        if ($(this).attr('data-token')) {
            methodForm += "<input type='hidden' name='_token' value='" + $(this).attr('data-token') + "'>\n";
        }
        methodForm += "</form>\n";
        return methodForm;
    })
        .removeAttr('href')
        .on('click', function() {
            var button = $(this);

            if (button.hasClass('confirm-action')) {
                askConfirmation(function() {
                    button.find("form").submit();
                });
            } else {
                button.find("form").submit();
            }
        });

    // Messenger config
    Messenger.options = {
        extraClasses: 'messenger-fixed messenger-on-top',
        theme: 'air'
    };

    // App setup
    window.Cachet = {};

    moment.locale(Global.locale);

    $('abbr.timeago').each(function () {
        var $el = $(this);
        $el
            .livestamp($el.data('timeago'))
            .tooltip();
    });

    window.Cachet.Notifier = function () {
        this.notify = function (message, type, options) {
            type = (typeof type === 'undefined' || type === 'error') ? 'error' : type;

            var defaultOptions = {
                message: message,
                type: type,
                showCloseButton: true
            };

            options = _.extend(defaultOptions, options);

            Messenger().post(options);
        };
    };

    $(".sidebar-toggler").click(function(e) {
        e.preventDefault();
        $(".wrapper").toggleClass("toggled");
    });

    $('.color-code').minicolors({
        control: 'hue',
        defaultValue: $(this).val() || '',
        inline: false,
        letterCase: 'lowercase',
        opacity: false,
        position: 'bottom left',
        theme: 'bootstrap'
    });

    $('[data-toggle="tooltip"]').tooltip();

    $('button.close').on('click', function() {
        $(this).parents('div.alert').addClass('hide');
    });

    $('form[name=IncidentForm] select[name=component_id]').on('change', function() {
        var $option = $(this).find('option:selected');
        var $componentStatus = $('#component-status');

        if ($option.val() !== '') {
            if ($componentStatus.hasClass('hidden')) {
                $componentStatus.removeClass('hidden');
            } else {
                $componentStatus.addClass('hidden');
            }
        }
    });

    // Date picker.
    $('input[rel=datepicker]').datetimepicker({
        format: "DD/MM/YYYY HH:mm",
        minDate: new Date(), // Don't allow dates before today.
        sideBySide: true,
        icons: {
            time: 'ion-clock',
            date: 'ion-android-calendar',
            up: 'ion-ios-arrow-up',
            down: 'ion-ios-arrow-down',
            previous: 'ion-ios-arrow-left',
            next: 'ion-ios-arrow-right',
            today: 'ion-android-home',
            clear: 'ion-trash-a',
        }
    });

    $('input[rel=datepicker-any]').datetimepicker({
        format: "DD/MM/YYYY HH:mm",
        sideBySide: true,
        icons: {
            time: 'ion-clock',
            date: 'ion-android-calendar',
            up: 'ion-ios-arrow-up',
            down: 'ion-ios-arrow-down',
            previous: 'ion-ios-arrow-left',
            next: 'ion-ios-arrow-right',
            today: 'ion-android-home',
            clear: 'ion-trash-a',
        }
    });

    // Sortable components.
    var componentList = document.getElementById("component-list");
    if (componentList) {
        new Sortable(componentList, {
            group: "omega",
            handle: ".drag-handle",
            onUpdate: function() {
                var orderedComponentIds = $.map($('#component-list .striped-list-item'), function(elem) {
                    return $(elem).data('component-id');
                });

                $.ajax({
                    async: true,
                    url: '/dashboard/api/components/order',
                    type: 'POST',
                    data: {
                        ids: orderedComponentIds
                    },
                    success: function() {
                        (new Cachet.Notifier()).notify('Component orders updated.', 'success');
                    },
                    error: function() {
                        (new Cachet.Notifier()).notify('Component orders not updated.', 'error');
                    }
                });
            }
        });
    }

    // Sortable Component Groups
    var componentGroupList = document.getElementById("component-group-list");
    if (componentGroupList) {
        new Sortable(componentGroupList, {
            group: "omega",
            handle: ".drag-handle",
            onUpdate: function() {
                var orderedComponentGroupsIds = $.map(
                    $('#component-group-list .striped-list-item'),
                    function(elem) {
                        return $(elem).data('group-id');
                    }
                );
                $.ajax({
                    async: true,
                    url: '/dashboard/api/components/groups/order',
                    type: 'POST',
                    data: {ids: orderedComponentGroupsIds},
                    success: function() {
                        (new Cachet.Notifier()).notify('Component groups order has been updated.', 'success');
                    },
                    error: function() {
                        (new Cachet.Notifier()).notify('Component groups order could not be updated.', 'error');
                    }
                });
            }
        });
    }

    // Toggle inline component statuses.
    $('form.component-inline').on('click', 'input[type=radio]', function() {
        var $form = $(this).parents('form');
        var formData = $form.serializeObject();

        $.ajax({
            async: true,
            url: '/dashboard/api/components/' + formData.component_id,
            type: 'POST',
            data: formData,
            success: function(component) {
                (new Cachet.Notifier()).notify($form.data('messenger'), 'success');
            },
            error: function(a, b, c) {
                (new Cachet.Notifier()).notify('Something went wrong updating the component.');
            }
        });
    });

    // Incident management
    $('select[name=template]').on('change', function() {
        var $this = $(this).find('option:selected'),
            slug   = $this.val();

        // Only fetch the template if we've picked one.
        if (slug) {
            $.ajax({
                async: true,
                data: {
                    slug: slug
                },
                url: '/dashboard/api/incidents/templates',
                success: function(tpl) {
                    var $form = $('form[role=form]');
                    $form.find('input[name=incident\\[name\\]]').val(tpl.name);
                    $form.find('textarea[name=incident\\[message\\]]').val(tpl.template);
                },
                error: function() {
                    (new Cachet.Notifier()).notify('There was an error finding that template.');
                }
            });
        }
    });

    // Banner removal JS
    $('#remove-banner').click(function(){
        $('#banner-view').remove();
        $('input[name=remove_banner]').val('1');
    });

    $('.group-name').on('click', function () {
        var $this = $(this);

        $this.find('.group-toggle').toggleClass('ion-ios-minus-outline').toggleClass('ion-ios-plus-outline');

        $this.next('.group-items').toggleClass('hide');
    });

    // Setup wizard
    $('.wizard-next').on('click', function () {
        var $form   = $('#setup-form'),
            $btn    = $(this),
            current = $btn.data('currentBlock'),
            next    = $btn.data('nextBlock');

        $btn.button('loading');

        // Only validate going forward. If current group is invalid, do not go further
        if (next > current) {
            var url = '/setup/step' + current;
            $.post(url, $form.serializeObject())
                .done(function(response) {
                    goToStep(current, next);
                })
                .fail(function(response) {
                    var errors = _.toArray(response.responseJSON.errors);
                    _.each(errors, function(error) {
                        (new Cachet.Notifier()).notify(error);
                    });
                })
                .always(function() {
                    $btn.button('reset');
                });

            return false;
        } else {
            goToStep(current, next);
            $btn.button('reset');
        }
    });

    // Sparkline
    if ($.fn.sparkline) {
        var sparkLine = function () {
            $('.sparkline').each(function () {
                var data = $(this).data();
                data.valueSpots = {
                    '0:': data.spotColor
                };

                $(this).sparkline(data.data, data);
                var composite = data.compositedata;

                if (composite) {
                    var stlColor = $(this).attr("data-stack-line-color"),
                        stfColor = $(this).attr("data-stack-fill-color"),
                        sptColor = $(this).attr("data-stack-spot-color"),
                        sptRadius = $(this).attr("data-stack-spot-radius");

                    $(this).sparkline(composite, {
                        composite: true,
                        lineColor: stlColor,
                        fillColor: stfColor,
                        spotColor: sptColor,
                        highlightSpotColor: sptColor,
                        spotRadius: sptRadius,
                        valueSpots: {
                            '0:': sptColor
                        }
                    });
                };
            });
        };

        sparkLine(false);
    }

    function goToStep(current, next) {
        // validation was ok. We can go on next step.
        $('.block-' + current)
          .removeClass('show')
          .addClass('hidden');

        $('.block-' + next)
          .removeClass('hidden')
          .addClass('show');

        $('.steps .step')
            .removeClass("active")
            .filter(":lt(" + (next) + ")")
            .addClass("active");
    }

    // Password strength
    $('.password-strength').strengthify();

    // Check for updates.
    if ($('#update-alert').length > 0) {
        $.ajax({
            async: true,
            dataType: 'json',
            url: '/dashboard/api/system/version',
        }).done(function (result) {
            if (result.is_latest == false) {
                $('#update-alert').removeClass('hidden');
            }
        });
    }
});

function askConfirmation(callback) {
    swal({
        type: "warning",
        title: "Confirm your action",
        text: "Are you sure you want to do this?",
        confirmButtonText: "Yes",
        confirmButtonColor: "#FF6F6F",
        showCancelButton: true
    }, function() {
        callback();
    });
}
<commit_msg>Fixes #1339 - Ensure incident field names are the same everywhere<commit_after>$(function() {
    // Ajax Setup
    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        var token;
        if (! options.crossDomain) {
            token = $('meta[name="token"]').attr('content');
            if (token) {
                jqXHR.setRequestHeader('X-CSRF-Token', token);
            }
        }

        return jqXHR;
    });

    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Accept', 'application/json');
            // xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        },
        statusCode: {
            401: function () {
                window.location.href = '/';
            },
            403: function () {
                window.location.href = '/';
            }
        }
    });

    // Prevent double form submission
    $('form').submit(function() {
        var $form = $(this);
        $form.find(':submit').prop('disabled', true);
    });

    // Autosizing of textareas.
    autosize($('textarea.autosize'));

    // Mock the DELETE form requests.
    $('[data-method]').not(".disabled").append(function() {
        var methodForm = "\n";
        methodForm    += "<form action='" + $(this).attr('href') + "' method='POST' style='display:none'>\n";
        methodForm    += " <input type='hidden' name='_method' value='" + $(this).attr('data-method') + "'>\n";
        if ($(this).attr('data-token')) {
            methodForm += "<input type='hidden' name='_token' value='" + $(this).attr('data-token') + "'>\n";
        }
        methodForm += "</form>\n";
        return methodForm;
    })
        .removeAttr('href')
        .on('click', function() {
            var button = $(this);

            if (button.hasClass('confirm-action')) {
                askConfirmation(function() {
                    button.find("form").submit();
                });
            } else {
                button.find("form").submit();
            }
        });

    // Messenger config
    Messenger.options = {
        extraClasses: 'messenger-fixed messenger-on-top',
        theme: 'air'
    };

    // App setup
    window.Cachet = {};

    moment.locale(Global.locale);

    $('abbr.timeago').each(function () {
        var $el = $(this);
        $el
            .livestamp($el.data('timeago'))
            .tooltip();
    });

    window.Cachet.Notifier = function () {
        this.notify = function (message, type, options) {
            type = (typeof type === 'undefined' || type === 'error') ? 'error' : type;

            var defaultOptions = {
                message: message,
                type: type,
                showCloseButton: true
            };

            options = _.extend(defaultOptions, options);

            Messenger().post(options);
        };
    };

    $(".sidebar-toggler").click(function(e) {
        e.preventDefault();
        $(".wrapper").toggleClass("toggled");
    });

    $('.color-code').minicolors({
        control: 'hue',
        defaultValue: $(this).val() || '',
        inline: false,
        letterCase: 'lowercase',
        opacity: false,
        position: 'bottom left',
        theme: 'bootstrap'
    });

    $('[data-toggle="tooltip"]').tooltip();

    $('button.close').on('click', function() {
        $(this).parents('div.alert').addClass('hide');
    });

    $('form[name=IncidentForm] select[name=component_id]').on('change', function() {
        var $option = $(this).find('option:selected');
        var $componentStatus = $('#component-status');

        if ($option.val() !== '') {
            if ($componentStatus.hasClass('hidden')) {
                $componentStatus.removeClass('hidden');
            } else {
                $componentStatus.addClass('hidden');
            }
        }
    });

    // Date picker.
    $('input[rel=datepicker]').datetimepicker({
        format: "DD/MM/YYYY HH:mm",
        minDate: new Date(), // Don't allow dates before today.
        sideBySide: true,
        icons: {
            time: 'ion-clock',
            date: 'ion-android-calendar',
            up: 'ion-ios-arrow-up',
            down: 'ion-ios-arrow-down',
            previous: 'ion-ios-arrow-left',
            next: 'ion-ios-arrow-right',
            today: 'ion-android-home',
            clear: 'ion-trash-a',
        }
    });

    $('input[rel=datepicker-any]').datetimepicker({
        format: "DD/MM/YYYY HH:mm",
        sideBySide: true,
        icons: {
            time: 'ion-clock',
            date: 'ion-android-calendar',
            up: 'ion-ios-arrow-up',
            down: 'ion-ios-arrow-down',
            previous: 'ion-ios-arrow-left',
            next: 'ion-ios-arrow-right',
            today: 'ion-android-home',
            clear: 'ion-trash-a',
        }
    });

    // Sortable components.
    var componentList = document.getElementById("component-list");
    if (componentList) {
        new Sortable(componentList, {
            group: "omega",
            handle: ".drag-handle",
            onUpdate: function() {
                var orderedComponentIds = $.map($('#component-list .striped-list-item'), function(elem) {
                    return $(elem).data('component-id');
                });

                $.ajax({
                    async: true,
                    url: '/dashboard/api/components/order',
                    type: 'POST',
                    data: {
                        ids: orderedComponentIds
                    },
                    success: function() {
                        (new Cachet.Notifier()).notify('Component orders updated.', 'success');
                    },
                    error: function() {
                        (new Cachet.Notifier()).notify('Component orders not updated.', 'error');
                    }
                });
            }
        });
    }

    // Sortable Component Groups
    var componentGroupList = document.getElementById("component-group-list");
    if (componentGroupList) {
        new Sortable(componentGroupList, {
            group: "omega",
            handle: ".drag-handle",
            onUpdate: function() {
                var orderedComponentGroupsIds = $.map(
                    $('#component-group-list .striped-list-item'),
                    function(elem) {
                        return $(elem).data('group-id');
                    }
                );
                $.ajax({
                    async: true,
                    url: '/dashboard/api/components/groups/order',
                    type: 'POST',
                    data: {ids: orderedComponentGroupsIds},
                    success: function() {
                        (new Cachet.Notifier()).notify('Component groups order has been updated.', 'success');
                    },
                    error: function() {
                        (new Cachet.Notifier()).notify('Component groups order could not be updated.', 'error');
                    }
                });
            }
        });
    }

    // Toggle inline component statuses.
    $('form.component-inline').on('click', 'input[type=radio]', function() {
        var $form = $(this).parents('form');
        var formData = $form.serializeObject();

        $.ajax({
            async: true,
            url: '/dashboard/api/components/' + formData.component_id,
            type: 'POST',
            data: formData,
            success: function(component) {
                (new Cachet.Notifier()).notify($form.data('messenger'), 'success');
            },
            error: function(a, b, c) {
                (new Cachet.Notifier()).notify('Something went wrong updating the component.');
            }
        });
    });

    // Incident management
    $('select[name=template]').on('change', function() {
        var $this = $(this).find('option:selected'),
            slug   = $this.val();

        // Only fetch the template if we've picked one.
        if (slug) {
            $.ajax({
                async: true,
                data: {
                    slug: slug
                },
                url: '/dashboard/api/incidents/templates',
                success: function(tpl) {
                    var $form = $('form[role=form]');
                    $form.find('input[name=name]').val(tpl.name);
                    $form.find('textarea[name=message]').val(tpl.template);
                },
                error: function() {
                    (new Cachet.Notifier()).notify('There was an error finding that template.');
                }
            });
        }
    });

    // Banner removal JS
    $('#remove-banner').click(function(){
        $('#banner-view').remove();
        $('input[name=remove_banner]').val('1');
    });

    $('.group-name').on('click', function () {
        var $this = $(this);

        $this.find('.group-toggle').toggleClass('ion-ios-minus-outline').toggleClass('ion-ios-plus-outline');

        $this.next('.group-items').toggleClass('hide');
    });

    // Setup wizard
    $('.wizard-next').on('click', function () {
        var $form   = $('#setup-form'),
            $btn    = $(this),
            current = $btn.data('currentBlock'),
            next    = $btn.data('nextBlock');

        $btn.button('loading');

        // Only validate going forward. If current group is invalid, do not go further
        if (next > current) {
            var url = '/setup/step' + current;
            $.post(url, $form.serializeObject())
                .done(function(response) {
                    goToStep(current, next);
                })
                .fail(function(response) {
                    var errors = _.toArray(response.responseJSON.errors);
                    _.each(errors, function(error) {
                        (new Cachet.Notifier()).notify(error);
                    });
                })
                .always(function() {
                    $btn.button('reset');
                });

            return false;
        } else {
            goToStep(current, next);
            $btn.button('reset');
        }
    });

    // Sparkline
    if ($.fn.sparkline) {
        var sparkLine = function () {
            $('.sparkline').each(function () {
                var data = $(this).data();
                data.valueSpots = {
                    '0:': data.spotColor
                };

                $(this).sparkline(data.data, data);
                var composite = data.compositedata;

                if (composite) {
                    var stlColor = $(this).attr("data-stack-line-color"),
                        stfColor = $(this).attr("data-stack-fill-color"),
                        sptColor = $(this).attr("data-stack-spot-color"),
                        sptRadius = $(this).attr("data-stack-spot-radius");

                    $(this).sparkline(composite, {
                        composite: true,
                        lineColor: stlColor,
                        fillColor: stfColor,
                        spotColor: sptColor,
                        highlightSpotColor: sptColor,
                        spotRadius: sptRadius,
                        valueSpots: {
                            '0:': sptColor
                        }
                    });
                };
            });
        };

        sparkLine(false);
    }

    function goToStep(current, next) {
        // validation was ok. We can go on next step.
        $('.block-' + current)
          .removeClass('show')
          .addClass('hidden');

        $('.block-' + next)
          .removeClass('hidden')
          .addClass('show');

        $('.steps .step')
            .removeClass("active")
            .filter(":lt(" + (next) + ")")
            .addClass("active");
    }

    // Password strength
    $('.password-strength').strengthify();

    // Check for updates.
    if ($('#update-alert').length > 0) {
        $.ajax({
            async: true,
            dataType: 'json',
            url: '/dashboard/api/system/version',
        }).done(function (result) {
            if (result.is_latest == false) {
                $('#update-alert').removeClass('hidden');
            }
        });
    }
});

function askConfirmation(callback) {
    swal({
        type: "warning",
        title: "Confirm your action",
        text: "Are you sure you want to do this?",
        confirmButtonText: "Yes",
        confirmButtonColor: "#FF6F6F",
        showCancelButton: true
    }, function() {
        callback();
    });
}
<|endoftext|>


<commit_before>'use strict';

// Core modules
var fs = require('fs');
var path = require('path');

// External modules
var Bluebird   = require('bluebird');
var dateFormat = require('dateformat');

var changelog = module.exports = {
  update: function (args) {
    return Bluebird.resolve().then(function () {
      if (changelog.exists() && changelog.needsUpdate()) {
        return changelog.setVersion(args.version);
      }
    });
  },

  changelogPath: function () {
    return path.resolve(process.env.CHANGELOG_HOME || process.cwd(), 'CHANGELOG.md');
  },

  exists: function () {
    return fs.existsSync(this.changelogPath());
  },

  needsUpdate: function () {
    return this.read().indexOf('## Upcoming') > -1;
  },

  setVersion: function (version) {
    var currentContent = this.read();
    var date           = date;
    var formattedDate  = dateFormat(date, 'yyyy-mm-dd');
    var needle         = '## Upcoming';
    var replacement    = '## v' + version + ' - ' + formattedDate;

    this.write(currentContent.replace(needle, replacement));
  },

  read: function () {
    return fs.readFileSync(this.changelogPath()).toString();
  },

  write: function (newContent) {
    fs.writeFileSync(this.changelogPath(), newContent);
  }
};
<commit_msg>Fix changelog update<commit_after>'use strict';

// Core modules
var fs = require('fs');
var path = require('path');

// 3rd-party modules
var Bluebird   = require('bluebird');
var dateFormat = require('dateformat');

// Local modules
var helper = require('./misc');

var changelog = module.exports = {
  update: function (args) {
    return Bluebird.resolve().then(function () {
      if (changelog.exists() && changelog.needsUpdate()) {
        return changelog.setVersion(args.version).then(function () {
          return changelog.commitVersion(args.version);
        });
      }
    });
  },

  changelogPath: function () {
    return path.resolve(process.env.CHANGELOG_HOME || process.cwd(), 'CHANGELOG.md');
  },

  exists: function () {
    return fs.existsSync(this.changelogPath());
  },

  needsUpdate: function () {
    return this.read().indexOf('## Upcoming') > -1;
  },

  setVersion: function (version) {
    var currentContent = this.read();
    var date           = date;
    var formattedDate  = dateFormat(date, 'yyyy-mm-dd');
    var needle         = '## Upcoming';
    var replacement    = '## v' + version + ' - ' + formattedDate;

    this.write(currentContent.replace(needle, replacement));
  },

  read: function () {
    fs.readFileSync(this.changelogPath()).toString();
  },

  write: function (newContent) {
    fs.writeFileSync(this.changelogPath(), newContent);
  },

  commitVersion: function (version) {
    return helper.exec('git add CHANGELOG.md').then(function () {
      return helper.exec('git commit -m "Add changes in version: v' + version + '"');
    });
  }
};
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const util = require('util')
const hasha = require('hasha')

const analyzeDirectory = require('./analyzers/directory')
const analyzeName = require('./analyzers/name')
const analyzeTypes = require('./analyzers/types')
const analyzeArchive = require('./analyzers/archive')
const analyzeFile = require('./analyzers/file')

const lstat = util.promisify(fs.lstat)

async function computeDigest(token, options) {
  const digest = await hasha.fromStream(fs.createReadStream(token.path), {
    algorithm: options.digestAlgorithm,
    encoding: 'base64'
  })
  token.digest = `${options.digestAlgorithm}-${digest}`
}

async function analyzePath(token, options) {
  if (token.analyzed) {
    return false
  }

  options.logger.log('path:analyze:start', token)

  token.stats = await lstat(token.path)

  try {
    if (token.stats.isDirectory()) {
      await analyzeDirectory(token, options)
    } else if (token.stats.isFile()) {
      analyzeName(token, options)
      await analyzeTypes(token, options)

      if (!token.digest) {
        await computeDigest(token, options)
      }

      if (options.cache && options.cache.getFileCache && await options.cache.getFileCache(token, options)) {
        token.unchanged = true
        token.analyzed = true
      }

      await analyzeArchive(token, options)
      await analyzeFile(token, options)
    } else {
      throw new Error('Unsupported file type')
    }
  } catch (err) {
    throw err
  } finally {
    delete token.stats
  }

  options.logger.log('path:analyze:end', token)
}

module.exports = analyzePath
<commit_msg>Force file type on cached fs files<commit_after>'use strict'

const fs = require('fs')
const util = require('util')
const hasha = require('hasha')

const analyzeDirectory = require('./analyzers/directory')
const analyzeName = require('./analyzers/name')
const analyzeTypes = require('./analyzers/types')
const analyzeArchive = require('./analyzers/archive')
const analyzeFile = require('./analyzers/file')

const lstat = util.promisify(fs.lstat)

async function computeDigest(token, options) {
  const digest = await hasha.fromStream(fs.createReadStream(token.path), {
    algorithm: options.digestAlgorithm,
    encoding: 'base64'
  })
  token.digest = `${options.digestAlgorithm}-${digest}`
}

async function analyzePath(token, options) {
  if (token.analyzed) {
    return false
  }

  options.logger.log('path:analyze:start', token)

  token.stats = await lstat(token.path)

  try {
    if (token.stats.isDirectory()) {
      await analyzeDirectory(token, options)
    } else if (token.stats.isFile()) {
      analyzeName(token, options)
      await analyzeTypes(token, options)

      if (!token.digest) {
        await computeDigest(token, options)
      }

      if (options.cache && options.cache.getFileCache && await options.cache.getFileCache(token, options)) {
        token.type = 'file'
        token.unchanged = true
        token.analyzed = true
      }

      await analyzeArchive(token, options)
      await analyzeFile(token, options)
    } else {
      throw new Error('Unsupported file type')
    }
  } catch (err) {
    throw err
  } finally {
    delete token.stats
  }

  options.logger.log('path:analyze:end', token)
}

module.exports = analyzePath
<|endoftext|>


<commit_before>const db = require('./db')
const machineLoader = require('../lib/machine-loader')
const { saveConfig, saveAccounts, loadLatest } = require('../lib/new-settings-loader')
const { migrate } = require('../lib/config-migration')

const _ = require('lodash/fp')

const OLD_SETTINGS_LOADER_SCHEMA_VERSION = 1

module.exports.up = function (next) {
  function migrateConfig (settings) {
    const newSettings = migrate(settings.config, settings.accounts)
    return Promise.all([
      saveConfig(newSettings.config),
      saveAccounts(newSettings.accounts)
    ])
      .then(() => next())
  }

  loadLatest(OLD_SETTINGS_LOADER_SCHEMA_VERSION)
    .then(async settings => {
      if (_.isEmpty(settings.config)) {
        return {
          settings,
          machines: []
        }
      }
      return {
        settings,
        machines: await machineLoader.getMachineNames(settings.config)
      }
    })
    .then(({ settings, machines }) => {
      if (_.isEmpty(settings.config)) {
        return next()
      }
      const sql = machines
        ? machines.map(m => `update devices set name = '${m.name}' where device_id = '${m.deviceId}'`)
        : []
      return db.multi(sql, () => migrateConfig(settings))
    })
    .catch(err => {
      if (err.message === 'lamassu-server is not configured') {
        return next()
      }
      console.log(err.message)
      return next(err)
    })
}

module.exports.down = function (next) {
  next()
}
<commit_msg>fix: don't update machine names from queried machine names<commit_after>const db = require('./db')
const machineLoader = require('../lib/machine-loader')
const { saveConfig, saveAccounts, loadLatest } = require('../lib/new-settings-loader')
const { migrate } = require('../lib/config-migration')

const _ = require('lodash/fp')

const OLD_SETTINGS_LOADER_SCHEMA_VERSION = 1

module.exports.up = function (next) {
  function migrateConfig (settings) {
    const newSettings = migrate(settings.config, settings.accounts)
    return Promise.all([
      saveConfig(newSettings.config),
      saveAccounts(newSettings.accounts)
    ])
      .then(() => next())
  }

  loadLatest(OLD_SETTINGS_LOADER_SCHEMA_VERSION)
    .then(settings => _.isEmpty(settings.config)
        ? next()
        : migrateConfig(settings)
    )
    .catch(err => {
      if (err.message === 'lamassu-server is not configured') {
        return next()
      }
      console.log(err.message)
      return next(err)
    })
}

module.exports.down = function (next) {
  next()
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2008 rPath, Inc.
 All rights reserved
*/

function parseXHRresponseIE(xhr) {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.validateOnParse = false;
    if (!xmlDoc.loadXML(xhr.responseText))
    {
      //TODO: Need to log an error
    }
    return xmlDoc;
}

function parseResponseAndAppendTo(xhr, wanted_element, append_to) {
    var xmlDoc = null;
    try { //Internet Explorer
        loaded = jQuery(xhr.responseText);
        //In IE, it appears to load it discarding the body tags, so no selection is needed
        loaded.appendTo(append_to);
    }
    catch(e) {
      try { //Firefox, Mozilla, Opera, etc.
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(xhr.responseText, "text/xml");
        jQuery('#' + wanted_element, xmlDoc).appendTo(append_to);
      }
      catch(e) {throw e;}
    }
}

function finished_load_packageList(xhr, textStatus)
{
    //We don't use the "success" callback because the data is too big to put on the stack
    // See http://dev.jquery.com/ticket/3250
    if (textStatus == 'success') {
        xmlDoc = parseResponseAndAppendTo(xhr, 'packageList', '#packageList_troveList');
        // Set up the links to the anchors
        add_anchor_links();
        // Set the odd/even classes
        //var rows = jQuery('tr[id=packageList_trove_row]');
        //odd_and_even(rows);
        add_filter_handler();
        jQuery('#loading_wait').hide();
        jQuery('#packageList_troveList').show();
        jQuery('#selectPackagesFormSubmit').get(0).disabled=false;
        jQuery('input[name=jumpto]').get(0).disabled=false;
    }
}

var lastselected = null;

function trim(str)
{
    return str.replace(/^\s+|\s+$/g, '');
}

function jump_to_item()
{
    linkname = trim(jQuery(this).text());
    divOffset = jQuery('#packageList_troveList').offset().top;
    row = jQuery('tr[name=row_' + linkname + ']');
    pOffset = row.offset().top;
    var pScroll = pOffset - divOffset - 2;
    jQuery('#packageList_troveList').animate({scrollTop: '+=' + pScroll + 'px'}, 50, 'swing');
    obj = jQuery('input#checkbox_' + linkname).attr('checked', 'checked');
    if (lastselected)
        lastselected.removeClass('selected');
    lastselected = row.addClass('selected');
    return false;
}

function reset_filter()
{
    jQuery('#filter_selections').empty().hide('fast');
}

var troveNames = [];

function get_trove_list()
{
    troveNames = jQuery('.packageList_trove_name').map(function(index, domElem) {
        return trim(jQuery(domElem).text());
    });
}

function pkg_filter(val){
    if (troveNames.length == 0)
        get_trove_list();
    if (!val) {
        reset_filter();
        return true;
    }
    regex = new RegExp(val, 'i');
    var results = jQuery('#filter_selections');
    wrapper = jQuery('#filter_navigation_link_template').clone();
    wrapper.attr('id', 'filter_navigation_link');
    wrapper.show();
    results.empty();
    var added = 0;
    for (var i = 0; i < troveNames.length; i++) {
        if (troveNames[i].search(regex) != -1){
            wclone = wrapper.clone()
            wclone.append(document.createTextNode(troveNames[i]));
            added += 1;
            //results.append(document.createTextNode('\n'));
            results.append(wclone);
        }
    }
    if (added <= 0) {
        results.append('
No packages match the filter term.
');
    }
    jQuery('div[id=filter_navigation_link]').click(jump_to_item);
    results.show('fast');
    return true;
}

function pkgs_live_filter(e)
{
    searchval = jQuery(this).val();
    switch(e.which) {
        case 13:
        case 10:
        case 9:
            //ignore enter and tab They'll be picked up by onchange
            return true;
    };

    if (searchval.length < 2)
        reset_filter();
    else
        pkg_filter(searchval);
}

function add_filter_handler() {
    var search_box = jQuery('input[name=jumpto]');
    //search_box.change( function (e) { pkg_filter(this.value) });
    search_box.keyup( pkgs_live_filter );
    //Enable the clear button
    jQuery('#jumpto_box_clear').click(function() {
        jQuery('input[name=jumpto]').val('');
        reset_filter();
        return false;
    });
}

function animate_scroll_to(eventObj) {
    var divOffset = jQuery('#packageList_troveList').offset().top;
    var pOffset = jQuery('#' + this.id + "_target").offset().top;
    var pScroll = pOffset - divOffset;
    jQuery('#packageList_troveList').animate({scrollTop: '+=' + pScroll + 'px'}, 300, 'swing');
    return false;
}

function linkhere(index, domElement)
{
    var linktmp = jQuery('#packageList_navigation_link_template > a').clone().get(0);
    linktmp.id = 'packageList_navigation_link';
    linktmp.href = '#' + domElement.id;
    var id = domElement.id.replace('_target', '');
    var res = jQuery('#' + id).wrapInner(linktmp)

    res.click(animate_scroll_to);
}

function add_anchor_links()
{
    jQuery('h3.packageList_section_header').map(linkhere);
}

jQuery(document).ready(function () {
    //Show the spinner, and start loading the trove list
    jQuery('#loading_wait').show();
    jQuery.ajax({
        type: 'GET',
        url: 'packageList',
        complete: finished_load_packageList,
        dataType: 'html',
        cache: false,
        error:
            function(req, textStatus, errorThrown) {
                alert("Could not load the package list");
            }
        });
    });
<commit_msg>linty cleanups<commit_after>/*
 Copyright (c) 2008 rPath, Inc.
 All rights reserved
*/

function parseXHRresponseIE(xhr) {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.validateOnParse = false;
    if (!xmlDoc.loadXML(xhr.responseText))
    {
      //TODO: Need to log an error
    }
    return xmlDoc;
}

function parseResponseAndAppendTo(xhr, wanted_element, append_to) {
    var xmlDoc = null;
    try { //Internet Explorer
        loaded = jQuery(xhr.responseText);
        //In IE, it appears to load it discarding the body tags, so no selection is needed
        loaded.appendTo(append_to);
    }
    catch(e) {
      try { //Firefox, Mozilla, Opera, etc.
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(xhr.responseText, "text/xml");
        jQuery('#' + wanted_element, xmlDoc).appendTo(append_to);
      }
      catch(e) {throw e;}
    }
}

function finished_load_packageList(xhr, textStatus) {
    //We don't use the "success" callback because the data is too big to put on the stack
    // See http://dev.jquery.com/ticket/3250
    if (textStatus == 'success') {
        xmlDoc = parseResponseAndAppendTo(xhr, 'packageList', '#packageList_troveList');
        // Set up the links to the anchors
        add_anchor_links();
        // Set the odd/even classes
        //var rows = jQuery('tr[id=packageList_trove_row]');
        //odd_and_even(rows);
        add_filter_handler();
        jQuery('#loading_wait').hide();
        jQuery('#packageList_troveList').show();
        jQuery('#selectPackagesFormSubmit').get(0).disabled=false;
        jQuery('input[name=jumpto]').get(0).disabled=false;
    }
}

var lastselected = null;

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function jump_to_item() {
    linkname = trim(jQuery(this).text());
    divOffset = jQuery('#packageList_troveList').offset().top;
    row = jQuery('tr[name=row_' + linkname + ']');
    pOffset = row.offset().top;
    var pScroll = pOffset - divOffset - 2;
    jQuery('#packageList_troveList').animate({scrollTop: '+=' + pScroll + 'px'}, 50, 'swing');
    obj = jQuery('input#checkbox_' + linkname).attr('checked', 'checked');
    if (lastselected)
        lastselected.removeClass('selected');
    lastselected = row.addClass('selected');
    return false;
}

function reset_filter() {
    jQuery('#filter_selections').empty().hide('fast');
}

var troveNames = [];

function get_trove_list() {
    troveNames = jQuery('.packageList_trove_name').map(function(index, domElem) {
        return trim(jQuery(domElem).text());
    });
}

function pkg_filter(val){
    if (troveNames.length == 0)
        get_trove_list();
    if (!val) {
        reset_filter();
        return true;
    }
    regex = new RegExp(val, 'i');
    var results = jQuery('#filter_selections');
    wrapper = jQuery('#filter_navigation_link_template').clone();
    wrapper.attr('id', 'filter_navigation_link');
    wrapper.show();
    results.empty();
    var added = 0;
    for (var i = 0; i < troveNames.length; i++) {
        if (troveNames[i].search(regex) != -1){
            wclone = wrapper.clone();
            wclone.append(document.createTextNode(troveNames[i]));
            added += 1;
            results.append(wclone);
        }
    }
    if (added <= 0) {
        results.append('
No packages match the filter term.
');
    }
    jQuery('div[id=filter_navigation_link]').click(jump_to_item);
    results.show('fast');
    return true;
}

function pkgs_live_filter(e) {
    searchval = jQuery(this).val();
    switch(e.which) {
        case 13:
        case 10:
        case 9:
            //ignore enter and tab They'll be picked up by onchange
            return true;
    };

    if (searchval.length < 2)
        reset_filter();
    else
        pkg_filter(searchval);
}

function add_filter_handler() {
    var search_box = jQuery('input[name=jumpto]');
    //search_box.change( function (e) { pkg_filter(this.value) });
    search_box.keyup( pkgs_live_filter );
    //Enable the clear button
    jQuery('#jumpto_box_clear').click(function() {
        jQuery('input[name=jumpto]').val('');
        reset_filter();
        return false;
    });
}

function animate_scroll_to(eventObj) {
    var divOffset = jQuery('#packageList_troveList').offset().top;
    var pOffset = jQuery('#' + this.id + "_target").offset().top;
    var pScroll = pOffset - divOffset;
    jQuery('#packageList_troveList').animate({scrollTop: '+=' + pScroll + 'px'}, 300, 'swing');
    return false;
}

function linkhere(index, domElement) {
    var linktmp = jQuery('#packageList_navigation_link_template > a').clone().get(0);
    linktmp.id = 'packageList_navigation_link';
    linktmp.href = '#' + domElement.id;
    var id = domElement.id.replace('_target', '');
    var res = jQuery('#' + id).wrapInner(linktmp);

    res.click(animate_scroll_to);
}

function add_anchor_links() {
    jQuery('h3.packageList_section_header').map(linkhere);
}

jQuery(document).ready(function () {
    //Show the spinner, and start loading the trove list
    jQuery('#loading_wait').show();
    jQuery.ajax({
        type: 'GET',
        url: 'packageList',
        complete: finished_load_packageList,
        dataType: 'html',
        cache: false,
        error:
            function(req, textStatus, errorThrown) {
                alert("Could not load the package list");
            }
        });
    });
<|endoftext|>


<commit_before>/*
Maps urls to files, useful if you want to quickly and safely
share only a few files...

usage:

require("./alias.js")(app,{
  "/favicon.ico":"/path/to/favicon.ico"
  ,"/robots.txt":"/path/to/robots.txt"
  ,"nodeinfo.json":"/path/to/nodeinfo.json"
  ,"feed.xml":"/path/to/rss.xml" // an alias
  ,"rss.xml":"/path/to/rss.xml"
});

*/

module.exports=function(a,o){
  Object.keys(o).map(function(k){
    app.get(f,function(req,res,next){
      res.sendFile(o[k]);
    });
  });
};
<commit_msg>bad name<commit_after>/*
Maps urls to files, useful if you want to quickly and safely
share only a few files...

usage:

require("./alias.js")(app,{
  "/favicon.ico":"/path/to/favicon.ico"
  ,"/robots.txt":"/path/to/robots.txt"
  ,"nodeinfo.json":"/path/to/nodeinfo.json"
  ,"feed.xml":"/path/to/rss.xml" // an alias
  ,"rss.xml":"/path/to/rss.xml"
});

*/

module.exports=function(a,o){
  Object.keys(o).map(function(k){
    a.get(f,function(req,res,next){
      res.sendFile(o[k]);
    });
  });
};
<|endoftext|>


<commit_before>// Source : https://leetcode.com/problems/number-of-1-bits/
// Author : Dean Shi
// Date   : 2015-06-16

/**********************************************************************************
 *
 * Write a function that takes an unsigned integer and returns the number of ’1' bits it has
 * (also known as the Hamming weight).
 *
 * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
 * so the function should return 3.
 *
 * Credits:Special thanks to @ts for adding this problem and creating all test cases.
 *
 **********************************************************************************/

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    return n.toString(2).split('1').length - 1;
};

// Test case
console.log(hammingWeight(11) === 3); // true
<commit_msg>Update NumberOf1Bits.js<commit_after>// Source : https://leetcode.com/problems/number-of-1-bits/
// Author : Dean Shi
// Date   : 2015-06-16

/**********************************************************************************
 *
 * Write a function that takes an unsigned integer and returns the number of ’1' bits it has
 * (also known as the Hamming weight).
 *
 * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
 * so the function should return 3.
 *
 * Credits:Special thanks to @ts for adding this problem and creating all test cases.
 *
 **********************************************************************************/

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    let result = 0
    do {
        result += n & 1
    } while (n >>>= 1)
    return result
};
<|endoftext|>


<commit_before>// Socket init
var socket = new io.Socket();
socket.connect();
socket.on('connect', function() {
  socket.subscribe(token);
});
<commit_msg>Socket Io reconnect<commit_after>var connected = false;
var timeout;
const RETRY_INTERVAL = 5000;

var socket = new io.Socket();

socket.on('connect', function() {
  socket.subscribe(token);
  connected = true;
  clearTimeout(timeout);
});

socket.on('disconnect', function() {
 connected = false;
  console.log('SocketIo disconnected, trying to automatically reconnect in ' + RETRY_INTERVAL/1000 + ' seconds.');
  retryConnectOnFailure(RETRY_INTERVAL);
});

var retryConnectOnFailure = function(retryInMilliseconds) {
  timeout = setTimeout(function() {
    if (!connected) {
      socket.connect();
      retryConnectOnFailure(retryInMilliseconds);
    }
  }, retryInMilliseconds);
}

socket.connect();
retryConnectOnFailure(RETRY_INTERVAL);
<|endoftext|>


<commit_before>var message_edit = (function () {
var exports = {};
var currently_editing_messages = {};

//returns true if the edit task should end.
exports.save = function (row) {
    var msg_list = current_msg_list;
    var message = current_msg_list.get(rows.id(row));
    var changed = false;

    var new_content = row.find(".message_edit_content").val();
    var topic_changed = false;
    var new_topic;
    if (message.type === "stream") {
        new_topic = row.find(".message_edit_topic").val();
        topic_changed = (new_topic !== message.subject && new_topic.trim() !== "");
    }

    // Editing a not-yet-acked message (because the original send attempt failed)
    // just results in the in-memory message being changed
    if (message.local_id !== undefined) {
        // No changes
        if (new_content !== message.raw_content && !new_topic) {
            return true;
        }
        echo.edit_locally(message, new_content, topic_changed ? new_topic : undefined);
        return true;
    }

    var request = {message_id: message.id};
    if (topic_changed) {
        request.subject = new_topic;
        if (feature_flags.propagate_topic_edits) {
            var selected_topic_propagation = row.find("select.message_edit_topic_propagate").val() || "change_later";
            request.propagate_mode = selected_topic_propagation;
        }
        changed = true;
    }

    if (new_content !== message.raw_content) {
        request.content = new_content;
        changed = true;
    }
    if (!changed) {
        // If they didn't change anything, just cancel it.
        return true;
    }
    channel.post({
        url: '/json/update_message',
        data: request,
        success: function (data) {
            if (msg_list === current_msg_list) {
                return true;
            }
        },
        error: function (xhr, error_type, xhn) {
            var message = util.xhr_error_message("Error saving edit", xhr);
            row.find(".edit_error").text(message).show();
        }
    });
    // The message will automatically get replaced when it arrives.
};

function handle_edit_keydown(e) {
    var row, code = e.keyCode || e.which;

    if (e.target.id === "message_edit_content" && code === 13 &&
        (e.metaKey || e.ctrlKey)) {
        row = $(".message_edit_content").filter(":focus").closest(".message_row");
        if (message_edit.save(row) === true) {
            message_edit.end(row);
        }
    } else if (e.target.id === "message_edit_topic" && code === 13) {
        //hitting enter in topic field isn't so great.
        e.stopPropagation();
        e.preventDefault();
    }
}

function edit_message (row, raw_content) {
    var content_top = row.find('.message_content')[0]
        .getBoundingClientRect().top;

    var message = current_msg_list.get(rows.id(row));
    var edit_row = row.find(".message_edit");
    var form = $(templates.render('message_edit_form',
                                  {is_stream: message.is_stream,
                                   topic: message.subject,
                                   content: raw_content}));

    var edit_obj = {form: form, raw_content: raw_content};
    var original_topic = message.subject;

    current_msg_list.show_edit_message(row, edit_obj);

    form.keydown(handle_edit_keydown);

    currently_editing_messages[message.id] = edit_obj;
    if (message.subject === compose.empty_subject_placeholder()) {
        edit_row.find(".message_edit_topic").focus();
    } else {
        edit_row.find(".message_edit_content").focus();
    }

    // Scroll to keep the message content in the same place
    var edit_top = edit_row.find('.message_edit_content')[0]
        .getBoundingClientRect().top;

    var scroll_by = edit_top - content_top + 5 /* border and padding */;
    edit_obj.scrolled_by = scroll_by;
    viewport.scrollTop(viewport.scrollTop() + scroll_by);

    if (feature_flags.propagate_topic_edits && message.local_id !== undefined) {
        var topic_input = edit_row.find(".message_edit_topic");
        topic_input.keyup( function () {
            var new_topic = topic_input.val();
            row.find('.message_edit_topic_propagate').toggle(new_topic !== original_topic);
        });
    }

    composebox_typeahead.initialize_compose_typeahead("#message_edit_content", {emoji: true});
}

function start_edit_maintaining_scroll(row, content) {
    edit_message(row, content);
    var row_bottom = row.height() + row.offset().top;
    var composebox_top = $("#compose").offset().top;
    if (row_bottom > composebox_top) {
        viewport.scrollTop(viewport.scrollTop() + row_bottom - composebox_top);
    }
}

exports.start = function (row) {
    var message = current_msg_list.get(rows.id(row));
    var msg_list = current_msg_list;
    channel.post({
        url: '/json/fetch_raw_message',
        idempotent: true,
        data: {message_id: message.id},
        success: function (data) {
            if (current_msg_list === msg_list) {
                message.raw_content = data.raw_content;
                start_edit_maintaining_scroll(row, data.raw_content);
            }
        }
    });
};

exports.start_local_failed_edit = function (row, message) {
    start_edit_maintaining_scroll(row, message.raw_content);
};

exports.start_topic_edit = function (recipient_row) {
    var form = $(templates.render('topic_edit_form'));
    current_msg_list.show_edit_topic(recipient_row, form);
    form.keydown(handle_edit_keydown);
    var message = current_msg_list.get(rows.id(recipient_row));
    var topic = message.subject;
    if (topic === compose.empty_subject_placeholder()) {
        topic = '';
    }
    form.find(".message_edit_topic").val(topic).select().focus();
};

exports.is_editing = function (id) {
    return currently_editing_messages[id] !== undefined;
};

exports.end = function (row) {
    var message = current_msg_list.get(rows.id(row));
    if (currently_editing_messages[message.id] !== undefined) {
        var scroll_by = currently_editing_messages[message.id].scrolled_by;
        viewport.scrollTop(viewport.scrollTop() - scroll_by);
        delete currently_editing_messages[message.id];
        current_msg_list.hide_edit_message(row);
    }
};

exports.maybe_show_edit = function (row, id) {
    if (currently_editing_messages[id] !== undefined){
        current_msg_list.show_edit_message(row, currently_editing_messages[id]);
    }
};

$(document).on('narrow_deactivated.zulip', function (event) {
    _.each(currently_editing_messages, function (elem, idx) {
        if (current_msg_list.get(idx) !== undefined) {
            var row = current_msg_list.get_row(idx);
            current_msg_list.show_edit_message(row, elem);
        }
    });
});

return exports;
}());
<commit_msg>Fix inverted boolean check for local messages in topic propagation<commit_after>var message_edit = (function () {
var exports = {};
var currently_editing_messages = {};

//returns true if the edit task should end.
exports.save = function (row) {
    var msg_list = current_msg_list;
    var message = current_msg_list.get(rows.id(row));
    var changed = false;

    var new_content = row.find(".message_edit_content").val();
    var topic_changed = false;
    var new_topic;
    if (message.type === "stream") {
        new_topic = row.find(".message_edit_topic").val();
        topic_changed = (new_topic !== message.subject && new_topic.trim() !== "");
    }

    // Editing a not-yet-acked message (because the original send attempt failed)
    // just results in the in-memory message being changed
    if (message.local_id !== undefined) {
        // No changes
        if (new_content !== message.raw_content && !new_topic) {
            return true;
        }
        echo.edit_locally(message, new_content, topic_changed ? new_topic : undefined);
        return true;
    }

    var request = {message_id: message.id};
    if (topic_changed) {
        request.subject = new_topic;
        if (feature_flags.propagate_topic_edits) {
            var selected_topic_propagation = row.find("select.message_edit_topic_propagate").val() || "change_later";
            request.propagate_mode = selected_topic_propagation;
        }
        changed = true;
    }

    if (new_content !== message.raw_content) {
        request.content = new_content;
        changed = true;
    }
    if (!changed) {
        // If they didn't change anything, just cancel it.
        return true;
    }
    channel.post({
        url: '/json/update_message',
        data: request,
        success: function (data) {
            if (msg_list === current_msg_list) {
                return true;
            }
        },
        error: function (xhr, error_type, xhn) {
            var message = util.xhr_error_message("Error saving edit", xhr);
            row.find(".edit_error").text(message).show();
        }
    });
    // The message will automatically get replaced when it arrives.
};

function handle_edit_keydown(e) {
    var row, code = e.keyCode || e.which;

    if (e.target.id === "message_edit_content" && code === 13 &&
        (e.metaKey || e.ctrlKey)) {
        row = $(".message_edit_content").filter(":focus").closest(".message_row");
        if (message_edit.save(row) === true) {
            message_edit.end(row);
        }
    } else if (e.target.id === "message_edit_topic" && code === 13) {
        //hitting enter in topic field isn't so great.
        e.stopPropagation();
        e.preventDefault();
    }
}

function edit_message (row, raw_content) {
    var content_top = row.find('.message_content')[0]
        .getBoundingClientRect().top;

    var message = current_msg_list.get(rows.id(row));
    var edit_row = row.find(".message_edit");
    var form = $(templates.render('message_edit_form',
                                  {is_stream: message.is_stream,
                                   topic: message.subject,
                                   content: raw_content}));

    var edit_obj = {form: form, raw_content: raw_content};
    var original_topic = message.subject;

    current_msg_list.show_edit_message(row, edit_obj);

    form.keydown(handle_edit_keydown);

    currently_editing_messages[message.id] = edit_obj;
    if (message.subject === compose.empty_subject_placeholder()) {
        edit_row.find(".message_edit_topic").focus();
    } else {
        edit_row.find(".message_edit_content").focus();
    }

    // Scroll to keep the message content in the same place
    var edit_top = edit_row.find('.message_edit_content')[0]
        .getBoundingClientRect().top;

    var scroll_by = edit_top - content_top + 5 /* border and padding */;
    edit_obj.scrolled_by = scroll_by;
    viewport.scrollTop(viewport.scrollTop() + scroll_by);

    if (feature_flags.propagate_topic_edits && message.local_id === undefined) {
        var topic_input = edit_row.find(".message_edit_topic");
        topic_input.keyup( function () {
            var new_topic = topic_input.val();
            row.find('.message_edit_topic_propagate').toggle(new_topic !== original_topic);
        });
    }

    composebox_typeahead.initialize_compose_typeahead("#message_edit_content", {emoji: true});
}

function start_edit_maintaining_scroll(row, content) {
    edit_message(row, content);
    var row_bottom = row.height() + row.offset().top;
    var composebox_top = $("#compose").offset().top;
    if (row_bottom > composebox_top) {
        viewport.scrollTop(viewport.scrollTop() + row_bottom - composebox_top);
    }
}

exports.start = function (row) {
    var message = current_msg_list.get(rows.id(row));
    var msg_list = current_msg_list;
    channel.post({
        url: '/json/fetch_raw_message',
        idempotent: true,
        data: {message_id: message.id},
        success: function (data) {
            if (current_msg_list === msg_list) {
                message.raw_content = data.raw_content;
                start_edit_maintaining_scroll(row, data.raw_content);
            }
        }
    });
};

exports.start_local_failed_edit = function (row, message) {
    start_edit_maintaining_scroll(row, message.raw_content);
};

exports.start_topic_edit = function (recipient_row) {
    var form = $(templates.render('topic_edit_form'));
    current_msg_list.show_edit_topic(recipient_row, form);
    form.keydown(handle_edit_keydown);
    var message = current_msg_list.get(rows.id(recipient_row));
    var topic = message.subject;
    if (topic === compose.empty_subject_placeholder()) {
        topic = '';
    }
    form.find(".message_edit_topic").val(topic).select().focus();
};

exports.is_editing = function (id) {
    return currently_editing_messages[id] !== undefined;
};

exports.end = function (row) {
    var message = current_msg_list.get(rows.id(row));
    if (currently_editing_messages[message.id] !== undefined) {
        var scroll_by = currently_editing_messages[message.id].scrolled_by;
        viewport.scrollTop(viewport.scrollTop() - scroll_by);
        delete currently_editing_messages[message.id];
        current_msg_list.hide_edit_message(row);
    }
};

exports.maybe_show_edit = function (row, id) {
    if (currently_editing_messages[id] !== undefined){
        current_msg_list.show_edit_message(row, currently_editing_messages[id]);
    }
};

$(document).on('narrow_deactivated.zulip', function (event) {
    _.each(currently_editing_messages, function (elem, idx) {
        if (current_msg_list.get(idx) !== undefined) {
            var row = current_msg_list.get_row(idx);
            current_msg_list.show_edit_message(row, elem);
        }
    });
});

return exports;
}());
<|endoftext|>


<commit_before>var Projection = function()
{
	this._init = [];
	this._rules = [];
	this._otherwise = [];
}

Projection.prototype.init = function(func) {
	this._init.push(func);
	return this;
};

Projection.prototype.any = function(func) {
	this.when(function() { return true;}, func);
	return this;
}

Projection.prototype.when = function(criteria, func) {
	this._rules.push({criteria: criteria, function: func});
	return this;
}

Projection.prototype.property = function(prop, value, func) {
	return this.when( function(x) { return x[prop] === value}, func);
}

Projection.prototype.otherwise = function(func) {
	this._otherwise.push(func);
	return this;
}

Projection.prototype.combine = function(projection) {
	this._init = this._init.concat(projection._init);
	this._rules = this._rules.concat(projection._rules);
	this._otherwise = this._otherwise.concat(projection._otherwise);
	return this;
}

Projection.prototype.project = function(state, data, callback) {
	var supportsAsync = typeof(callback) !== 'undefined';
	this._init.forEach(function(f) {
		f(state);
	});

	if(!Array.isArray(data)) {
		data = [data];
	}
	var idx = 0;
	var self = this;
/*	data.forEach(function(x) {

		state = self._match(state, x, next);
	});
*/
	next(state);

	function next() {
		var element = data[idx++];
		//is done?
		if(!element) {
			if(callback) {
				callback(null, state);
				return state;
			} else {
				return state;
			}
		} else {
			self._match(state, element, next, supportsAsync);
		}
	}
	return state;
}

Projection.prototype._match = function(state, element, next, supportsAsync) {
	var processed = false;
	var self = this;
	this._rules.forEach(function(rule) {
		if(rule.criteria(element)) {
			processed = true;
			var func = rule["function"];
			self._exec(func,state, element, next, supportsAsync);

		}
	});

	if(!processed) {
		this._otherwise.forEach(function(func) {
			self._exec(func,state, element, next, supportsAsync);
		});
	}

};

Projection.prototype._exec = function(func, state, element, next, supportsAsync) {
	//3 arguments, means that function is expecting a next() function
	if(func.length === 3) {
		if(!supportsAsync) {
			throw new Error("cannot have async projection without calling project with callback");
		} else {
			func(state, element, next);
			return true;
		}
	} else {
		func(state, element);
		next(state);
	}

}

module.exports = Projection;<commit_msg>removed dead code<commit_after>var Projection = function()
{
	this._init = [];
	this._rules = [];
	this._otherwise = [];
}

Projection.prototype.init = function(func) {
	this._init.push(func);
	return this;
};

Projection.prototype.any = function(func) {
	this.when(function() { return true;}, func);
	return this;
}

Projection.prototype.when = function(criteria, func) {
	this._rules.push({criteria: criteria, function: func});
	return this;
}

Projection.prototype.property = function(prop, value, func) {
	return this.when( function(x) { return x[prop] === value}, func);
}

Projection.prototype.otherwise = function(func) {
	this._otherwise.push(func);
	return this;
}

Projection.prototype.combine = function(projection) {
	this._init = this._init.concat(projection._init);
	this._rules = this._rules.concat(projection._rules);
	this._otherwise = this._otherwise.concat(projection._otherwise);
	return this;
}

Projection.prototype.project = function(state, data, callback) {
	var supportsAsync = typeof(callback) !== 'undefined';
	this._init.forEach(function(f) {
		f(state);
	});

	if(!Array.isArray(data)) {
		data = [data];
	}
	var idx = 0;
	var self = this;

	next(state);

	function next() {
		var element = data[idx++];
		//is done?
		if(!element) {
			if(callback) {
				callback(null, state);
				return state;
			} else {
				return state;
			}
		} else {
			self._match(state, element, next, supportsAsync);
		}
	}
	return state;
}

Projection.prototype._match = function(state, element, next, supportsAsync) {
	var processed = false;
	var self = this;
	this._rules.forEach(function(rule) {
		if(rule.criteria(element)) {
			processed = true;
			var func = rule["function"];
			self._exec(func,state, element, next, supportsAsync);

		}
	});

	if(!processed) {
		this._otherwise.forEach(function(func) {
			self._exec(func,state, element, next, supportsAsync);
		});
	}

};

Projection.prototype._exec = function(func, state, element, next, supportsAsync) {
	//3 arguments, means that function is expecting a next() function
	if(func.length === 3) {
		if(!supportsAsync) {
			throw new Error("cannot have async projection without calling project with callback");
		} else {
			func(state, element, next);
			return true;
		}
	} else {
		func(state, element);
		next(state);
	}

}

module.exports = Projection;<|endoftext|>


<commit_before>import SimpleBar from 'simplebar';
import {activate_correct_tab} from './tabbed-instructions.js';

function registerCodeSection($codeSection) {
    const $li = $codeSection.find("ul.nav li");
    const $blocks = $codeSection.find(".blocks div");

    $li.click(function () {
        const language = this.dataset.language;

        $li.removeClass("active");
        $li.filter("[data-language=" + language + "]").addClass("active");

        $blocks.removeClass("active");
        $blocks.filter("[data-language=" + language + "]").addClass("active");
    });
}

function highlight_current_article() {
    $('.help .sidebar a').removeClass('highlighted');
    const path = window.location.pathname;

    if (!path) {
        return;
    }

    const hash = window.location.hash;
    let article = $('.help .sidebar a[href="' + path + hash + '"]');
    if (!article.length) {
        // If there isn't an entry in the left sidebar that matches
        // the full url+hash pair, instead highlight an entry in the
        // left sidebar that just matches the url part.
        article = $('.help .sidebar a[href="' + path + '"]');
    }
    // Highlight current article link and the heading of the same
    article.closest('ul').css('display', 'block');
    article.addClass('highlighted');
}

function render_code_sections() {
    $(".code-section").each(function () {
        activate_correct_tab($(this));
        registerCodeSection($(this));
    });

    highlight_current_article();

    common.adjust_mac_shortcuts(".markdown .content code", true);

    $("table").each(function () {
        $(this).addClass("table table-striped");
    });
}

function scrollToHash(simplebar) {
    const hash = window.location.hash;
    const scrollbar = simplebar.getScrollElement();
    if (hash !== '') {
        const position = $(hash).position().top - $(scrollbar.firstChild).position().top;
        scrollbar.scrollTop = position;
    } else {
        scrollbar.scrollTop = 0;
    }
}

const html_map = {};
const loading = {
    name: null,
};

const markdownSB = new SimpleBar($(".markdown")[0]);

const fetch_page = function (path, callback) {
    $.get(path, function (res) {
        const $html = $(res).find(".markdown .content");

        callback($html.html().trim());
        render_code_sections();
    });
};

const update_page = function (html_map, path) {
    if (html_map[path]) {
        $(".markdown .content").html(html_map[path]);
        render_code_sections();
        scrollToHash(markdownSB);
    } else {
        loading.name = path;
        fetch_page(path, function (res) {
            html_map[path] = res;
            $(".markdown .content").html(html_map[path]);
            loading.name = null;
            scrollToHash(markdownSB);
        });
    }
};

new SimpleBar($(".sidebar")[0]);

$(".sidebar.slide h2").click(function (e) {
    const $next = $(e.target).next();

    if ($next.is("ul")) {
        // Close other article's headings first
        $('.sidebar ul').not($next).hide();
        // Toggle the heading
        $next.slideToggle("fast", "swing");
    }
});

$(".sidebar a").click(function (e) {
    const path = $(this).attr("href");
    const path_dir = path.split('/')[1];
    const current_dir = window.location.pathname.split('/')[1];

    // Do not block redirecting to external URLs
    if (path_dir !== current_dir) {
        return;
    }

    if (loading.name === path) {
        return;
    }

    history.pushState({}, "", path);

    update_page(html_map, path);

    $(".sidebar").removeClass("show");

    e.preventDefault();
});

if (window.location.pathname === '/help/') {
    // Expand the Guides user docs section in sidebar in the /help/ homepage.
    $('.help .sidebar h2#guides + ul').show();
}
// Remove ID attributes from sidebar links so they don't conflict with index page anchor links
$('.help .sidebar h1, .help .sidebar h2, .help .sidebar h3').removeAttr('id');

// Scroll to anchor link when clicked
$(document).on('click', '.markdown .content h1, .markdown .content h2, .markdown .content h3', function () {
    window.location.hash = $(this).attr("id");
    scrollToHash(markdownSB);
});

$(".hamburger").click(function () {
    $(".sidebar").toggleClass("show");
});

$(".markdown").click(function () {
    if ($(".sidebar.show").length) {
        $(".sidebar.show").toggleClass("show");
    }
});

render_code_sections();

// Finally, make sure if we loaded a window with a hash, we scroll
// to the right place.
scrollToHash(markdownSB);

window.addEventListener("popstate", function () {
    const path = window.location.pathname;
    update_page(html_map, path);
});

$('body').addClass('noscroll');
<commit_msg>help: Convert html_map from object to Map.<commit_after>import SimpleBar from 'simplebar';
import {activate_correct_tab} from './tabbed-instructions.js';

function registerCodeSection($codeSection) {
    const $li = $codeSection.find("ul.nav li");
    const $blocks = $codeSection.find(".blocks div");

    $li.click(function () {
        const language = this.dataset.language;

        $li.removeClass("active");
        $li.filter("[data-language=" + language + "]").addClass("active");

        $blocks.removeClass("active");
        $blocks.filter("[data-language=" + language + "]").addClass("active");
    });
}

function highlight_current_article() {
    $('.help .sidebar a').removeClass('highlighted');
    const path = window.location.pathname;

    if (!path) {
        return;
    }

    const hash = window.location.hash;
    let article = $('.help .sidebar a[href="' + path + hash + '"]');
    if (!article.length) {
        // If there isn't an entry in the left sidebar that matches
        // the full url+hash pair, instead highlight an entry in the
        // left sidebar that just matches the url part.
        article = $('.help .sidebar a[href="' + path + '"]');
    }
    // Highlight current article link and the heading of the same
    article.closest('ul').css('display', 'block');
    article.addClass('highlighted');
}

function render_code_sections() {
    $(".code-section").each(function () {
        activate_correct_tab($(this));
        registerCodeSection($(this));
    });

    highlight_current_article();

    common.adjust_mac_shortcuts(".markdown .content code", true);

    $("table").each(function () {
        $(this).addClass("table table-striped");
    });
}

function scrollToHash(simplebar) {
    const hash = window.location.hash;
    const scrollbar = simplebar.getScrollElement();
    if (hash !== '') {
        const position = $(hash).position().top - $(scrollbar.firstChild).position().top;
        scrollbar.scrollTop = position;
    } else {
        scrollbar.scrollTop = 0;
    }
}

const html_map = new Map();
const loading = {
    name: null,
};

const markdownSB = new SimpleBar($(".markdown")[0]);

const fetch_page = function (path, callback) {
    $.get(path, function (res) {
        const $html = $(res).find(".markdown .content");

        callback($html.html().trim());
        render_code_sections();
    });
};

const update_page = function (html_map, path) {
    if (html_map.has(path)) {
        $(".markdown .content").html(html_map.get(path));
        render_code_sections();
        scrollToHash(markdownSB);
    } else {
        loading.name = path;
        fetch_page(path, function (res) {
            html_map.set(path, res);
            $(".markdown .content").html(res);
            loading.name = null;
            scrollToHash(markdownSB);
        });
    }
};

new SimpleBar($(".sidebar")[0]);

$(".sidebar.slide h2").click(function (e) {
    const $next = $(e.target).next();

    if ($next.is("ul")) {
        // Close other article's headings first
        $('.sidebar ul').not($next).hide();
        // Toggle the heading
        $next.slideToggle("fast", "swing");
    }
});

$(".sidebar a").click(function (e) {
    const path = $(this).attr("href");
    const path_dir = path.split('/')[1];
    const current_dir = window.location.pathname.split('/')[1];

    // Do not block redirecting to external URLs
    if (path_dir !== current_dir) {
        return;
    }

    if (loading.name === path) {
        return;
    }

    history.pushState({}, "", path);

    update_page(html_map, path);

    $(".sidebar").removeClass("show");

    e.preventDefault();
});

if (window.location.pathname === '/help/') {
    // Expand the Guides user docs section in sidebar in the /help/ homepage.
    $('.help .sidebar h2#guides + ul').show();
}
// Remove ID attributes from sidebar links so they don't conflict with index page anchor links
$('.help .sidebar h1, .help .sidebar h2, .help .sidebar h3').removeAttr('id');

// Scroll to anchor link when clicked
$(document).on('click', '.markdown .content h1, .markdown .content h2, .markdown .content h3', function () {
    window.location.hash = $(this).attr("id");
    scrollToHash(markdownSB);
});

$(".hamburger").click(function () {
    $(".sidebar").toggleClass("show");
});

$(".markdown").click(function () {
    if ($(".sidebar.show").length) {
        $(".sidebar.show").toggleClass("show");
    }
});

render_code_sections();

// Finally, make sure if we loaded a window with a hash, we scroll
// to the right place.
scrollToHash(markdownSB);

window.addEventListener("popstate", function () {
    const path = window.location.pathname;
    update_page(html_map, path);
});

$('body').addClass('noscroll');
<|endoftext|>


<commit_before>"use strict";

const BlackHole = require('../BlackHole');
const isRelativeUrl = require('is-relative-url');
const LinkCheckResult = require('../LinkCheckResult');
const ms = require('ms');
const request = require('request');

module.exports = {

    check: function check(link, opts, callback, attempts, additionalMessage) {

        if (attempts == null) {
            attempts = 0;
        }

        const options = {
            uri: link,
            headers: {
                // override 'User-Agent' (some sites return `401` when the user-agent isn't a web browser)
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'
            },
            maxRedirects: 8,
            strictSSL: false,
            timeout: ms(opts.timeout),
        };

        if (opts.baseUrl && isRelativeUrl(link)) {
            options.baseUrl = opts.baseUrl;
        }

        if (opts.headers) {
            Object.assign(options.headers, opts.headers);
        }

        let retryCount = opts.retryCount || 2;

        request.head(options, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                if (additionalMessage){
                  err = (err == null) ? additionalMessage : `${err} ${additionalMessage}`;
                }
                callback(null, new LinkCheckResult(opts, link, res ? res.statusCode : 0, err)); // alive, returned 200 OK
                return;
            }

            // if HEAD fails (405 Method Not Allowed, etc), try GET
            request.get(options, function (err, res) {
              debugger
                // If enabled in opts, the response was a 429 (Too Many Requests) and there is a retry-after provided, wait and then retry
                if (opts.retryOn429 && res && res.statusCode === 429 && res.headers.hasOwnProperty('retry-after') && attempts < opts.retryCount) {
                    const retryStr = res.headers['retry-after'];
                    let retryInMs = 0;
                    // Standard for 'retry-after' header is in seconds.
                    // the format have to be checked before to see if it's an integer or a complex one.
                    // see https://github.com/tcort/link-check/issues/24

                    if(isNaN(retryStr)){
                      // Some HTTP servers return a non standard 'retry-after' header with incorrect values according to <https://tools.ietf.org/html/rfc7231#section-7.1.3>.
                      // tcort/link-check implemented a retry system to mainly enable Github links to be tested.
                      // Hopefully Github fixed this non standard behaviour on their side.
                      // tcort/link-check will then stop the support of non standard 'retry-after' header for releases greater or equal to 4.7.0.
                      // all this 'isNaN' part and the additionalMessage will then be removed from the code.
                      additionalMessage =
                        "Server returned a non standard \'retry-after\' header. "
                        + "Non standard \'retry-after\' header will not work after link-check 4.7.0 release. "
                        + "See https://github.com/tcort/link-check/releases/tag/v4.5.2 release note for details.";

                      let buf = '';
                      let letter = false;
                      for (let i = 0; i < retryStr.length; i++) {
                          let c = retryStr[i];
                          if (isNaN(c)) {
                              letter = true;
                              buf += c;
                          } else {
                              if (letter) {
                                  retryInMs += ms(buf.trim());
                                  buf = '';
                              }
                              letter = false;
                              buf += c;
                          }
                      }
                      retryInMs += ms(buf.trim());
                    }else{
                      // standard compliant header value conversion to milliseconds
                      const secondsToMilisecondsMultiplier = 1000;
                      retryInMs = parseFloat(retryStr) * secondsToMilisecondsMultiplier;
                    }

                    // Recurse back after the retry timeout has elapsed (incrementing our attempts to avoid an infinite loop)
                    setTimeout(check, retryInMs, link, opts, callback, attempts + 1, additionalMessage);
                } else {
                    if (additionalMessage){
                      err = (err == null) ? additionalMessage : `${err} ${additionalMessage}`;
                    }
                    callback(null, new LinkCheckResult(opts, link, res ? res.statusCode : 0, err));
                }
            }).pipe(new BlackHole());
        });
    },
};
<commit_msg>remove debug breakpoint<commit_after>"use strict";

const BlackHole = require('../BlackHole');
const isRelativeUrl = require('is-relative-url');
const LinkCheckResult = require('../LinkCheckResult');
const ms = require('ms');
const request = require('request');

module.exports = {

    check: function check(link, opts, callback, attempts, additionalMessage) {

        if (attempts == null) {
            attempts = 0;
        }

        const options = {
            uri: link,
            headers: {
                // override 'User-Agent' (some sites return `401` when the user-agent isn't a web browser)
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'
            },
            maxRedirects: 8,
            strictSSL: false,
            timeout: ms(opts.timeout),
        };

        if (opts.baseUrl && isRelativeUrl(link)) {
            options.baseUrl = opts.baseUrl;
        }

        if (opts.headers) {
            Object.assign(options.headers, opts.headers);
        }

        let retryCount = opts.retryCount || 2;

        request.head(options, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                if (additionalMessage){
                  err = (err == null) ? additionalMessage : `${err} ${additionalMessage}`;
                }
                callback(null, new LinkCheckResult(opts, link, res ? res.statusCode : 0, err)); // alive, returned 200 OK
                return;
            }

            // if HEAD fails (405 Method Not Allowed, etc), try GET
            request.get(options, function (err, res) {
                // If enabled in opts, the response was a 429 (Too Many Requests) and there is a retry-after provided, wait and then retry
                if (opts.retryOn429 && res && res.statusCode === 429 && res.headers.hasOwnProperty('retry-after') && attempts < opts.retryCount) {
                    const retryStr = res.headers['retry-after'];
                    let retryInMs = 0;
                    // Standard for 'retry-after' header is in seconds.
                    // the format have to be checked before to see if it's an integer or a complex one.
                    // see https://github.com/tcort/link-check/issues/24

                    if(isNaN(retryStr)){
                      // Some HTTP servers return a non standard 'retry-after' header with incorrect values according to <https://tools.ietf.org/html/rfc7231#section-7.1.3>.
                      // tcort/link-check implemented a retry system to mainly enable Github links to be tested.
                      // Hopefully Github fixed this non standard behaviour on their side.
                      // tcort/link-check will then stop the support of non standard 'retry-after' header for releases greater or equal to 4.7.0.
                      // all this 'isNaN' part and the additionalMessage will then be removed from the code.
                      additionalMessage =
                        "Server returned a non standard \'retry-after\' header. "
                        + "Non standard \'retry-after\' header will not work after link-check 4.7.0 release. "
                        + "See https://github.com/tcort/link-check/releases/tag/v4.5.2 release note for details.";

                      let buf = '';
                      let letter = false;
                      for (let i = 0; i < retryStr.length; i++) {
                          let c = retryStr[i];
                          if (isNaN(c)) {
                              letter = true;
                              buf += c;
                          } else {
                              if (letter) {
                                  retryInMs += ms(buf.trim());
                                  buf = '';
                              }
                              letter = false;
                              buf += c;
                          }
                      }
                      retryInMs += ms(buf.trim());
                    }else{
                      // standard compliant header value conversion to milliseconds
                      const secondsToMilisecondsMultiplier = 1000;
                      retryInMs = parseFloat(retryStr) * secondsToMilisecondsMultiplier;
                    }

                    // Recurse back after the retry timeout has elapsed (incrementing our attempts to avoid an infinite loop)
                    setTimeout(check, retryInMs, link, opts, callback, attempts + 1, additionalMessage);
                } else {
                    if (additionalMessage){
                      err = (err == null) ? additionalMessage : `${err} ${additionalMessage}`;
                    }
                    callback(null, new LinkCheckResult(opts, link, res ? res.statusCode : 0, err));
                }
            }).pipe(new BlackHole());
        });
    },
};
<|endoftext|>


<commit_before>function havefiles() {
	return ($('#num_active_files').val() != "0");
}

$(function() {

	var timer;

	$("#basesubmitdiv").addClass("fixed");
	$("#basesubmitdivbuttons").addClass("fixed");

	$("#basesubmitdiv").stop().animate({
		"background-color": "#fff",
		opacity: 0.94
	}, 10);

	if ($("#alloptions").height() >= $("#preview").height()) {
		$(".optionsandpreviewwrapper").height($("#alloptions").height());
	} else {
		$(".optionsandpreviewwrapper").height($("#preview").height());
	}

	$("form").submit(function() {
		if (!havefiles()) {
			$("#submiterrormessage1").show().fadeOut(1200, "easeInOutCubic");
			return false;
		}
	});

	// throttle scroll event
	$(window).scroll(function(){
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function(){
			// fix buttons to bottom
			var offset = $(".footer").height();

			if($(window).scrollTop() > 80) {
				$("#alloptions").addClass("fixed");
			} else {
				$("#alloptions").removeClass("fixed");
			}

			if($(window).scrollTop() + $(window).height() < $(document).height()-90) {
				$("#basesubmitdiv").addClass("fixed");
				$("#basesubmitdivbuttons").addClass("fixed");
				// $("#alloptions").addClass("fixed");

				$("#basesubmitdiv").stop().animate({
					"background-color": "#fff",
					opacity: 0.94
				}, 100);
			} else {
				$("#basesubmitdiv").removeClass("fixed");
				$("#basesubmitdivbuttons").removeClass("fixed");
				// $("#alloptions").removeClass("fixed");

				$("#basesubmitdiv").stop().animate({
					"background-color": "none",
					opacity: 1
				}, 100);
			}
		}, 10);
	});
});<commit_msg>tweaking ui<commit_after>function havefiles() {
	return ($('#num_active_files').val() != "0");
}

$(function() {

	var timer;

	if ($("#alloptions").height() > $(window).height() ||
		$("#preview").height() > $(window).height()) {

		$("#basesubmitdiv").addClass("fixed");
		$("#basesubmitdivbuttons").addClass("fixed");
	}

	$("#basesubmitdiv").stop().animate({
		"background-color": "#fff",
		opacity: 0.94
	}, 10);

	if ($("#alloptions").height() >= $("#preview").height()) {
		$(".optionsandpreviewwrapper").height($("#alloptions").height()+60);
	} else {
		$(".optionsandpreviewwrapper").height($("#preview").height()+60);
	}

	$("form").submit(function() {
		if (!havefiles()) {
			$("#submiterrormessage1").show().fadeOut(1200, "easeInOutCubic");
			return false;
		}
	});

	// throttle scroll event
	$(window).scroll(function(){
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function(){
			// fix buttons to bottom
			var offset = $(".footer").height();

			if($(window).scrollTop() > 90) {
				$("#alloptions").addClass("fixed");
			} else {
				$("#alloptions").removeClass("fixed");
			}

			if($(window).scrollTop() + $(window).height() < $(document).height()-90) {
				$("#basesubmitdiv").addClass("fixed");
				$("#basesubmitdivbuttons").addClass("fixed");
				// $("#alloptions").addClass("fixed");

				$("#basesubmitdiv").stop().animate({
					"background-color": "#fff",
					opacity: 0.94
				}, 100);
			} else {
				$("#basesubmitdiv").removeClass("fixed");
				$("#basesubmitdivbuttons").removeClass("fixed");
				// $("#alloptions").removeClass("fixed");

				$("#basesubmitdiv").stop().animate({
					"background-color": "none",
					opacity: 1
				}, 100);
			}
		}, 10);
	});
});<|endoftext|>


<commit_before>"use strict";

importScripts("thirdparty/bluebird/js/browser/bluebird.js");
importScripts("thirdparty/typescript/bin/typescriptServices.js");

var kLiveSourceFileName = "live.ts";
var kLiveCompiledFileNmae = "live.js";

function createCompilerHost(source, libSource, options) {
  var output;
  var host = {
    getSourceFile: function(filename, languageVersion) {
      var source = this.__fileContents[filename];
      if (source) {
        return ts.createSourceFile(filename, source, options, "0");
      }
    },
    writeFile: function(name, text, writeByteOrderMark) {
      if (name === kLiveCompiledFileNmae) {
        output = text;
      }
    },
    getDefaultLibFilename: function() {
      return "lib.d.ts";
    },
    useCaseSensitiveFileNames: function() { return false; },
    getCanonicalFileName: function(filename) { return filename; },
    getCurrentDirectory: function() { return ""; },
    getNewLine: function() { return "\n"; },
    getOutput: function() { return output; },

    __options: options,
    __fileContents: {},
  };

  host.__fileContents[kLiveSourceFileName] = source;
  host.__fileContents["lib.d.ts"] = libSource;
  return host;
}

function compileSource(source, libSource) {
  var options = {
    target: ts.ScriptTarget.ES5
  };
  var host = createCompilerHost(source, libSource, options);
  var program = ts.createProgram([kLiveSourceFileName], options, host);
  var errors = program.getDiagnostics();

  if (errors.length) {
    return {
      type: "error",
      errors: errorText(errors)
    };
  }

  var checker = program.getTypeChecker(true);
  errors = checker.getDiagnostics();
  checker.emitFiles(program.getSourceFile(kLiveSourceFileName));

  return {
    type: "compiled",
    source: host.getOutput(),
    errors: errorText(errors)
  };

  function errorText(errors) {
    return errors.map(function(e) {
      if (e.file) {
        var start = e.file.getLineAndCharacterFromPosition(e.start);
        return start.line + ": " + e.messageText;
      }
      return "Error: " + e.messageText;
    }).join("\n");
  }
}

function loadDefaultLibrary(defaultLib) {
  return new Promise(function(resolve, reject) {
    if (defaultLibSource !== void 0) return resolve();
    var xhr = new XMLHttpRequest();
    var url = "thirdparty/typescript/bin/lib.d.ts";
    xhr.open("get", url);
    xhr.onload = function loaded(e) {
      defaultLibSource = e.target.response;
      resolve();
    }
    xhr.onerror = function error(e) {
      reject({
        type: "error",
        errors: "Failed to load " + url + ": " + (e.statusText || "error.")
      })
    }
    xhr.send();
  });
}

var defaultLibSource = void 0;

function compileInternal(source) {
  return loadDefaultLibrary().
    then(function() {
      try {
        return compileSource(source, defaultLibSource);
      } catch (e) {
        var err = e.message;
        var stack = (e.stack || "").
          replace(new RegExp("^" + e.name + "(\r*\n*)*:?", ""), "").
          replace(err, "").
          replace(/^(\s|\r|\n)*/, "");
        e = err.replace(/^error:\s*/i, "") + "\n\n" + stack;
        return {
          type: "error",
          errors: "CompilerError:\n\n" + e
        };
      }
    });
}

onmessage = function(e) {
  var msg = e.data;
  var source = msg.source;
  compileInternal(source).then(postMessage, postMessage);
}
<commit_msg>fix(types): declare generic types for print/alert global functions<commit_after>"use strict";

importScripts("thirdparty/bluebird/js/browser/bluebird.js");
importScripts("thirdparty/typescript/bin/typescriptServices.js");

var kLiveSourceFileName = "live.ts";
var kLiveCompiledFileNmae = "live.js";

var kBuiltinFunctionTypes = [
  "declare function print(a?, b?, c?, d?, e?, f?, g?, h?, i?, j?, k?, l?, m?, n?, o?, p?, q?, r?, s?, t?, u?, v?, w?, x?, y?, z?);",
  "declare function alert(a?, b?, c?, d?, e?, f?, g?, h?, i?, j?, k?, l?, m?, n?, o?, p?, q?, r?, s?, t?, u?, v?, w?, x?, y?, z?);"
].join("\n") + "\n\n";

function createCompilerHost(source, libSource, options) {
  var output;
  var host = {
    getSourceFile: function(filename, languageVersion) {
      var source = this.__fileContents[filename];
      if (source) {
        return ts.createSourceFile(filename, source, options, "0");
      }
    },
    writeFile: function(name, text, writeByteOrderMark) {
      if (name === kLiveCompiledFileNmae) {
        output = text;
      }
    },
    getDefaultLibFilename: function() {
      return "lib.d.ts";
    },
    useCaseSensitiveFileNames: function() { return false; },
    getCanonicalFileName: function(filename) { return filename; },
    getCurrentDirectory: function() { return ""; },
    getNewLine: function() { return "\n"; },
    getOutput: function() { return output; },

    __options: options,
    __fileContents: {},
  };

  host.__fileContents[kLiveSourceFileName] = source;
  host.__fileContents["lib.d.ts"] = libSource;
  return host;
}

function compileSource(source, libSource) {
  var options = {
    target: ts.ScriptTarget.ES5
  };
  var host = createCompilerHost(source, kBuiltinFunctionTypes + libSource, options);
  var program = ts.createProgram([kLiveSourceFileName], options, host);
  var errors = program.getDiagnostics();

  if (errors.length) {
    return {
      type: "error",
      errors: errorText(errors)
    };
  }

  var checker = program.getTypeChecker(true);
  errors = checker.getDiagnostics();
  checker.emitFiles(program.getSourceFile(kLiveSourceFileName));

  return {
    type: "compiled",
    source: host.getOutput(),
    errors: errorText(errors)
  };

  function errorText(errors) {
    return errors.map(function(e) {
      if (e.file) {
        var start = e.file.getLineAndCharacterFromPosition(e.start);
        return start.line + ": " + e.messageText;
      }
      return "Error: " + e.messageText;
    }).join("\n");
  }
}

function loadDefaultLibrary(defaultLib) {
  return new Promise(function(resolve, reject) {
    if (defaultLibSource !== void 0) return resolve();
    var xhr = new XMLHttpRequest();
    var url = "thirdparty/typescript/bin/lib.d.ts";
    xhr.open("get", url);
    xhr.onload = function loaded(e) {
      defaultLibSource = e.target.response;
      resolve();
    }
    xhr.onerror = function error(e) {
      reject({
        type: "error",
        errors: "Failed to load " + url + ": " + (e.statusText || "error.")
      })
    }
    xhr.send();
  });
}

var defaultLibSource = void 0;

function compileInternal(source) {
  return loadDefaultLibrary().
    then(function() {
      try {
        return compileSource(source, defaultLibSource);
      } catch (e) {
        var err = e.message;
        var stack = (e.stack || "").
          replace(new RegExp("^" + e.name + "(\r*\n*)*:?", ""), "").
          replace(err, "").
          replace(/^(\s|\r|\n)*/, "");
        e = err.replace(/^error:\s*/i, "") + "\n\n" + stack;
        return {
          type: "error",
          errors: "CompilerError:\n\n" + e
        };
      }
    });
}

onmessage = function(e) {
  var msg = e.data;
  var source = msg.source;
  compileInternal(source).then(postMessage, postMessage);
}
<|endoftext|>