<commit_before>/*
 * jQuery gentleSelect plugin
 * http://shawnchin.github.com/jquery-gentleSelect
 *
 * Copyright (c) 2010 Shawn Chin.
 * Licensed under the MIT license.
 *
 * Usage:
 *  (JS)
 *
 *  $('#myselect').gentleSelect(); // default. single column
 *
 * $('#myselect').gentleSelect({ // 3 columns, 150px wide each
 *    itemWidth : 150,
 *    columns   : 3,
 * });
 *
 *  (HTML)
 *  <select id='myselect'><options> .... </options></select>
 *
 */
(function($) {

    var defaults = {
        minWidth  : 100, // only applies if columns and itemWidth not set
        itemWidth : undefined,
        columns   : undefined,
        rows      : undefined,
        title     : undefined
    }

    function defined(obj) {
        if (typeof obj == "undefined") { return false; }
        else { return true; }
    }

    function hasError(c, o) {
        if (c.attr("multiple") == true) {
            $.error("Sorry, gentleSelect does not work with multiple=true yet");
            return true;
        }
        if (defined(o.columns) && defined(o.rows)) {
            $.error("gentleSelect: You cannot supply both 'rows' and 'columns'");
            return true;
        }
        if (defined(o.columns) && !defined(o.itemWidth)) {
            $.error("gentleSelect: itemWidth must be supplied if 'columns' is specified");
            return true;
        }
        if (defined(o.rows) && !defined(o.itemWidth)) {
            $.error("gentleSelect: itemWidth must be supplied if 'rows' is specified");
            return true;
        }
        return false;
    }

    var methods = {
        init : function(options) {
            var o = $.extend({}, defaults, options);

            if (hasError(this, o)) { return this; }; // check for errors
            this.hide(); // hide original select box

            // initialise  to replace select box
            var label = $("" + this.find(":selected").text() + "")
                .insertBefore(this)
                .bind("mouseenter.gentleselect", event_handlers.labelHoverIn)
                .bind("mouseleave.gentleselect", event_handlers.labelHoverOut)
                .bind("click.gentleselect", event_handlers.labelClick)
                .data("root", this);
            this.data("label", label)
                .data("options", o);

            // generate list of options
            var ul = $("

");
            this.find("option").each(function() {
                var li = $("
" + $(this).text() + "
")
                    .data("value", $(this).attr("value"))
                    .data("name", $(this).text())
                    .appendTo(ul);
                if ($(this).attr("selected")) { li.addClass("selected"); }
            });

            // build dialog box
            var dialog = $("

")
                .append(ul)
                .insertAfter(label)
                .bind("click.gentleselect", event_handlers.dialogClick)
                .bind("mouseleave.gentleselect", event_handlers.dialogHoverOut)
                .data("label", label)
                .data("root", this);
            this.data("dialog", dialog);

            // if to be displayed in columns
            if (defined(o.columns) || defined(o.rows)) {

                // Update CSS
                ul.css("float", "left")
                    .find("li").width(o.itemWidth).css("float","left");

                var f = ul.find("li:first");
                var actualWidth = o.itemWidth
                    + parseInt(f.css("padding-left"))
                    + parseInt(f.css("padding-right"));
                var elemCount = ul.find("li").length;
                if (defined(o.columns)) {
                    var cols = parseInt(o.columns);
                    var rows = Math.ceil(elemCount / cols);
                } else {
                    var rows = parseInt(o.rows);
                    var cols = Math.ceil(elemCount / rows);
                }
                dialog.width(actualWidth * cols);

                // add padding
                for (var i = 0; i < (rows * cols) - elemCount; i++) {
                    $("

").appendTo(ul);
                }

                // reorder elements
                var ptr = [];
                var idx = 0;
                ul.find("li").each(function() {
                    if (idx < rows) {
                        ptr[idx] = $(this);
                    } else {
                        var p = idx % rows;
                        $(this).insertAfter(ptr[p]);
                        ptr[p] = $(this);
                    }
                    idx++;
                });
            } else if (typeof o.minWidth == "number") {
                dialog.css("min-width", o.minWidth);
            }

            if (defined(o.title)) {
                $("
" + o.title + "
").prependTo(dialog);
            }

            // ESC key should hide all dialog boxes
            $(document).bind("keyup.gentleselect", event_handlers.keyUp);

            return this;
        },

        // if select box was updated externally, we need to bring everything
        // else up to speed.
        update : function() {
            var root = this;
            var v = this.val(); // current value of select box
            this.data("dialog").find("li").each(function() {
                if ($(this).data("value") == v) {
                    $(this).addClass("selected");
                    root.data("label").text($(this).data("name"));
                } else {
                    $(this).removeClass("selected");
                };
            });
            return this;
        }
    };

    var event_handlers = {

        labelHoverIn : function() {
            $(this).addClass('gentleselect-label-highlight');
        },

        labelHoverOut : function() {
            $(this).removeClass('gentleselect-label-highlight');
        },

        labelClick : function() {
            var pos = $(this).position();
            var dialog = $(this).data("root").data("dialog")
                .css("top", pos.top + $(this).data("root").height)
                .css("left", pos.left + 1)
                .slideDown();

        },

        dialogHoverOut : function() {
            $(this).hide();
        },

        dialogClick : function(e) {
            var clicked = $(e.target);
            $(this).fadeOut("fast"); // hide dialog

            if (clicked.is("li") && !clicked.hasClass("gentleselect-dummy")) {
                var value = clicked.data("value");
                var name = clicked.data("name");
                var label = $(this).data("label")
                    .text(name); // update label

                // update selected li
                $(this).find("li.selected").removeClass("selected");
                clicked.addClass("selected");
                // update actual selectbox
                var actual = $(this).data("root").val(value).trigger("change");

            }
        },

        keyUp : function(e) {
            if (e.keyCode == 27 ) { // ESC
                $(".gentleselect-dialog").hide();
            }
        }
    };

    $.fn.gentleSelect = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.gentleSelect' );
        }
    };

})(jQuery);
<commit_msg>Fixed bug where IE would freak out because if the weird method invocation jquery is using. Changed it to a standard method invocation and everything works.<commit_after>/*
 * jQuery gentleSelect plugin
 * http://shawnchin.github.com/jquery-gentleSelect
 *
 * Copyright (c) 2010 Shawn Chin.
 * Licensed under the MIT license.
 *
 * Usage:
 *  (JS)
 *
 *  $('#myselect').gentleSelect(); // default. single column
 *
 * $('#myselect').gentleSelect({ // 3 columns, 150px wide each
 *    itemWidth : 150,
 *    columns   : 3,
 * });
 *
 *  (HTML)
 *  <select id='myselect'><options> .... </options></select>
 *
 */
(function($) {

    var defaults = {
        minWidth  : 100, // only applies if columns and itemWidth not set
        itemWidth : undefined,
        columns   : undefined,
        rows      : undefined,
        title     : undefined
    }

    function defined(obj) {
        if (typeof obj == "undefined") { return false; }
        else { return true; }
    }

    function hasError(c, o) {
        if (c.attr("multiple") == true) {
            $.error("Sorry, gentleSelect does not work with multiple=true yet");
            return true;
        }
        if (defined(o.columns) && defined(o.rows)) {
            $.error("gentleSelect: You cannot supply both 'rows' and 'columns'");
            return true;
        }
        if (defined(o.columns) && !defined(o.itemWidth)) {
            $.error("gentleSelect: itemWidth must be supplied if 'columns' is specified");
            return true;
        }
        if (defined(o.rows) && !defined(o.itemWidth)) {
            $.error("gentleSelect: itemWidth must be supplied if 'rows' is specified");
            return true;
        }
        return false;
    }

    var methods = {
        init : function(options) {
            var o = $.extend({}, defaults, options);

            if (hasError(this, o)) { return this; }; // check for errors
            this.hide(); // hide original select box

            // initialise  to replace select box
            var label = $("" + this.find(":selected").text() + "")
                .insertBefore(this)
                .bind("mouseenter.gentleselect", event_handlers.labelHoverIn)
                .bind("mouseleave.gentleselect", event_handlers.labelHoverOut)
                .bind("click.gentleselect", event_handlers.labelClick)
                .data("root", this);
            this.data("label", label)
                .data("options", o);

            // generate list of options
            var ul = $("

");
            this.find("option").each(function() {
                var li = $("
" + $(this).text() + "
")
                    .data("value", $(this).attr("value"))
                    .data("name", $(this).text())
                    .appendTo(ul);
                if ($(this).attr("selected")) { li.addClass("selected"); }
            });

            // build dialog box
            var dialog = $("

")
                .append(ul)
                .insertAfter(label)
                .bind("click.gentleselect", event_handlers.dialogClick)
                .bind("mouseleave.gentleselect", event_handlers.dialogHoverOut)
                .data("label", label)
                .data("root", this);
            this.data("dialog", dialog);

            // if to be displayed in columns
            if (defined(o.columns) || defined(o.rows)) {

                // Update CSS
                ul.css("float", "left")
                    .find("li").width(o.itemWidth).css("float","left");

                var f = ul.find("li:first");
                var actualWidth = o.itemWidth
                    + parseInt(f.css("padding-left"))
                    + parseInt(f.css("padding-right"));
                var elemCount = ul.find("li").length;
                if (defined(o.columns)) {
                    var cols = parseInt(o.columns);
                    var rows = Math.ceil(elemCount / cols);
                } else {
                    var rows = parseInt(o.rows);
                    var cols = Math.ceil(elemCount / rows);
                }
                dialog.width(actualWidth * cols);

                // add padding
                for (var i = 0; i < (rows * cols) - elemCount; i++) {
                    $("

").appendTo(ul);
                }

                // reorder elements
                var ptr = [];
                var idx = 0;
                ul.find("li").each(function() {
                    if (idx < rows) {
                        ptr[idx] = $(this);
                    } else {
                        var p = idx % rows;
                        $(this).insertAfter(ptr[p]);
                        ptr[p] = $(this);
                    }
                    idx++;
                });
            } else if (typeof o.minWidth == "number") {
                dialog.css("min-width", o.minWidth);
            }

            if (defined(o.title)) {
                $("
" + o.title + "
").prependTo(dialog);
            }

            // ESC key should hide all dialog boxes
            $(document).bind("keyup.gentleselect", event_handlers.keyUp);

            return this;
        },

        // if select box was updated externally, we need to bring everything
        // else up to speed.
        update : function() {
            var root = this;
            var v = this.val(); // current value of select box
            this.data("dialog").find("li").each(function() {
                if ($(this).data("value") == v) {
                    $(this).addClass("selected");
                    root.data("label").text($(this).data("name"));
                } else {
                    $(this).removeClass("selected");
                };
            });
            return this;
        }
    };

    var event_handlers = {

        labelHoverIn : function() {
            $(this).addClass('gentleselect-label-highlight');
        },

        labelHoverOut : function() {
            $(this).removeClass('gentleselect-label-highlight');
        },

        labelClick : function() {
            var pos = $(this).position();
            var dialog = $(this).data("root").data("dialog")
                .css("top", pos.top + $(this).data("root").height())
                .css("left", pos.left + 1)
                .slideDown();

        },

        dialogHoverOut : function() {
            $(this).hide();
        },

        dialogClick : function(e) {
            var clicked = $(e.target);
            $(this).fadeOut("fast"); // hide dialog

            if (clicked.is("li") && !clicked.hasClass("gentleselect-dummy")) {
                var value = clicked.data("value");
                var name = clicked.data("name");
                var label = $(this).data("label")
                    .text(name); // update label

                // update selected li
                $(this).find("li.selected").removeClass("selected");
                clicked.addClass("selected");
                // update actual selectbox
                var actual = $(this).data("root").val(value).trigger("change");

            }
        },

        keyUp : function(e) {
            if (e.keyCode == 27 ) { // ESC
                $(".gentleselect-dialog").hide();
            }
        }
    };

    $.fn.gentleSelect = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.gentleSelect' );
        }
    };

})(jQuery);
<|endoftext|>


<commit_before>import { observable } from 'mobx';
import { getWeb3 } from '../utils/blockchainHelpers'

class Web3Store {

	@observable web3;
	@observable curAddress
	@observable accounts

	constructor(strategies) {
		getWeb3((web3) => {
			this.web3 = web3
			web3.eth.getAccounts().then((accounts) => {
				this.accounts = accounts
        this.curAddress = accounts[0]
  		})
		})
	}
}

const web3Store = new Web3Store();

export default web3Store;
export { Web3Store };
<commit_msg>Fix blank screen when MetaMask is not installed<commit_after>import { observable } from 'mobx';
import { getWeb3 } from '../utils/blockchainHelpers'

class Web3Store {

	@observable web3;
	@observable curAddress
	@observable accounts

	constructor(strategies) {
		getWeb3((web3) => {
      if (web3) {
        this.web3 = web3
        web3.eth.getAccounts().then((accounts) => {
          this.accounts = accounts
          this.curAddress = accounts[0]
        })
      }
		})
	}
}

const web3Store = new Web3Store();

export default web3Store;
export { Web3Store };
<|endoftext|>


<commit_before>{% load l10n %}

{% block vars %}var {{ module }} = {};
{{ module }}.map = null; {{ module }}.controls = null; {{ module }}.panel = null; {{ module }}.bounds = null; {{ module }}.layers = {}; {{ module }}.info = null;
{% endblock %}

{{ module }}_init = function(){
    var base_layer = new ol.layer.Tile({
        source: new ol.source.OSM(),
    });

    {% for layer in map_layers %}
    {{ module }}.layers[{{ forloop.counter0 }}] = new ol.layer.Vector({
        source: new ol.source.Vector({
            parser: new ol.parser.GeoJSON(),
            url: '{{ layer.url }}'
        }),
        style: new ol.style.Style({
            symbolizers: [
                new ol.style.Icon({
                    url: '{{ layer.external_graphic }}',
                })
            ]
        })
    });
    {% endfor %}

    {{ module }}.map = new ol.Map({
        target: '{{ module }}_map',
        layers: [
            base_layer{% for layer in map_layers %}, {{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}
        ],
        renderer: ol.RendererHint.CANVAS,
        view: new ol.View2D({
          center: [0, 0],
          zoom: 2
        })
    });

    {{ module }}.info = $('#{{ module }}_info');

    {{ module }}.info.popover({
      animation: false,
      placement: 'top',
      html: true,
      trigger: 'manual'
    });

    var displayFeatureInfo = function(pixel) {
      {{ module }}.info.css({
        left: pixel[0] + 'px',
        top: (pixel[1] - 5) + 'px'
      });
      {{ module }}.map.getFeatures({
        pixel: pixel,
        layers: [{% for layer in map_layers %}{% if forloop.first %}{% else %}, {% endif %}{{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}],
        success: function(layerFeatures) {
          var feature = layerFeatures[0][0];
          if (feature) {
            {{ module }}.info.popover('hide')
                .attr('data-original-title', feature.e.name)
                .attr('data-content', "")
                .popover('show');
          } else {
            {{ module }}.info.popover('hide');
          }
        }
      });
    };

    var goToFeature = function(pixel) {
      {{ module }}.map.getFeatures({
        pixel: pixel,
        layers: [{% for layer in map_layers %}{% if forloop.first %}{% else %}, {% endif %}{{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}],
        success: function(layerFeatures) {
          var feature = layerFeatures[0][0];
          if (feature) {
            window.location.href = feature.e.url;
          } else {
          }
        }
      });
    };

    $({{ module }}.map.getViewport()).on('mousemove', function(evt) {
      var pixel = {{ module }}.map.getEventPixel(evt.originalEvent);
      displayFeatureInfo(pixel);
    });

    $({{ module }}.map.getViewport()).on('click', function(evt) {
      var pixel = {{ module }}.map.getEventPixel(evt.originalEvent);
      goToFeature(pixel);
    });

}
<commit_msg>fix bug with on [hover|click] feature actions on several layers<commit_after>{% load l10n %}

{% block vars %}var {{ module }} = {};
{{ module }}.map = null; {{ module }}.controls = null; {{ module }}.panel = null; {{ module }}.bounds = null; {{ module }}.layers = {}; {{ module }}.info = null;
{% endblock %}

{{ module }}_init = function(){
    var base_layer = new ol.layer.Tile({
        source: new ol.source.OSM(),
    });

    {% for layer in map_layers %}
    {{ module }}.layers[{{ forloop.counter0 }}] = new ol.layer.Vector({
        source: new ol.source.Vector({
            parser: new ol.parser.GeoJSON(),
            url: '{{ layer.url }}'
        }),
        style: new ol.style.Style({
            symbolizers: [
                new ol.style.Icon({
                    url: '{{ layer.external_graphic }}',
                })
            ]
        })
    });
    {% endfor %}

    {{ module }}.map = new ol.Map({
        target: '{{ module }}_map',
        layers: [
            base_layer{% for layer in map_layers %}, {{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}
        ],
        renderer: ol.RendererHint.CANVAS,
        view: new ol.View2D({
          center: [0, 0],
          zoom: 2
        })
    });

    {{ module }}.info = $('#{{ module }}_info');

    {{ module }}.info.popover({
      animation: false,
      placement: 'top',
      html: true,
      trigger: 'manual'
    });

    var displayFeatureInfo = function(pixel) {
      {{ module }}.info.css({
        left: pixel[0] + 'px',
        top: (pixel[1] - 5) + 'px'
      });
      {{ module }}.map.getFeatures({
        pixel: pixel,
        layers: [{% for layer in map_layers %}{% if forloop.first %}{% else %}, {% endif %}{{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}],
        success: function(layerFeatures) {
          var flattenFeatures = [].concat.apply([], layerFeatures);
          var feature = flattenFeatures[0];
          if (feature) {
            {{ module }}.info.popover('hide')
                .attr('data-original-title', feature.e.name)
                .attr('data-content', "")
                .popover('show');
          } else {
            {{ module }}.info.popover('hide');
          }
        }
      });
    };

    var goToFeature = function(pixel) {
      {{ module }}.map.getFeatures({
        pixel: pixel,
        layers: [{% for layer in map_layers %}{% if forloop.first %}{% else %}, {% endif %}{{ module }}.layers[{{ forloop.counter0 }}]{% endfor %}],
        success: function(layerFeatures) {
          var flattenFeatures = [].concat.apply([], layerFeatures);
          var feature = flattenFeatures[0];
          if (feature) {
            window.location.href = feature.e.url;
          } else {
          }
        }
      });
    };

    $({{ module }}.map.getViewport()).on('mousemove', function(evt) {
      var pixel = {{ module }}.map.getEventPixel(evt.originalEvent);
      displayFeatureInfo(pixel);
    });

    $({{ module }}.map.getViewport()).on('click', function(evt) {
      var pixel = {{ module }}.map.getEventPixel(evt.originalEvent);
      goToFeature(pixel);
    });

}
<|endoftext|>


<commit_before>// test whether a string is camel-case
var hasSpace = /\s/
var hasSeparator = /[\W_]/
var hasCamel = /([a-z][A-Z]|[A-Z][a-z])/
// separator splitter
var separatorSplitter = /[\W_]+(.|$)/g
// camelcase splitter
var camelSpitter = /(.)([A-Z]+)/g

// remove any starting case from a 'string', like camel or snake, but keep
// spaces and punctuation that may be important otherwise
function toNoCase (str) {
  if (hasSpace.test(str)) return str.toLowerCase()
  if (hasSeparator.test(str)) return (unseparate(str) || str).toLowerCase()
  if (hasCamel.test(string)) return uncamelize(string).toLowerCase()
  return str.toLowerCase()
}

// un-separate a 'string'
function unseparate (str) {
  return str.replace(separatorSplitter, function (m, next) {
    return next ? ' ' + next : ''
  })
}

// un-camelize a 'string'
function uncamelize (str) {
  return str.replace(camelSpitter, function (m, previous, uppers) {
    return previous + ' ' + uppers.toLowerCase().split('').join(' ')
  })
}

module.exports = toNoCase

/*
    var clean = require('to-no-case');

    clean('camelCase');       // "camel case"
    clean('snake_case');      // "snake case"
    clean('slug-case');       // "slug case"
    clean('Title of Case');   // "title of case"
    clean('Sentence case.');  // "sentence case."
*/
<commit_msg>update string/case-none — fix typo<commit_after>// test whether a string is camel-case
var hasSpace = /\s/
var hasSeparator = /[\W_]/
var hasCamel = /([a-z][A-Z]|[A-Z][a-z])/
// separator splitter
var separatorSplitter = /[\W_]+(.|$)/g
// camelcase splitter
var camelSpitter = /(.)([A-Z]+)/g

// remove any starting case from a 'string', like camel or snake, but keep
// spaces and punctuation that may be important otherwise
function toNoCase (str) {
  if (hasSpace.test(str)) return str.toLowerCase()
  if (hasSeparator.test(str)) return (unseparate(str) || str).toLowerCase()
  if (hasCamel.test(str)) return uncamelize(str).toLowerCase()
  return str.toLowerCase()
}

// un-separate a 'string'
function unseparate (str) {
  return str.replace(separatorSplitter, function (m, next) {
    return next ? ' ' + next : ''
  })
}

// un-camelize a 'string'
function uncamelize (str) {
  return str.replace(camelSpitter, function (m, previous, uppers) {
    return previous + ' ' + uppers.toLowerCase().split('').join(' ')
  })
}

module.exports = toNoCase

/*
    var clean = require('to-no-case');

    clean('camelCase');       // "camel case"
    clean('snake_case');      // "snake case"
    clean('slug-case');       // "slug case"
    clean('Title of Case');   // "title of case"
    clean('Sentence case.');  // "sentence case."
*/
<|endoftext|>


<commit_before>const GH_RESERVED_USER_NAMES = [
  'settings',
  'orgs',
  'organizations',
  'site',
  'blog',
  'about',
  'explore',
  'styleguide',
  'showcases',
  'trending',
  'stars',
  'dashboard',
  'notifications',
  'search',
  'developer',
  'account',
  'pulls',
  'issues',
  'features',
  'contact',
  'security',
  'join',
  'login',
  'watching',
  'new',
  'integrations',
  'gist',
  'business',
  'mirrors',
  'open-source',
  'personal',
  'pricing',
  'sessions',
  'topics',
  'users',
  'marketplace'
];
const GH_RESERVED_REPO_NAMES = ['followers', 'following', 'repositories'];
const GH_404_SEL = '#parallax_wrapper';
const GH_RAW_CONTENT = 'body > pre';

class OctotreeService {
  constructor() {
    this.reset();
  }

  load(loadFn) {
    loadFn();
  }

  // Hooks
  activate(inputs, opts) {}

  applyOptions(opts) {
    return false;
  }

  reset() {
    this.getAccessToken = this._getAccessToken;
    this.shouldShowOctotree = this._shouldShowOctotree;
    this.getInvalidTokenMessage = this._getInvalidTokenMessage;
  }

  _getAccessToken() {
    return window.store.get(window.STORE.TOKEN);
  }

  _getInvalidTokenMessage({responseStatus, requestHeaders}) {
    return (
      'The GitHub access token is invalid. ' +
      'Please go to Settings and update the token.'
    );
  }

  _shouldShowOctotree() {
    if ($(GH_404_SEL).length) {
      return false;
    }

    // Skip raw page
    if ($(GH_RAW_CONTENT).length) {
      return false;
    }

    // (username)/(reponame)[/(type)][/(typeId)]
    const match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?(?:\/([^\/]+))?/);
    if (!match) {
      return false;
    }

    const username = match[1];
    const reponame = match[2];

    // Not a repository, skip
    if (~GH_RESERVED_USER_NAMES.indexOf(username) || ~GH_RESERVED_REPO_NAMES.indexOf(reponame)) {
      return false;
    }

    return true;
  }
}

window.octotree = new OctotreeService();
<commit_msg>Minor refactor<commit_after>const GH_RESERVED_USER_NAMES = [
  'settings',
  'orgs',
  'organizations',
  'site',
  'blog',
  'about',
  'explore',
  'styleguide',
  'showcases',
  'trending',
  'stars',
  'dashboard',
  'notifications',
  'search',
  'developer',
  'account',
  'pulls',
  'issues',
  'features',
  'contact',
  'security',
  'join',
  'login',
  'watching',
  'new',
  'integrations',
  'gist',
  'business',
  'mirrors',
  'open-source',
  'personal',
  'pricing',
  'sessions',
  'topics',
  'users',
  'marketplace'
];
const GH_RESERVED_REPO_NAMES = ['followers', 'following', 'repositories'];
const GH_404_SEL = '#parallax_wrapper';
const GH_RAW_CONTENT = 'body > pre';

class OctotreeService {
  constructor() {
    this.reset();
  }

  // Hooks
  activate(inputs, opts) {}

  applyOptions(opts) {
    return false;
  }

  // Public
  load(loadFn) {
    loadFn();
  }

  reset() {
    this.getAccessToken = this._getAccessToken;
    this.shouldShowOctotree = this._shouldShowOctotree;
    this.getInvalidTokenMessage = this._getInvalidTokenMessage;
  }

  // Private
  _getAccessToken() {
    return window.store.get(window.STORE.TOKEN);
  }

  _getInvalidTokenMessage({responseStatus, requestHeaders}) {
    return (
      'The GitHub access token is invalid. ' +
      'Please go to Settings and update the token.'
    );
  }

  _shouldShowOctotree() {
    if ($(GH_404_SEL).length) {
      return false;
    }

    // Skip raw page
    if ($(GH_RAW_CONTENT).length) {
      return false;
    }

    // (username)/(reponame)[/(type)][/(typeId)]
    const match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?(?:\/([^\/]+))?/);
    if (!match) {
      return false;
    }

    const username = match[1];
    const reponame = match[2];

    // Not a repository, skip
    if (~GH_RESERVED_USER_NAMES.indexOf(username) || ~GH_RESERVED_REPO_NAMES.indexOf(reponame)) {
      return false;
    }

    return true;
  }
}

window.octotree = new OctotreeService();
<|endoftext|>


<commit_before>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import RSVP from 'rsvp';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            if (options.developer) {
                enabled = enabled && this.get('config.enableDeveloperExperiments');
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    koenigEditor: feature('koenigEditor', {developer: true}),
    publicAPI: feature('publicAPI'),
    subscribers: feature('subscribers'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return RSVP.hash({
            settings: this.get('settings').fetch(),
            user: this.get('session.user')
        }).then(({user}) => {
            this.set('_user', user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.get('notifications').showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled || this.get('nightShift');

        return this.get('lazyLoader').loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
            $('link[title=light]').prop('disabled', nightShift);
        });
    }
});
<commit_msg>🐛 Fixed need to click Night Shift toggle 3 times in certain circumstances (#965)<commit_after>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import RSVP from 'rsvp';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            if (options.developer) {
                enabled = enabled && this.get('config.enableDeveloperExperiments');
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    koenigEditor: feature('koenigEditor', {developer: true}),
    publicAPI: feature('publicAPI'),
    subscribers: feature('subscribers'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return RSVP.hash({
            settings: this.get('settings').fetch(),
            user: this.get('session.user')
        }).then(({user}) => {
            this.set('_user', user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.get('notifications').showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled;

        if (typeof nightShift === 'undefined') {
            nightShift = enabled || this.get('nightShift');
        }

        return this.get('lazyLoader').loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
            $('link[title=light]').prop('disabled', nightShift);
        });
    }
});
<|endoftext|>


<commit_before>require("./make_default_helpers_test");

var getRenderer = require('./get_renderer');
var getPartials = require('./get_partials');
var build = require("./build");
var assert = require('assert');
var Q = require('q');
var path = require('path');
var rmdir = require('rimraf');
var fs = require('fs');
var read = Q.denodeify(fs.readFile);

describe("documentjs/lib/generators/html/build",function(){

	beforeEach(function(done){
		rmdir(path.join(__dirname,"..","site","static"), function(e){
			rmdir(path.join(__dirname,"..","site","templates"), done);
		});
	});

	it("get_renderer and get_partial work",function(done){
		Q.all([
			getRenderer('build/test/templates'),
			getPartials('build/test/templates')
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({subject: "World"});

			assert.equal(result, "
Hello World
");
			done();
		},done).catch(done);
	});

	it("build.renderer build.templates build.helpers",function(done){

		var options = {
			html: { templates: path.join(__dirname,"test","templates_with_helpers") },
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var data = {subject: "World", message: "hello"};
		var getCurrent = function(){
			return data;
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, {}, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({
				subject: "World",
				src: "./index.js",
				type: "",
				line: "100"
			});

			assert.equal(result, "
HELLO World
\n");
			done();
		},done).catch(done);

	});

	it("Does ignoreTemplateRender",function(done){
		var options = {
			html: {templates: path.join(__dirname,"test","render_body_option")},
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var data = {message: "this isnt doing anything"};
		var getCurrent = function(){
			return data;
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, {}, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({body: "{{message}} stuff"});

			assert.equal(result, "
{{message}} stuff
\n
static
");
			done();
		},done).catch(done);

	});

	it("builds the static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				dependencies: {
					"can-component": "3.0.0-pre.9"
				}
			}
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "bundles","bit-docs-site","static.js"));
		}).then(function(res){
			assert.ok(/can-component/.test(res), "got static.js with component");
		});
	});

	it("copy absolute staticDist folders to static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				dependencies: {
					"can-component": "3.0.0-pre.9"
				},
				staticDist: [
					path.join(__dirname, '..', 'test-static-dist')
				]
			},
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "test.css"));
		}).then(function(res){
			assert.ok(/#TestID/.test(res), "got static.js with component");
		});
	});

	it("copy relative staticDist folders to static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				dependencies: {
					"can-component": "3.0.0-pre.9"
				},
				staticDist: [
					'./test-static-dist'
				]
			},
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "test.css"));
		}).then(function(res){
			assert.ok(/#TestID/.test(res), "got static.js with component");
		});
	});

	it("makes linked content",function(done){
		var options = {
			html: { templates: path.join(__dirname,"test","escaped") },
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var docObject = {
			src: "./index.js",
			type: "",
			line: "100",
			description: "This is [something]"
		};
		var getCurrent = function(){
			return docObject;
		};
		var docMap = {
			"index": docObject,
			something: {name: "something", title: "<something/>"}
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, docMap, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer(docObject);
			assert.equal(result, "
This is <something/>
\n\n");
			done();
		},done).catch(done);
	});

});
<commit_msg>Cleanup tests<commit_after>require("./make_default_helpers_test");

var getRenderer = require('./get_renderer');
var getPartials = require('./get_partials');
var build = require("./build");
var assert = require('assert');
var Q = require('q');
var path = require('path');
var rmdir = require('rimraf');
var fs = require('fs');
var read = Q.denodeify(fs.readFile);

describe("documentjs/lib/generators/html/build",function(){

	beforeEach(function(done){
		rmdir(path.join(__dirname,"..","site","static"), function(e){
			rmdir(path.join(__dirname,"..","site","templates"), done);
		});
	});

	it("get_renderer and get_partial work",function(done){
		Q.all([
			getRenderer('build/test/templates'),
			getPartials('build/test/templates')
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({subject: "World"});

			assert.equal(result, "
Hello World
");
			done();
		},done).catch(done);
	});

	it("build.renderer build.templates build.helpers",function(done){

		var options = {
			html: { templates: path.join(__dirname,"test","templates_with_helpers") },
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var data = {subject: "World", message: "hello"};
		var getCurrent = function(){
			return data;
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, {}, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({
				subject: "World",
				src: "./index.js",
				type: "",
				line: "100"
			});

			assert.equal(result, "
HELLO World
\n");
			done();
		},done).catch(done);

	});

	it("Does ignoreTemplateRender",function(done){
		var options = {
			html: {templates: path.join(__dirname,"test","render_body_option")},
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var data = {message: "this isnt doing anything"};
		var getCurrent = function(){
			return data;
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, {}, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer({body: "{{message}} stuff"});

			assert.equal(result, "
{{message}} stuff
\n
static
");
			done();
		},done).catch(done);

	});

	it("builds the static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				dependencies: {
					"can-component": "3.0.0-pre.9"
				}
			}
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "bundles","bit-docs-site","static.js"));
		}).then(function(res){
			assert.ok(/can-component/.test(res), "got static.js with component");
		});
	});

	it("copy absolute staticDist folders to static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				staticDist: [
					path.join(__dirname, '..', 'test-static-dist')
				]
			},
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "test.css"));
		}).then(function(res){
			assert.ok(/#TestID/.test(res), "got test.css file");
		});
	});

	it("copy relative staticDist folders to static dist", function(){
		this.timeout(120000);
		return build.staticDist({
			forceBuild: true,
			html: {
				staticDist: [
					'./test-static-dist'
				]
			},
		}).then(function(result){
			return read(path.join(__dirname, "..", result.distFolder, "test.css"));
		}).then(function(res){
			assert.ok(/#TestID/.test(res), "got test.css file");
		});
	});

	it("makes linked content",function(done){
		var options = {
			html: { templates: path.join(__dirname,"test","escaped") },
			dest: "XXXXYYYZZZ",
			forceBuild: true,
			pageConfig: {
				project: {
					source: "http://test.com"
				}
			}
		};
		buildTemplatesPromise = build.templates(options);

		var docObject = {
			src: "./index.js",
			type: "",
			line: "100",
			description: "This is [something]"
		};
		var getCurrent = function(){
			return docObject;
		};
		var docMap = {
			"index": docObject,
			something: {name: "something", title: "<something/>"}
		};

		Q.all([
			build.renderer(buildTemplatesPromise, options),
			build.helpers(buildTemplatesPromise, docMap, options, getCurrent)
		]).then(function(results){

			var renderer = results[0];

			var result = renderer(docObject);
			assert.equal(result, "
This is <something/>
\n\n");
			done();
		},done).catch(done);
	});

});
<|endoftext|>


<commit_before>/*
 * jQuery File Upload Plugin JS Example 8.8.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */

'use strict';

let dominator = {

  init: function(DOMelement) {
    this.el = DOMelement;
    this.files = new Map();
  },

  setType: (file_id, type) => {
    if(dominator.files.has(file_id)) {
      dominator.files.get(file_id).type = type;
    }
  },

  add: (e, data) => {
    let element = $('select#' + data.files[0].name.split('.')[0]);
    if(!dominator.files.has(element[0].id)) {
      dominator.files.set(element[0].id,
        {
          type: ''
        }
      );
      element.on('change', (e) => {
        dominator.setType(element[0].id, e.currentTarget.value);
      });
    } else {
      data.abort(); // TODO make it abort add
    }
  },

}

$(function () {
    'use strict';

  dominator.init($('#fileupload')); // Initialize the dominator

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        //url: 'server/php/'
      uploadTemplate: dominator.uploadTemplate
    }).on('fileuploadadded', dominator.add)
    .on('fileuploadsend', function(e, data) {
      data.data.set('file_type',
        dominator.files.get(data.data.get('file').name.split('.')[0]).type);
    })
    .on('fileuploadcompleted', function(e, data) {
      $('#fileupload_control .process').on('click', e => {
        console.log(e);
        console.log(data);
        $.get('/process', {f1: '1', f2: '2'});
      });

      $('#fileupload_control .process').removeAttr('disabled');
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );

    // Load existing files:
/*    $('#fileupload').addClass('fileupload-processing');*/
    //$.ajax({
        //// Uncomment the following to send cross-domain cookies:
        ////xhrFields: {withCredentials: true},
        ////url: $('#fileupload').fileupload('option', 'url'),
        //url: '/upload/view/',
        //dataType: 'json',
        //context: $('#fileupload')[0]
    //}).always(function () {
        //$(this).removeClass('fileupload-processing');
    //}).done(function (result) {
        //$(this).fileupload('option', 'done')
            //.call(this, null, {result: result});
    //});

});
<commit_msg>UPDATE bound events to call apropriate api endpoint for process<commit_after>/*
 * jQuery File Upload Plugin JS Example 8.8.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */

'use strict';

let dominator = {

  init: function(DOMelement) {
    this.el = DOMelement;
    this.files = new Map();
  },

  setType: (file_id, type) => {
    if(dominator.files.has(file_id)) {
      dominator.files.get(file_id).type = type;
    }
  },

  add: (e, data) => {
    let element = $('select#' + data.files[0].name.split('.')[0]);
    if(!dominator.files.has(element[0].id)) {
      dominator.files.set(element[0].id,
        {
          type: ''
        }
      );
      element.on('change', (e) => {
        dominator.setType(element[0].id, e.currentTarget.value);
      });
    } else {
      data.abort(); // TODO make it abort add
    }
  },

}

$(function () {
    'use strict';

  dominator.init($('#fileupload')); // Initialize the dominator

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        //url: 'server/php/'
      uploadTemplate: dominator.uploadTemplate
    }).on('fileuploadadded', dominator.add)
    .on('fileuploadsend', function(e, data) {
      data.data.set('file_type',
        dominator.files.get(data.data.get('file').name.split('.')[0]).type);
    })
    .on('fileuploadcompleted', function(e, data) {
      $('#fileupload_control .process').on('click', e => {
        console.log(data.result);
        let key = undefined;
        let file = data.result.files[0];
/*        if(file.name.split('_').length > 1) {*/
          //key = file.name.split('_')[1].split('.')[0];
        //} else if(file.name.split('_').length = 1) {
          //key = file.name.split('_')[0].split('.')[0];
        //}
        //let o = dominator.files.forEach(function(f) {
          //if(!f.hasOwnProperty('resource_id')
          //&& (dominator.files.has(key))) {
            //dominator.files.get(key).resource_id = .resource_id
          //}
        /*});*/
        $.get('/process/' + file.resource_id);
      });

      $('#fileupload_control .process').removeAttr('disabled');
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );

    // Load existing files:
/*    $('#fileupload').addClass('fileupload-processing');*/
    //$.ajax({
        //// Uncomment the following to send cross-domain cookies:
        ////xhrFields: {withCredentials: true},
        ////url: $('#fileupload').fileupload('option', 'url'),
        //url: '/upload/view/',
        //dataType: 'json',
        //context: $('#fileupload')[0]
    //}).always(function () {
        //$(this).removeClass('fileupload-processing');
    //}).done(function (result) {
        //$(this).fileupload('option', 'done')
            //.call(this, null, {result: result});
    //});

});
<|endoftext|>


<commit_before>Ui.Element.extend('Ui.CanvasElement',
/**@lends Ui.CanvasElement#*/
{
	context: undefined,

	/**
	 * @constructs
	 * @class The base class for all Canvas drawing
	 * @extends Ui.Element
	 */
	constructor: function(config){
	},

	/**
	 * Call this method when the canvas need to be redraw
	 */
	update: function() {
		this.context.clearRect(0, 0, this.getLayoutWidth(), this.getLayoutHeight());
		this.context.save();
		this.updateCanvas(this.context);
		this.context.restore();
	},

	/**
	 * Override this method to provide the Canvas rendering
	 */
	updateCanvas: function(context) {
	},

	roundRect: function(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft, antiClockwise) {
		if((antiClockwise != undefined) && antiClockwise) {
			this.roundRectAntiClockwise(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft);
			return;
		}
		if(radiusTopLeft > 0) {
			this.context.moveTo(x+0, y+radiusTopLeft);
			this.context.quadraticCurveTo(x+0,y+0,x+radiusTopLeft,y+0);
		}
		else
			this.context.moveTo(x+0,y+0);
		if(radiusTopRight > 0) {
			this.context.lineTo(x+(width-radiusTopRight),y+0);
			this.context.quadraticCurveTo(x+width,y+0,x+width,y+radiusTopRight);
		}
		else
			this.context.lineTo(x+width,y+0);
		if(radiusBottomRight > 0) {
			this.context.lineTo(x+width,y+(height-radiusBottomRight));
			this.context.quadraticCurveTo(x+width,y+height,x+(width-radiusBottomRight),y+height);
		}
		else
			this.context.lineTo(x+width,y+height);
		if(radiusBottomLeft > 0) {
			this.context.lineTo(x+radiusBottomLeft,y+height);
			this.context.quadraticCurveTo(x+0,y+height,x+0,y+(height-radiusBottomLeft));
		}
		else
			this.context.lineTo(x+0,y+height);
	},

	roundRectAntiClockwise: function(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft) {
		if(radiusTopLeft > 0) {
			this.context.moveTo(x+radiusTopLeft, y+0);
			this.context.quadraticCurveTo(x+0,y+0,x+0,y+radiusTopLeft);
		}
		else
			this.context.moveTo(x+0,y+0);
		if(radiusBottomLeft > 0) {
			this.context.lineTo(x+0,y+(height-radiusBottomLeft));
			this.context.quadraticCurveTo(x+0,y+height,x+radiusBottomLeft,y+height);
		}
		else
			this.context.lineTo(x+0,y+height);
		if(radiusBottomRight > 0) {
			this.context.lineTo(x+(width-radiusBottomRight),y+height);
			this.context.quadraticCurveTo(x+width,y+height,x+width,y+(height-radiusBottomRight));
		}
		else
			this.context.lineTo(x+width,y+height);
		if(radiusTopRight > 0) {
			this.context.lineTo(x+width,y+radiusTopRight);
			this.context.quadraticCurveTo(x+width,y+0,x+(width-radiusTopRight),y+0);
		}
		else
			this.context.lineTo(x+width,y+0);
	},

	svgPath: function(path) {
		var ctx = this.context;
		var x = 0;
		var y = 0;

		ctx.beginPath();

		var parser = new Ui.SvgParser({ path: path });
		parser.next();

		while(!parser.isEnd()) {
			var cmd = parser.getCmd();
			if(parser.isCmd())
				parser.next();

			if(cmd == 'm') {
				parser.setCmd('l');
				x += parser.getCurrent(); parser.next();
				y += parser.getCurrent(); parser.next();
				ctx.moveTo(x, y);
			}
			else if(cmd == 'M') {
				parser.setCmd('L');
				x = parser.getCurrent(); parser.next();
				y = parser.getCurrent(); parser.next();
				ctx.moveTo(x, y);
			}
			else if(cmd == 'l') {
				x += parser.getCurrent(); parser.next();
				y += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'L') {
				x = parser.getCurrent(); parser.next();
				y = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'v') {
				y += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'V') {
				y = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'h') {
				x += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'H') {
				x = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'c') {
				var x1 = x + parser.getCurrent(); parser.next();
				var y1 = y + parser.getCurrent(); parser.next();
				var x2 = x + parser.getCurrent(); parser.next();
				var y2 = y + parser.getCurrent(); parser.next();
				var x3 = x + parser.getCurrent(); parser.next();
				var y3 = y + parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 'C') {
				var x1 = parser.getCurrent(); parser.next();
				var y1 = parser.getCurrent(); parser.next();
				var x2 = parser.getCurrent(); parser.next();
				var y2 = parser.getCurrent(); parser.next();
				var x3 = parser.getCurrent(); parser.next();
				var y3 = parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 'q') {
				var x1 = x + parser.getCurrent(); parser.next();
				var y1 = y + parser.getCurrent(); parser.next();
				var x2 = x + parser.getCurrent(); parser.next();
				var y2 = y + parser.getCurrent(); parser.next();
				ctx.quadraticCurveTo(x1, y1, x2, y2);
				x = x2; y = y2;
			}
			else if(cmd == 'Q') {
				var x1 = parser.getCurrent(); parser.next();
				var y1 = parser.getCurrent(); parser.next();
				var x2 = parser.getCurrent(); parser.next();
				var y2 = parser.getCurrent(); parser.next();
				ctx.quadraticCurveTo(x1, y1, x2, y2);
				x = x2; y = y2;
			}
			else if(cmd == 'z') {
			}
			else {
				console.log('Invalid SVG path cmd: '+cmd+' ('+path+')');
				throw('Invalid SVG path');
			}
		}
		ctx.closePath();
	}
},
/**@lends Ui.CanvasElement#*/
{
	renderDrawing: function() {
		var canvas = document.createElement('canvas');
		if('G_vmlCanvasManager' in window)
			canvas = G_vmlCanvasManager.initElement(canvas);
		this.context = canvas.getContext('2d');
		this.canvas = canvas;
		return canvas;
	},

	arrangeCore: function(width, height) {
		this.getDrawing().setAttribute('width', width, null);
		this.getDrawing().setAttribute('height', height, null);
		this.update();
	},

	drawCore: function() {
		this.update();
	}
});

<commit_msg>add S and s command in the SVG path<commit_after>Ui.Element.extend('Ui.CanvasElement',
/**@lends Ui.CanvasElement#*/
{
	context: undefined,

	/**
	 * @constructs
	 * @class The base class for all Canvas drawing
	 * @extends Ui.Element
	 */
	constructor: function(config){
	},

	/**
	 * Call this method when the canvas need to be redraw
	 */
	update: function() {
		this.context.clearRect(0, 0, this.getLayoutWidth(), this.getLayoutHeight());
		this.context.save();
		this.updateCanvas(this.context);
		this.context.restore();
	},

	/**
	 * Override this method to provide the Canvas rendering
	 */
	updateCanvas: function(context) {
	},

	roundRect: function(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft, antiClockwise) {
		if((antiClockwise != undefined) && antiClockwise) {
			this.roundRectAntiClockwise(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft);
			return;
		}
		if(radiusTopLeft > 0) {
			this.context.moveTo(x+0, y+radiusTopLeft);
			this.context.quadraticCurveTo(x+0,y+0,x+radiusTopLeft,y+0);
		}
		else
			this.context.moveTo(x+0,y+0);
		if(radiusTopRight > 0) {
			this.context.lineTo(x+(width-radiusTopRight),y+0);
			this.context.quadraticCurveTo(x+width,y+0,x+width,y+radiusTopRight);
		}
		else
			this.context.lineTo(x+width,y+0);
		if(radiusBottomRight > 0) {
			this.context.lineTo(x+width,y+(height-radiusBottomRight));
			this.context.quadraticCurveTo(x+width,y+height,x+(width-radiusBottomRight),y+height);
		}
		else
			this.context.lineTo(x+width,y+height);
		if(radiusBottomLeft > 0) {
			this.context.lineTo(x+radiusBottomLeft,y+height);
			this.context.quadraticCurveTo(x+0,y+height,x+0,y+(height-radiusBottomLeft));
		}
		else
			this.context.lineTo(x+0,y+height);
	},

	roundRectAntiClockwise: function(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft) {
		if(radiusTopLeft > 0) {
			this.context.moveTo(x+radiusTopLeft, y+0);
			this.context.quadraticCurveTo(x+0,y+0,x+0,y+radiusTopLeft);
		}
		else
			this.context.moveTo(x+0,y+0);
		if(radiusBottomLeft > 0) {
			this.context.lineTo(x+0,y+(height-radiusBottomLeft));
			this.context.quadraticCurveTo(x+0,y+height,x+radiusBottomLeft,y+height);
		}
		else
			this.context.lineTo(x+0,y+height);
		if(radiusBottomRight > 0) {
			this.context.lineTo(x+(width-radiusBottomRight),y+height);
			this.context.quadraticCurveTo(x+width,y+height,x+width,y+(height-radiusBottomRight));
		}
		else
			this.context.lineTo(x+width,y+height);
		if(radiusTopRight > 0) {
			this.context.lineTo(x+width,y+radiusTopRight);
			this.context.quadraticCurveTo(x+width,y+0,x+(width-radiusTopRight),y+0);
		}
		else
			this.context.lineTo(x+width,y+0);
	},

	svgPath: function(path) {
		var ctx = this.context;
		var x = 0;
		var y = 0;

		ctx.beginPath();

		var parser = new Ui.SvgParser({ path: path });
		parser.next();

		while(!parser.isEnd()) {
			var cmd = parser.getCmd();
			if(parser.isCmd())
				parser.next();

			if(cmd == 'm') {
				parser.setCmd('l');
				x += parser.getCurrent(); parser.next();
				y += parser.getCurrent(); parser.next();
				ctx.moveTo(x, y);
			}
			else if(cmd == 'M') {
				parser.setCmd('L');
				x = parser.getCurrent(); parser.next();
				y = parser.getCurrent(); parser.next();
				ctx.moveTo(x, y);
			}
			else if(cmd == 'l') {
				x += parser.getCurrent(); parser.next();
				y += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'L') {
				x = parser.getCurrent(); parser.next();
				y = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'v') {
				y += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'V') {
				y = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'h') {
				x += parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'H') {
				x = parser.getCurrent(); parser.next();
				ctx.lineTo(x, y);
			}
			else if(cmd == 'c') {
				var x1 = x + parser.getCurrent(); parser.next();
				var y1 = y + parser.getCurrent(); parser.next();
				var x2 = x + parser.getCurrent(); parser.next();
				var y2 = y + parser.getCurrent(); parser.next();
				var x3 = x + parser.getCurrent(); parser.next();
				var y3 = y + parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 'C') {
				var x1 = parser.getCurrent(); parser.next();
				var y1 = parser.getCurrent(); parser.next();
				var x2 = parser.getCurrent(); parser.next();
				var y2 = parser.getCurrent(); parser.next();
				var x3 = parser.getCurrent(); parser.next();
				var y3 = parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 's') {
				var x1 = x + parser.getCurrent(); parser.next();
				var y1 = y + parser.getCurrent(); parser.next();
				var x2 = x1;
				var y2 = y1;
				var x3 = x + parser.getCurrent(); parser.next();
				var y3 = y + parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				ctx.lineTo(x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 'S') {
				var x1 = parser.getCurrent(); parser.next();
				var y1 = parser.getCurrent(); parser.next();
				var x2 = x1;
				var y2 = y1;
				var x3 = parser.getCurrent(); parser.next();
				var y3 = parser.getCurrent(); parser.next();
				ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
				x = x3; y = y3;
			}
			else if(cmd == 'q') {
				var x1 = x + parser.getCurrent(); parser.next();
				var y1 = y + parser.getCurrent(); parser.next();
				var x2 = x + parser.getCurrent(); parser.next();
				var y2 = y + parser.getCurrent(); parser.next();
				ctx.quadraticCurveTo(x1, y1, x2, y2);
				x = x2; y = y2;
			}
			else if(cmd == 'Q') {
				var x1 = parser.getCurrent(); parser.next();
				var y1 = parser.getCurrent(); parser.next();
				var x2 = parser.getCurrent(); parser.next();
				var y2 = parser.getCurrent(); parser.next();
				ctx.quadraticCurveTo(x1, y1, x2, y2);
				x = x2; y = y2;
			}
			else if(cmd == 'z') {
			}
			else {
				console.log('Invalid SVG path cmd: '+cmd+' ('+path+')');
				throw('Invalid SVG path');
			}
		}
		ctx.closePath();
	}
},
/**@lends Ui.CanvasElement#*/
{
	renderDrawing: function() {
		var canvas = document.createElement('canvas');
		if('G_vmlCanvasManager' in window)
			canvas = G_vmlCanvasManager.initElement(canvas);
		this.context = canvas.getContext('2d');
		this.canvas = canvas;
		return canvas;
	},

	arrangeCore: function(width, height) {
		this.getDrawing().setAttribute('width', width, null);
		this.getDrawing().setAttribute('height', height, null);
		this.update();
	},

	drawCore: function() {
		this.update();
	}
});

<|endoftext|>


<commit_before>#!/usr/bin/env node

// add bower components to packaging
// naught for stop/start

var _ = require("lodash"),
    program = require("commander"),
    path = require("path"),
    gulp = require("./lib/gulp"),
    runSequence = require("run-sequence").use(gulp),
    gutil = require("gulp-util"),
    pjson = require("./package.json"),
    help = require("gulp-help");

help(gulp, {
    description: "This task is what makes the 'tasks' command work"
});

var gulpRunner = function(err, runCmd) {
    if (err) {
        gutil.log(err);
        return;
    }

    gulp.on("task_err", function(e) {
        gutil.log(e.err);
        process.exit(1);
    });

    gulp.on("task_end", function(name) {
        gutil.log("Task ended " + name);
    });

    runSequence.apply(undefined, runCmd);
};

program
    .version(pjson.version)
    .usage('[command] <args>');

program.command("deploy")
    .description("Deploys a packaged version of an application")
    .option("-d, --destination <path>", "Deploy destination directory")
    .action(function(opts) {
        require('./lib/deploy')(opts, gulpRunner);
    });

program.command("launch")
    .description("Launches the newest deployed app")
    .option("-d, --destination <path>", "Deploy destination directory")
    .option("-w, --worker-count <number>", "Number of workers to launch")
    .action(function(cmd, opts) {
        require('./lib/launch')(cmd, opts, gulpRunner);
    });

program.command("modules <cmd>")
    .description("Manages dependencies")
    .option("-p, --package <package>", "The specific package")
    .action(function(cmd, opts) {
        require('./lib/modules')(cmd, opts, gulpRunner);
    })
    .on('--help', function() {
        console.log('  Sub-commands:');
        console.log();
        console.log('    package - Look for unpackaged modules and create them in modules directory');
        console.log('    explode - Look for missing modules in node_modules and install them');
        console.log();
    });

program.command("package")
    .description("Package the application or library")
    .option("-p, --path <path>", "The base path for packaging")
    .option("--patch", "When packaging a library, bump patch version (default)")
    .option("--minor", "When packaging a library, bump minor version")
    .option("--major", "When packaging a library, bump major version")
    .option("--no-bump", "When packaging a library, don't bump version")
    .option("--dependencies-only", "Only package dependencies", false)
    .action(function(opts) {
        require('./lib/package')(opts, gulpRunner);
    });

program.command("init")
    .description("Create an app scaffold")
    .action(function(dest) {
        require('./lib/init')(dest, gulpRunner);
    });

program.command("build [target]")
    .description("Build the application")
    .option("-l, --list", "List available build targets")
    .option("-s, --skip-modules", "Skip extracting dependent modules")
    .option("-c, --clean-modules", "Clean node_modules before exploding")
    .action(function(cmd, opt) {
        require('./lib/app')(true, cmd, opt, gulpRunner);
    });

program.command("app <task> [otherTasks...]")
    .description("Run ad-hoc gulp tasks defined in your project (use \"ss tasks\" to see list)")
    .option("--debug-brk", "Start server and wait in debug mode (if supported by task)")
    .action(function(cmd, otherTasks, opt) {
        var cmds = [[cmd]].concat(otherTasks.map(function(t) {
            return [t];
        }));
        require('./lib/app')(false, cmds, opt, gulpRunner);
    });

program.command("tasks")
    .description("List help on available tasks")
    .action(function(cmd, opt) {
        require('./lib/tasks')(opt, gulpRunner);
    });

program.command("server <task>")
    .description("Manage development server")
    .option("-l, --list", "List available commands")
    .action(function(cmd, opt) {
        require('./lib/server')(cmd, opt, gulpRunner);
    });

program.parse(process.argv);<commit_msg>Internal issue in running of gulp commands.<commit_after>#!/usr/bin/env node

// add bower components to packaging
// naught for stop/start

var _ = require("lodash"),
    program = require("commander"),
    path = require("path"),
    gulp = require("./lib/gulp"),
    runSequence = require("run-sequence").use(gulp),
    gutil = require("gulp-util"),
    pjson = require("./package.json"),
    help = require("gulp-help");

help(gulp, {
    description: "This task is what makes the 'tasks' command work"
});

var gulpRunner = function(err, runCmd) {
    if (err) {
        gutil.log(err);
        return;
    }

    gulp.on("task_err", function(e) {
        gutil.log(e.err);
        process.exit(1);
    });

    gulp.on("task_end", function(name) {
        gutil.log("Task ended " + name);
    });

    if (typeof runCmd === "array") {
        runSequence.apply(undefined, runCmd);
    } else {
        runSequence(runCmd);
    }
};

program
    .version(pjson.version)
    .usage('[command] <args>');

program.command("deploy")
    .description("Deploys a packaged version of an application")
    .option("-d, --destination <path>", "Deploy destination directory")
    .action(function(opts) {
        require('./lib/deploy')(opts, gulpRunner);
    });

program.command("launch")
    .description("Launches the newest deployed app")
    .option("-d, --destination <path>", "Deploy destination directory")
    .option("-w, --worker-count <number>", "Number of workers to launch")
    .action(function(cmd, opts) {
        require('./lib/launch')(cmd, opts, gulpRunner);
    });

program.command("modules <cmd>")
    .description("Manages dependencies")
    .option("-p, --package <package>", "The specific package")
    .action(function(cmd, opts) {
        require('./lib/modules')(cmd, opts, gulpRunner);
    })
    .on('--help', function() {
        console.log('  Sub-commands:');
        console.log();
        console.log('    package - Look for unpackaged modules and create them in modules directory');
        console.log('    explode - Look for missing modules in node_modules and install them');
        console.log();
    });

program.command("package")
    .description("Package the application or library")
    .option("-p, --path <path>", "The base path for packaging")
    .option("--patch", "When packaging a library, bump patch version (default)")
    .option("--minor", "When packaging a library, bump minor version")
    .option("--major", "When packaging a library, bump major version")
    .option("--no-bump", "When packaging a library, don't bump version")
    .option("--dependencies-only", "Only package dependencies", false)
    .action(function(opts) {
        require('./lib/package')(opts, gulpRunner);
    });

program.command("init")
    .description("Create an app scaffold")
    .action(function(dest) {
        require('./lib/init')(dest, gulpRunner);
    });

program.command("build [target]")
    .description("Build the application")
    .option("-l, --list", "List available build targets")
    .option("-s, --skip-modules", "Skip extracting dependent modules")
    .option("-c, --clean-modules", "Clean node_modules before exploding")
    .action(function(cmd, opt) {
        require('./lib/app')(true, cmd, opt, gulpRunner);
    });

program.command("app <task> [otherTasks...]")
    .description("Run ad-hoc gulp tasks defined in your project (use \"ss tasks\" to see list)")
    .option("--debug-brk", "Start server and wait in debug mode (if supported by task)")
    .action(function(cmd, otherTasks, opt) {
        var cmds = [[cmd]].concat(otherTasks.map(function(t) {
            return [t];
        }));
        require('./lib/app')(false, cmds, opt, gulpRunner);
    });

program.command("tasks")
    .description("List help on available tasks")
    .action(function(cmd, opt) {
        require('./lib/tasks')(opt, gulpRunner);
    });

program.command("server <task>")
    .description("Manage development server")
    .option("-l, --list", "List available commands")
    .action(function(cmd, opt) {
        require('./lib/server')(cmd, opt, gulpRunner);
    });

program.parse(process.argv);<|endoftext|>


<commit_before><commit_msg>Remove debugging message.<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Minor simplification."<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = {
    parserOptions: {
        ecmaVersion: 6,
    },

    env: {
        es6: true,
    },

    rules: {
        // Rules are divided into sections from http://eslint.org/docs/rules/

        // Possible errors
        'comma-dangle': ['error', 'always-multiline'],
        'no-cond-assign': 'error',
        'no-console': 'off',
        'no-constant-condition': ['error', {checkLoops: false}],
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-dupe-args': 'error',
        'no-dupe-keys': 'error',
        'no-duplicate-case': 'error',
        'no-empty-character-class': 'error',
        'no-empty': 'error',
        'no-ex-assign': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-parens': 'off',
        'no-extra-semi': 'error',
        'no-func-assign': 'error',
        'no-inner-declarations': 'error',
        'no-invalid-regexp': 'error',
        'no-irregular-whitespace': 'error',
        'no-negated-in-lhs': 'error',
        'no-obj-calls': 'error',
        'no-prototype-builtins': 'error',
        'no-regex-spaces': 'error',
        'no-sparse-arrays': 'error',
        'no-unreachable': 'error',
        'use-isnan': 'error',
        'no-unsafe-finally': 'error',
        'valid-jsdoc': 'off', // TODO enable?
        'valid-typeof': 'error',
        'no-unexpected-multiline': 'error',

        // Best practices
        'accessor-pairs': 'error',
        'array-callback-return': 'error',
        'block-scoped-var': 'off',
        complexity: ['warn', 10],
        'consistent-return': 'error',
        curly: 'error',
        'default-case': 'error',
        'dot-notation': 'error',
        'dot-location': ['error', 'property'],
        eqeqeq: ['error', 'smart'],
        'guard-for-in': 'off',
        'no-alert': 'error',
        'no-caller': 'error',
        'no-case-declarations': 'error',
        'no-div-regex': 'off',
        'no-else-return': 'error',
        'no-empty-function': 'error',
        'no-empty-pattern': 'error',
        'no-eq-null': 'off',
        'no-eval': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-extra-label': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'error',
        'no-implicit-coercion': ['error', {boolean: false, number: true, string: false}],
        'no-implicit-globals': 'error',
        'no-implied-eval': 'error',
        'no-invalid-this': 'off',
        'no-iterator': 'error',
        'no-labels': ['error', {allowLoop: true, allowSwitch: true}],
        'no-lone-blocks': 'off',
        'no-loop-func': 'off',
        'no-magic-numbers': 'off',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-native-reassign': 'error',
        'no-new-func': 'error',
        'no-new-wrappers': 'error',
        'no-new': 'error',
        'no-octal-escape': 'error',
        'no-octal': 'error',
        'no-param-reassign': 'off',
        'no-process-env': 'off',
        'no-proto': 'error',
        'no-redeclare': 'error',
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-self-assign': 'error',
        'no-self-compare': 'error',
        'no-sequences': 'error',
        'no-throw-literal': 'error',
        'no-unmodified-loop-condition': 'error',
        'no-unused-expressions': 'error',
        'no-unused-labels': 'error',
        'no-useless-call': 'error',
        'no-useless-concat': 'error',
        'no-useless-escape': 'error',
        'no-void': 'error',
        'no-warning-comments': 'off',
        'no-with': 'error',
        radix: 'off',
        'vars-on-top': 'off',
        'wrap-iife': ['error', 'inside'],
        yoda: 'error',

        // Strict mode
        strict: ['error', 'global'], // 'global' in Node, 'function' in a browser

        // Variables
        'init-declarations': 'off',
        'no-catch-shadow': 'off',
        'no-delete-var': 'error',
        'no-label-var': 'error',
        'no-restricted-globals': ['error', 'arguments', 'event'],
        'no-shadow-restricted-names': 'error',
        'no-shadow': 'off',
        'no-undef-init': 'error',
        'no-undef': 'error',
        'no-undefined': 'off',
        'no-unused-vars': ['error', {args: 'all', argsIgnorePattern: '^__'}],
        'no-use-before-define': 'off',

        // Node.js
        'callback-return': 'off',
        'global-require': 'off',
        'handle-callback-err': 'error',
        'no-mixed-requires': 'off',
        'no-new-require': 'error',
        'no-path-concat': 'off',
        'no-process-exit': 'error',
        'no-restricted-imports': 'off',
        'no-restricted-modules': 'off',
        'no-sync': 'off', // in some projects this might be useful

        // Stylistic issues
        'array-bracket-spacing': ['error', 'never'],
        'block-spacing': ['error', 'never'],
        'brace-style': 'error',
        camelcase: 'off',
        'comma-spacing': 'error',
        'comma-style': 'error',
        'computed-property-spacing': ['error', 'never'],
        'consistent-this': 'off',
        'eol-last': 'error',
        'func-names': 'off',
        'func-style': 'off',
        'id-length': 'off',
        'id-match': 'off',
        'id-blacklist': ['error', 'arguments', 'event'],
        indent: 'off', // TODO try to enable it
        'jsx-quotes': 'off',
        'key-spacing': 'error',
        'keyword-spacing': 'error',
        // Re-enable when commented out lines & ESLint pragmas work; was:
        // [2, {beforeBlockComment: true, beforeLineComment: true, allowBlockStart: true}],
        'lines-around-comment': 'off',
        'linebreak-style': 'off',
        'max-depth': 'off',
        'max-len': ['error', 120, 4, {ignoreUrls: true}],
        'max-lines': 'off',
        'max-nested-callbacks': 'off',
        'max-params': 'off',
        'max-statements': 'off',
        'max-statements-per-line': ['error', {max: 1}],
        'multiline-ternary': 'off',
        'new-cap': 'off',
        'new-parens': 'error',
        'newline-after-var': 'off',
        'newline-before-return': 'off',
        'newline-per-chained-call': ['error', {ignoreChainWithDepth: 4}],
        'no-array-constructor': 'error',
        'no-bitwise': 'error',
        'no-continue': 'off',
        'no-inline-comments': 'off',
        'no-lonely-if': 'error',
        'no-mixed-operators': ['error', {groups: [['&&', '||']], allowSamePrecedence: true}],
        'no-mixed-spaces-and-tabs': 'error',
        'no-multiple-empty-lines': ['error', {max: 2, maxEOF: 1}],
        'no-nested-ternary': 'error',
        'no-negated-condition': 'error',
        'no-new-object': 'error',
        // Already handled via no-with; would be: ['error', 'WithStatement']:
        'no-plusplus': 'off',
        'no-restricted-syntax': 'off',
        'no-spaced-func': 'error',
        'no-tabs': 'error',
        'no-ternary': 'off',
        'no-trailing-spaces': 'error',
        'no-underscore-dangle': 'off',
        'no-unneeded-ternary': 'error',
        'no-whitespace-before-property': 'error',
        'object-curly-newline': 'off',
        'object-curly-spacing': ['error', 'never'],
        'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
        'one-var': ['error', {initialized: 'never'}],
        'one-var-declaration-per-line': 'off', // I don't use this declaration style
        'operator-assignment': 'error',
        'operator-linebreak': ['error', 'after'],
        'padded-blocks': 'off',
        'quote-props': ['error', 'as-needed'],
        quotes: ['error', 'single'],
        'require-jsdoc': 'off',
        'semi-spacing': 'error',
        semi: 'error',
        'sort-vars': 'off',
        'sort-imports': 'off', // It sorts by the member syntax, not by module names
        'space-before-blocks': 'error',
        'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
        'space-in-parens': ['error', 'never'],
        'space-infix-ops': 'error',
        'space-unary-ops': 'error',
        'spaced-comment': ['error', 'always', {exceptions: ['+', '-', '*', '/']}],
        'unicode-bom': ['error', 'never'],
        'wrap-regex': 'off',

        // ECMAScript 6
        'arrow-body-style': ['error', 'as-needed'],
        'arrow-parens': ['error', 'as-needed'],
        'arrow-spacing': 'error',
        'constructor-super': 'error',
        'generator-star-spacing': ['error', {before: true, after: false}],
        // Arrow returning a ternary is disallowed; wrapping in braces doesn't help.
        'no-class-assign': 'error',
        'no-confusing-arrow': 'off',
        'no-const-assign': 'error',
        'no-dupe-class-members': 'error',
        'no-duplicate-imports': 'error',
        'no-new-symbol': 'error',
        'no-this-before-super': 'error',
        'no-var': 'error',
        'no-useless-computed-key': 'error',
        'no-useless-constructor': 'error',
        'no-useless-rename': 'error',
        'object-shorthand': 'error',
        'prefer-arrow-callback': 'error',
        'prefer-const': 'error',
        'prefer-spread': 'error',
        'prefer-reflect': ['error', {exceptions: ['delete']}],
        'prefer-rest-params': 'error',
        'prefer-template': 'error',
        'rest-spread-spacing': ['error', 'never'],
        'require-yield': 'off',
        'template-curly-spacing': ['error', 'always'],
        'yield-star-spacing': ['error', 'after'],
    },
};
<commit_msg>Enable the indent rule<commit_after>'use strict';

module.exports = {
    parserOptions: {
        ecmaVersion: 6,
    },

    env: {
        es6: true,
    },

    rules: {
        // Rules are divided into sections from http://eslint.org/docs/rules/

        // Possible errors
        'comma-dangle': ['error', 'always-multiline'],
        'no-cond-assign': 'error',
        'no-console': 'off',
        'no-constant-condition': ['error', {checkLoops: false}],
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-dupe-args': 'error',
        'no-dupe-keys': 'error',
        'no-duplicate-case': 'error',
        'no-empty-character-class': 'error',
        'no-empty': 'error',
        'no-ex-assign': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-parens': 'off',
        'no-extra-semi': 'error',
        'no-func-assign': 'error',
        'no-inner-declarations': 'error',
        'no-invalid-regexp': 'error',
        'no-irregular-whitespace': 'error',
        'no-negated-in-lhs': 'error',
        'no-obj-calls': 'error',
        'no-prototype-builtins': 'error',
        'no-regex-spaces': 'error',
        'no-sparse-arrays': 'error',
        'no-unreachable': 'error',
        'use-isnan': 'error',
        'no-unsafe-finally': 'error',
        'valid-jsdoc': 'off', // TODO enable?
        'valid-typeof': 'error',
        'no-unexpected-multiline': 'error',

        // Best practices
        'accessor-pairs': 'error',
        'array-callback-return': 'error',
        'block-scoped-var': 'off',
        complexity: ['warn', 10],
        'consistent-return': 'error',
        curly: 'error',
        'default-case': 'error',
        'dot-notation': 'error',
        'dot-location': ['error', 'property'],
        eqeqeq: ['error', 'smart'],
        'guard-for-in': 'off',
        'no-alert': 'error',
        'no-caller': 'error',
        'no-case-declarations': 'error',
        'no-div-regex': 'off',
        'no-else-return': 'error',
        'no-empty-function': 'error',
        'no-empty-pattern': 'error',
        'no-eq-null': 'off',
        'no-eval': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-extra-label': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'error',
        'no-implicit-coercion': ['error', {boolean: false, number: true, string: false}],
        'no-implicit-globals': 'error',
        'no-implied-eval': 'error',
        'no-invalid-this': 'off',
        'no-iterator': 'error',
        'no-labels': ['error', {allowLoop: true, allowSwitch: true}],
        'no-lone-blocks': 'off',
        'no-loop-func': 'off',
        'no-magic-numbers': 'off',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-native-reassign': 'error',
        'no-new-func': 'error',
        'no-new-wrappers': 'error',
        'no-new': 'error',
        'no-octal-escape': 'error',
        'no-octal': 'error',
        'no-param-reassign': 'off',
        'no-process-env': 'off',
        'no-proto': 'error',
        'no-redeclare': 'error',
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-self-assign': 'error',
        'no-self-compare': 'error',
        'no-sequences': 'error',
        'no-throw-literal': 'error',
        'no-unmodified-loop-condition': 'error',
        'no-unused-expressions': 'error',
        'no-unused-labels': 'error',
        'no-useless-call': 'error',
        'no-useless-concat': 'error',
        'no-useless-escape': 'error',
        'no-void': 'error',
        'no-warning-comments': 'off',
        'no-with': 'error',
        radix: 'off',
        'vars-on-top': 'off',
        'wrap-iife': ['error', 'inside'],
        yoda: 'error',

        // Strict mode
        strict: ['error', 'global'], // 'global' in Node, 'function' in a browser

        // Variables
        'init-declarations': 'off',
        'no-catch-shadow': 'off',
        'no-delete-var': 'error',
        'no-label-var': 'error',
        'no-restricted-globals': ['error', 'arguments', 'event'],
        'no-shadow-restricted-names': 'error',
        'no-shadow': 'off',
        'no-undef-init': 'error',
        'no-undef': 'error',
        'no-undefined': 'off',
        'no-unused-vars': ['error', {args: 'all', argsIgnorePattern: '^__'}],
        'no-use-before-define': 'off',

        // Node.js
        'callback-return': 'off',
        'global-require': 'off',
        'handle-callback-err': 'error',
        'no-mixed-requires': 'off',
        'no-new-require': 'error',
        'no-path-concat': 'off',
        'no-process-exit': 'error',
        'no-restricted-imports': 'off',
        'no-restricted-modules': 'off',
        'no-sync': 'off', // in some projects this might be useful

        // Stylistic issues
        'array-bracket-spacing': ['error', 'never'],
        'block-spacing': ['error', 'never'],
        'brace-style': 'error',
        camelcase: 'off',
        'comma-spacing': 'error',
        'comma-style': 'error',
        'computed-property-spacing': ['error', 'never'],
        'consistent-this': 'off',
        'eol-last': 'error',
        'func-names': 'off',
        'func-style': 'off',
        'id-length': 'off',
        'id-match': 'off',
        'id-blacklist': ['error', 'arguments', 'event'],
        indent: ['error', 4, {SwitchCase: 1, MemberExpression: 1}],
        'jsx-quotes': 'off',
        'key-spacing': 'error',
        'keyword-spacing': 'error',
        // Re-enable when commented out lines & ESLint pragmas work; was:
        // [2, {beforeBlockComment: true, beforeLineComment: true, allowBlockStart: true}],
        'lines-around-comment': 'off',
        'linebreak-style': 'off',
        'max-depth': 'off',
        'max-len': ['error', 120, 4, {ignoreUrls: true}],
        'max-lines': 'off',
        'max-nested-callbacks': 'off',
        'max-params': 'off',
        'max-statements': 'off',
        'max-statements-per-line': ['error', {max: 1}],
        'multiline-ternary': 'off',
        'new-cap': 'off',
        'new-parens': 'error',
        'newline-after-var': 'off',
        'newline-before-return': 'off',
        'newline-per-chained-call': ['error', {ignoreChainWithDepth: 4}],
        'no-array-constructor': 'error',
        'no-bitwise': 'error',
        'no-continue': 'off',
        'no-inline-comments': 'off',
        'no-lonely-if': 'error',
        'no-mixed-operators': ['error', {groups: [['&&', '||']], allowSamePrecedence: true}],
        'no-mixed-spaces-and-tabs': 'error',
        'no-multiple-empty-lines': ['error', {max: 2, maxEOF: 1}],
        'no-nested-ternary': 'error',
        'no-negated-condition': 'error',
        'no-new-object': 'error',
        // Already handled via no-with; would be: ['error', 'WithStatement']:
        'no-plusplus': 'off',
        'no-restricted-syntax': 'off',
        'no-spaced-func': 'error',
        'no-tabs': 'error',
        'no-ternary': 'off',
        'no-trailing-spaces': 'error',
        'no-underscore-dangle': 'off',
        'no-unneeded-ternary': 'error',
        'no-whitespace-before-property': 'error',
        'object-curly-newline': 'off',
        'object-curly-spacing': ['error', 'never'],
        'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
        'one-var': ['error', {initialized: 'never'}],
        'one-var-declaration-per-line': 'off', // I don't use this declaration style
        'operator-assignment': 'error',
        'operator-linebreak': ['error', 'after'],
        'padded-blocks': 'off',
        'quote-props': ['error', 'as-needed'],
        quotes: ['error', 'single'],
        'require-jsdoc': 'off',
        'semi-spacing': 'error',
        semi: 'error',
        'sort-vars': 'off',
        'sort-imports': 'off', // It sorts by the member syntax, not by module names
        'space-before-blocks': 'error',
        'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
        'space-in-parens': ['error', 'never'],
        'space-infix-ops': 'error',
        'space-unary-ops': 'error',
        'spaced-comment': ['error', 'always', {exceptions: ['+', '-', '*', '/']}],
        'unicode-bom': ['error', 'never'],
        'wrap-regex': 'off',

        // ECMAScript 6
        'arrow-body-style': ['error', 'as-needed'],
        'arrow-parens': ['error', 'as-needed'],
        'arrow-spacing': 'error',
        'constructor-super': 'error',
        'generator-star-spacing': ['error', {before: true, after: false}],
        // Arrow returning a ternary is disallowed; wrapping in braces doesn't help.
        'no-class-assign': 'error',
        'no-confusing-arrow': 'off',
        'no-const-assign': 'error',
        'no-dupe-class-members': 'error',
        'no-duplicate-imports': 'error',
        'no-new-symbol': 'error',
        'no-this-before-super': 'error',
        'no-var': 'error',
        'no-useless-computed-key': 'error',
        'no-useless-constructor': 'error',
        'no-useless-rename': 'error',
        'object-shorthand': 'error',
        'prefer-arrow-callback': 'error',
        'prefer-const': 'error',
        'prefer-spread': 'error',
        'prefer-reflect': ['error', {exceptions: ['delete']}],
        'prefer-rest-params': 'error',
        'prefer-template': 'error',
        'rest-spread-spacing': ['error', 'never'],
        'require-yield': 'off',
        'template-curly-spacing': ['error', 'always'],
        'yield-star-spacing': ['error', 'after'],
    },
};
<|endoftext|>