<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.dropbox = factory();
    }
}(this, function () {

  function isFunction(x, type){ return ({}).toString.call(x) == '[object Function]'; }
  function isString(x, type){ return ({}).toString.call(x) == '[object String]'; }
  function isObject(x, type){ return ({}).toString.call(x) == '[object Object]'; }
  function paramsFromUrlHash(){
    return window.location.hash.replace(/^#/,'').split('&').reduce(function(o,entry){ if(entry=='') return o; entry=entry.split('='); o[decodeURIComponent(entry[0])] = decodeURIComponent(entry[1]); return o;},{});
  }

  var api = 'https://api.dropboxapi.com/2/',
      content = 'https://content.dropboxapi.com/2/';
      tokenStore = function(key, val){ return ( arguments.length > 1 ) ? (localStorage[key] = val) : localStorage[key]; },
      globalErrorHandler = undefined;

  var endpointMapping = {
    'auth/token/revoke': { contentType: null },
    'files/upload': { baseUri: content, format: 'content-upload' },
    'files/get_thumbnail': { baseUri: content, format: 'content-download' },
    'files/download' : { baseUri: content, format: 'content-download' },
    'files/get_preview': {baseUri: content, format: 'content-download' },
    'files/upload_session/append': {baseUri: content, format: 'content-upload'},
    'files/upload_session/append_v2': {baseUri: content, format: 'content-upload'},
    'files/upload_session/finish': {baseUri: content, format: 'content-upload'},
    'files/upload_session/start': {baseUri: content, format: 'content-upload'},
    'files/get_shared_link_file': {baseUri: content, format: 'content-download'}
  }
  var contentTypeMapping = {
    'rpc' : 'application/json',
    'content-upload' : 'application/octet-stream'
  }

  var dropbox = function(endpoint, apiArgs){
    var args = [].slice.call(arguments);

    var config = endpointMapping[endpoint] || {};
    config.baseUri = config.baseUri || api;
    config.format = config.format || 'rpc';
    config.contentType = config.contentType || (config.contentType === null) ? null : contentTypeMapping[config.format];

    var lastArg = args[args.length - 1];
    var handlers = (args.length > 2 && (isObject(lastArg) || isFunction(lastArg))) ? lastArg : {};
    if(isFunction(handlers)) handlers = { onComplete: handlers };

    var r = new XMLHttpRequest();

    r.open('POST', config.baseUri+endpoint, true);
    r.setRequestHeader('Authorization', 'Bearer '+ tokenStore('__dbat') );

    if(config.format == 'content-download') r.responseType = 'blob';
    if(apiArgs && apiArgs.responseType){
      r.responseType = apiArgs.responseType;
      delete apiArgs.responseType;
    }

    if(config.contentType) r.setRequestHeader('Content-Type', config.contentType);
    if(apiArgs && (config.format == 'content-upload' || config.format == 'content-download'))
      r.setRequestHeader('Dropbox-API-Arg', JSON.stringify(apiArgs));

    if(handlers.onDownloadProgress) r.addEventListener("progress", handlers.onDownloadProgress);
    if(handlers.onUploadProgress && r.upload) r.upload.addEventListener("progress", handlers.onUploadProgress);
    if(handlers.onError || globalErrorHandler) r.addEventListener("error", function(e){
      var er = handlers.onError && handlers.onError(e.target);
      globalErrorHandler && globalErrorHandler(e.target, er);
    });

    r.onreadystatechange = function () {
      if (r.readyState != 4 ) return;
      if (r.status == 200) {
        var apiResponse = JSON.parse( r.getResponseHeader('dropbox-api-result') || r.responseText );
        if(endpoint=='auth/token/revoke') tokenStore('__dbat', '');
        handlers.onComplete && handlers.onComplete( apiResponse, r.response, r);
      } else {
        var er = handlers.onError && handlers.onError(r);
        globalErrorHandler && globalErrorHandler(r, er);
      }
    };

    var requestPayload = (args.length > 2 && config.format == 'content-upload') ? args[2] : undefined;
    requestPayload = requestPayload || ( (apiArgs && config.format == 'rpc') ? JSON.stringify(apiArgs) : null );
    if(requestPayload){
      r.send(requestPayload);
    } else {
      r.send();
    }
  }

  dropbox.setGlobalErrorHandler = function(handler){ globalErrorHandler = handler; }
  dropbox.setTokenStore = function(store){ tokenStore = store; },
  dropbox.authenticate = function(apiArgs, handlers){
    handlers = handlers || {};
    if(isFunction(handlers)) handlers = { onComplete: handlers };
    apiArgs = apiArgs || {};
    if(isString(apiArgs)) apiArgs = { client_id: apiArgs };
    apiArgs.redirect_uri = apiArgs.redirect_uri || window.location.href;

    // if we already have an access token, return immediately
    if( tokenStore('__dbat') ) return handlers.onComplete();

    var params = paramsFromUrlHash(),
        csrfToken = tokenStore('__dbcsrf');

    if(params.state && csrfToken && params.state == csrfToken){
      // we are returning from authentication redirect
      if(params.access_token){
        // the authentcation was successful
        tokenStore('__dbat', params.access_token);
        tokenStore('__dbcsrf', '');
        window.location.replace( window.location.href.replace(/#.*/,'') );
      } else {
        // the authentication was not successful
        var er = handlers.onError && handlers.onError(params);
        globalErrorHandler && globalErrorHandler(params, er);
      }
    } else {
      // initiate authentication
      var csrfToken = ""+Math.floor(Math.random()*100000);
      tokenStore('__dbcsrf', csrfToken);

      window.location = "https://www.dropbox.com/1/oauth2/authorize?response_type=token&"
                        + "client_id="+ encodeURIComponent(apiArgs.client_id) +"&"
                        + "redirect_uri="+ encodeURIComponent(apiArgs.redirect_uri) + "&"
                        + "state="+ encodeURIComponent(csrfToken);
    }
  }

  return dropbox;
}));
<commit_msg>extracting `toString` calls a bit<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.dropbox = factory();
    }
}(this, function () {

  var toString = ({}).toString;
  function isFunction(x, type){ return toString.call(x) == '[object Function]'; }
  function isString(x, type){ return toString.call(x) == '[object String]'; }
  function isObject(x, type){ return toString.call(x) == '[object Object]'; }
  function paramsFromUrlHash(){
    return window.location.hash.replace(/^#/,'').split('&').reduce(function(o,entry){ if(entry=='') return o; entry=entry.split('='); o[decodeURIComponent(entry[0])] = decodeURIComponent(entry[1]); return o;},{});
  }

  var api = 'https://api.dropboxapi.com/2/',
      content = 'https://content.dropboxapi.com/2/';
      tokenStore = function(key, val){ return ( arguments.length > 1 ) ? (localStorage[key] = val) : localStorage[key]; },
      globalErrorHandler = undefined;

  var endpointMapping = {
    'auth/token/revoke': { contentType: null },
    'files/upload': { baseUri: content, format: 'content-upload' },
    'files/get_thumbnail': { baseUri: content, format: 'content-download' },
    'files/download' : { baseUri: content, format: 'content-download' },
    'files/get_preview': {baseUri: content, format: 'content-download' },
    'files/upload_session/append': {baseUri: content, format: 'content-upload'},
    'files/upload_session/append_v2': {baseUri: content, format: 'content-upload'},
    'files/upload_session/finish': {baseUri: content, format: 'content-upload'},
    'files/upload_session/start': {baseUri: content, format: 'content-upload'},
    'files/get_shared_link_file': {baseUri: content, format: 'content-download'}
  }
  var contentTypeMapping = {
    'rpc' : 'application/json',
    'content-upload' : 'application/octet-stream'
  }

  var dropbox = function(endpoint, apiArgs){
    var args = [].slice.call(arguments);

    var config = endpointMapping[endpoint] || {};
    config.baseUri = config.baseUri || api;
    config.format = config.format || 'rpc';
    config.contentType = config.contentType || (config.contentType === null) ? null : contentTypeMapping[config.format];

    var lastArg = args[args.length - 1];
    var handlers = (args.length > 2 && (isObject(lastArg) || isFunction(lastArg))) ? lastArg : {};
    if(isFunction(handlers)) handlers = { onComplete: handlers };

    var r = new XMLHttpRequest();

    r.open('POST', config.baseUri+endpoint, true);
    r.setRequestHeader('Authorization', 'Bearer '+ tokenStore('__dbat') );

    if(config.format == 'content-download') r.responseType = 'blob';
    if(apiArgs && apiArgs.responseType){
      r.responseType = apiArgs.responseType;
      delete apiArgs.responseType;
    }

    if(config.contentType) r.setRequestHeader('Content-Type', config.contentType);
    if(apiArgs && (config.format == 'content-upload' || config.format == 'content-download'))
      r.setRequestHeader('Dropbox-API-Arg', JSON.stringify(apiArgs));

    if(handlers.onDownloadProgress) r.addEventListener("progress", handlers.onDownloadProgress);
    if(handlers.onUploadProgress && r.upload) r.upload.addEventListener("progress", handlers.onUploadProgress);
    if(handlers.onError || globalErrorHandler) r.addEventListener("error", function(e){
      var er = handlers.onError && handlers.onError(e.target);
      globalErrorHandler && globalErrorHandler(e.target, er);
    });

    r.onreadystatechange = function () {
      if (r.readyState != 4 ) return;
      if (r.status == 200) {
        var apiResponse = JSON.parse( r.getResponseHeader('dropbox-api-result') || r.responseText );
        if(endpoint=='auth/token/revoke') tokenStore('__dbat', '');
        handlers.onComplete && handlers.onComplete( apiResponse, r.response, r);
      } else {
        var er = handlers.onError && handlers.onError(r);
        globalErrorHandler && globalErrorHandler(r, er);
      }
    };

    var requestPayload = (args.length > 2 && config.format == 'content-upload') ? args[2] : undefined;
    requestPayload = requestPayload || ( (apiArgs && config.format == 'rpc') ? JSON.stringify(apiArgs) : null );
    if(requestPayload){
      r.send(requestPayload);
    } else {
      r.send();
    }
  }

  dropbox.setGlobalErrorHandler = function(handler){ globalErrorHandler = handler; }
  dropbox.setTokenStore = function(store){ tokenStore = store; },
  dropbox.authenticate = function(apiArgs, handlers){
    handlers = handlers || {};
    if(isFunction(handlers)) handlers = { onComplete: handlers };
    apiArgs = apiArgs || {};
    if(isString(apiArgs)) apiArgs = { client_id: apiArgs };
    apiArgs.redirect_uri = apiArgs.redirect_uri || window.location.href;

    // if we already have an access token, return immediately
    if( tokenStore('__dbat') ) return handlers.onComplete();

    var params = paramsFromUrlHash(),
        csrfToken = tokenStore('__dbcsrf');

    if(params.state && csrfToken && params.state == csrfToken){
      // we are returning from authentication redirect
      if(params.access_token){
        // the authentcation was successful
        tokenStore('__dbat', params.access_token);
        tokenStore('__dbcsrf', '');
        window.location.replace( window.location.href.replace(/#.*/,'') );
      } else {
        // the authentication was not successful
        var er = handlers.onError && handlers.onError(params);
        globalErrorHandler && globalErrorHandler(params, er);
      }
    } else {
      // initiate authentication
      var csrfToken = ""+Math.floor(Math.random()*100000);
      tokenStore('__dbcsrf', csrfToken);

      window.location = "https://www.dropbox.com/1/oauth2/authorize?response_type=token&"
                        + "client_id="+ encodeURIComponent(apiArgs.client_id) +"&"
                        + "redirect_uri="+ encodeURIComponent(apiArgs.redirect_uri) + "&"
                        + "state="+ encodeURIComponent(csrfToken);
    }
  }

  return dropbox;
}));
<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
  'app/core/utils/kbn',
],
function (angular, _, kbn) {
  'use strict';

  var module = angular.module('grafana.services');

  module.service('templateSrv', function() {
    var self = this;

    this._regex = /\$(\w+)|\[\[([\s\S]+?)\]\]/g;
    this._index = {};
    this._texts = {};
    this._grafanaVariables = {};
    this._adhocVariables = {};

    this.init = function(variables) {
      this.variables = variables;
      this.updateTemplateData();
    };

    this.updateTemplateData = function() {
      this._index = {};
      this._filters = {};

      for (var i = 0; i < this.variables.length; i++) {
        var variable = this.variables[i];

        // add adhoc filters to it's own index
        if (variable.type === 'adhoc') {
          this._adhocVariables[variable.datasource] = variable;
          continue;
        }

        if (!variable.current || !variable.current.isNone && !variable.current.value) {
          continue;
        }

        this._index[variable.name] = variable;
      }
    };

    this.getAdhocFilters = function(datasourceName) {
      var variable = this._adhocVariables[datasourceName];
      if (variable) {
        return variable.filters || [];
      }
      return []
    };

    function luceneEscape(value) {
      return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, "\\$1");
    }

    this.luceneFormat = function(value) {
      if (typeof value === 'string') {
        return luceneEscape(value);
      }
      var quotedValues = _.map(value, function(val) {
        return '\"' + luceneEscape(val) + '\"';
      });
      return '(' + quotedValues.join(' OR ') + ')';
    };

    this.formatValue = function(value, format, variable) {
      // for some scopedVars there is no variable
      variable = variable || {};

      if (typeof format === 'function') {
        return format(value, variable, this.formatValue);
      }

      switch(format) {
        case "regex": {
          if (typeof value === 'string') {
            return kbn.regexEscape(value);
          }

          var escapedValues = _.map(value, kbn.regexEscape);
          return '(' + escapedValues.join('|') + ')';
        }
        case "lucene": {
          return this.luceneFormat(value, format, variable);
        }
        case "pipe": {
          if (typeof value === 'string') {
            return value;
          }
          return value.join('|');
        }
        default:  {
          if (typeof value === 'string') {
            return value;
          }
          return '{' + value.join(',') + '}';
        }
      }
    };

    this.setGrafanaVariable = function (name, value) {
      this._grafanaVariables[name] = value;
    };

    this.variableExists = function(expression) {
      this._regex.lastIndex = 0;
      var match = this._regex.exec(expression);
      return match && (self._index[match[1] || match[2]] !== void 0);
    };

    this.highlightVariablesAsHtml = function(str) {
      if (!str || !_.isString(str)) { return str; }

      str = _.escape(str);
      this._regex.lastIndex = 0;
      return str.replace(this._regex, function(match, g1, g2) {
        if (self._index[g1 || g2]) {
          return '' + match + '';
        }
        return match;
      });
    };

    this.getAllValue = function(variable) {
      if (variable.allValue) {
        return variable.allValue;
      }
      var values = [];
      for (var i = 1; i < variable.options.length; i++) {
        values.push(variable.options[i].value);
      }
      return values;
    };

    this.replace = function(target, scopedVars, format) {
      if (!target) { return target; }

      var variable, systemValue, value;
      this._regex.lastIndex = 0;

      return target.replace(this._regex, function(match, g1, g2) {
        variable = self._index[g1 || g2];

        if (scopedVars) {
          value = scopedVars[g1 || g2];
          if (value) {
            return self.formatValue(value.value, format, variable);
          }
        }

        if (!variable) {
          return match;
        }

        systemValue = self._grafanaVariables[variable.current.value];
        if (systemValue) {
          return self.formatValue(systemValue, format, variable);
        }

        value = variable.current.value;
        if (self.isAllValue(value)) {
          value = self.getAllValue(variable);
          // skip formating of custom all values
          if (variable.allValue) {
            return value;
          }
        }

        var res = self.formatValue(value, format, variable);
        return res;
      });
    };

    this.isAllValue = function(value) {
      return value === '$__all' || Array.isArray(value) && value[0] === '$__all';
    };

    this.replaceWithText = function(target, scopedVars) {
      if (!target) { return target; }

      var variable;
      this._regex.lastIndex = 0;

      return target.replace(this._regex, function(match, g1, g2) {
        if (scopedVars) {
          var option = scopedVars[g1 || g2];
          if (option) { return option.text; }
        }

        variable = self._index[g1 || g2];
        if (!variable) { return match; }

        return self._grafanaVariables[variable.current.value] || variable.current.text;
      });
    };

    this.fillVariableValuesForUrl = function(params, scopedVars) {
      _.each(this.variables, function(variable) {
        if (scopedVars && scopedVars[variable.name] !== void 0) {
          params['var-' + variable.name] = scopedVars[variable.name].value;
        } else {
          params['var-' + variable.name] = variable.getValueForUrl();
        }
      });
    };

  });

});
<commit_msg>fix(jslint): fixed lint issue<commit_after>define([
  'angular',
  'lodash',
  'app/core/utils/kbn',
],
function (angular, _, kbn) {
  'use strict';

  var module = angular.module('grafana.services');

  module.service('templateSrv', function() {
    var self = this;

    this._regex = /\$(\w+)|\[\[([\s\S]+?)\]\]/g;
    this._index = {};
    this._texts = {};
    this._grafanaVariables = {};
    this._adhocVariables = {};

    this.init = function(variables) {
      this.variables = variables;
      this.updateTemplateData();
    };

    this.updateTemplateData = function() {
      this._index = {};
      this._filters = {};

      for (var i = 0; i < this.variables.length; i++) {
        var variable = this.variables[i];

        // add adhoc filters to it's own index
        if (variable.type === 'adhoc') {
          this._adhocVariables[variable.datasource] = variable;
          continue;
        }

        if (!variable.current || !variable.current.isNone && !variable.current.value) {
          continue;
        }

        this._index[variable.name] = variable;
      }
    };

    this.getAdhocFilters = function(datasourceName) {
      var variable = this._adhocVariables[datasourceName];
      if (variable) {
        return variable.filters || [];
      }
      return [];
    };

    function luceneEscape(value) {
      return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, "\\$1");
    }

    this.luceneFormat = function(value) {
      if (typeof value === 'string') {
        return luceneEscape(value);
      }
      var quotedValues = _.map(value, function(val) {
        return '\"' + luceneEscape(val) + '\"';
      });
      return '(' + quotedValues.join(' OR ') + ')';
    };

    this.formatValue = function(value, format, variable) {
      // for some scopedVars there is no variable
      variable = variable || {};

      if (typeof format === 'function') {
        return format(value, variable, this.formatValue);
      }

      switch(format) {
        case "regex": {
          if (typeof value === 'string') {
            return kbn.regexEscape(value);
          }

          var escapedValues = _.map(value, kbn.regexEscape);
          return '(' + escapedValues.join('|') + ')';
        }
        case "lucene": {
          return this.luceneFormat(value, format, variable);
        }
        case "pipe": {
          if (typeof value === 'string') {
            return value;
          }
          return value.join('|');
        }
        default:  {
          if (typeof value === 'string') {
            return value;
          }
          return '{' + value.join(',') + '}';
        }
      }
    };

    this.setGrafanaVariable = function (name, value) {
      this._grafanaVariables[name] = value;
    };

    this.variableExists = function(expression) {
      this._regex.lastIndex = 0;
      var match = this._regex.exec(expression);
      return match && (self._index[match[1] || match[2]] !== void 0);
    };

    this.highlightVariablesAsHtml = function(str) {
      if (!str || !_.isString(str)) { return str; }

      str = _.escape(str);
      this._regex.lastIndex = 0;
      return str.replace(this._regex, function(match, g1, g2) {
        if (self._index[g1 || g2]) {
          return '' + match + '';
        }
        return match;
      });
    };

    this.getAllValue = function(variable) {
      if (variable.allValue) {
        return variable.allValue;
      }
      var values = [];
      for (var i = 1; i < variable.options.length; i++) {
        values.push(variable.options[i].value);
      }
      return values;
    };

    this.replace = function(target, scopedVars, format) {
      if (!target) { return target; }

      var variable, systemValue, value;
      this._regex.lastIndex = 0;

      return target.replace(this._regex, function(match, g1, g2) {
        variable = self._index[g1 || g2];

        if (scopedVars) {
          value = scopedVars[g1 || g2];
          if (value) {
            return self.formatValue(value.value, format, variable);
          }
        }

        if (!variable) {
          return match;
        }

        systemValue = self._grafanaVariables[variable.current.value];
        if (systemValue) {
          return self.formatValue(systemValue, format, variable);
        }

        value = variable.current.value;
        if (self.isAllValue(value)) {
          value = self.getAllValue(variable);
          // skip formating of custom all values
          if (variable.allValue) {
            return value;
          }
        }

        var res = self.formatValue(value, format, variable);
        return res;
      });
    };

    this.isAllValue = function(value) {
      return value === '$__all' || Array.isArray(value) && value[0] === '$__all';
    };

    this.replaceWithText = function(target, scopedVars) {
      if (!target) { return target; }

      var variable;
      this._regex.lastIndex = 0;

      return target.replace(this._regex, function(match, g1, g2) {
        if (scopedVars) {
          var option = scopedVars[g1 || g2];
          if (option) { return option.text; }
        }

        variable = self._index[g1 || g2];
        if (!variable) { return match; }

        return self._grafanaVariables[variable.current.value] || variable.current.text;
      });
    };

    this.fillVariableValuesForUrl = function(params, scopedVars) {
      _.each(this.variables, function(variable) {
        if (scopedVars && scopedVars[variable.name] !== void 0) {
          params['var-' + variable.name] = scopedVars[variable.name].value;
        } else {
          params['var-' + variable.name] = variable.getValueForUrl();
        }
      });
    };

  });

});
<|endoftext|>


<commit_before>console.log("Code Kata: Word Wrap, by @romenrg");

function Wrapper() {
    this.wrap = function(string, columnNum) {
        var tmpString = string;
        var newString = "";
        var lastBlankPos = null;
        var finished = false;
        while (!finished) {
            lastBlankPos = null;
            for (var i=0; i<columnNum+1; i++) {
                if (tmpString.length > i) {
                    if (tmpString[i] == ' ') {
                        lastBlankPos = i;
                    }
                }
                else {
                    finished = true;
                }
            }
            if ((!finished) && (lastBlankPos != null)) { //TODO: Be careful with cases in which there are no spaces
                newString = newString.concat(tmpString.substr(0, lastBlankPos) + '\n');
                tmpString = tmpString.substr(lastBlankPos+1, tmpString.length);
            }
            else if (finished) {
                newString = newString.concat(tmpString.substr(0, tmpString.length));
                finished = true;
            }
            else {
                newString = newString.concat(tmpString.substr(0, columnNum) + '\n');
                tmpString = tmpString.substr(columnNum, tmpString.length);
            }
        }
        return newString;
    }
}

module.exports = Wrapper;<commit_msg>Refactoring tests and adding TODOs to the program<commit_after>function Wrapper() {
    //TODO 1: refactoring the wrap function
    this.wrap = function(string, columnNum) {
        var tmpString = string;
        var newString = "";
        var finished = false;
        while (!finished) {
            var lastBlankPos = null;
            for (var i=0; i<columnNum+1; i++) {
                if (tmpString.length > i) {
                    if (tmpString[i] == ' ') {
                        lastBlankPos = i;
                    }
                }
                else {
                    finished = true;
                }
            }
            if ((!finished) && (lastBlankPos != null)) {
                newString = newString.concat(tmpString.substr(0, lastBlankPos) + '\n');
                tmpString = tmpString.substr(lastBlankPos+1, tmpString.length);
            }
            else if (finished) {
                newString = newString.concat(tmpString.substr(0, tmpString.length));
                finished = true;
            }
            else {
                newString = newString.concat(tmpString.substr(0, columnNum) + '\n');
                tmpString = tmpString.substr(columnNum, tmpString.length);
            }
        }
        return newString;
    }
}

//TODO 2: Creating a main and getting parameters from stdin
console.log("Code Kata: Word Wrap, by @romenrg");

module.exports = Wrapper;<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from 'ember-bootstrap/templates/components/bs-modal/header/close';

/**

 @class ModalHeaderClose
 @namespace Components
 @extends Ember.Component
 @private
 */
export default Ember.Component.extend({
  layout,
  tagName: 'button',
  classNames: ['close'],
  attributeBindings: ['type', 'aria-label'],
  'aria-label': 'Close',
  type: 'button',

  /**
   * @event onClick
   * @public
   */
  onChange() {},

  click() {
    this.get('onClick')();
  }
});<commit_msg>fix(Modal): Fixed `onClick` dummy action. Thanks to @dajk<commit_after>import Ember from 'ember';
import layout from 'ember-bootstrap/templates/components/bs-modal/header/close';

/**

 @class ModalHeaderClose
 @namespace Components
 @extends Ember.Component
 @private
 */
export default Ember.Component.extend({
  layout,
  tagName: 'button',
  classNames: ['close'],
  attributeBindings: ['type', 'aria-label'],
  'aria-label': 'Close',
  type: 'button',

  /**
   * @event onClick
   * @public
   */
  onClick() {},

  click() {
    this.get('onClick')();
  }
});
<|endoftext|>


<commit_before>var Plotly = require('../src/plotly');

describe('Test Modebar', function() {
    'use strict';

    var getMockGraphInfo = function() {
        var graphInfo = {
            _fullLayout: {
                dragmode: 'zoom'
            },
            _context: {
                displayModeBar: true,
                displaylogo: true
            }
        };
        return graphInfo;
    };

    var getMockContainerTree = function() {
        var root = document.createElement('div');
        root.className = 'plot-container';
        var parent = document.createElement('div');
        parent.className = 'svg-container';
        root.appendChild(parent);
        return parent;
    };

    var createModebar = function(buttons) {

        var container = getMockContainerTree(),
            graphInfo = getMockGraphInfo();

        var modebar = new Plotly.ModeBar({
            buttons: buttons,
            container: container,
            Plotly: Plotly,
            graphInfo: graphInfo
        });
        return modebar;
    };

    describe('Test modebarCleanup:', function() {

        it('should make a cleanup.', function() {
            var buttons = [['zoom2d']];
            var modebar = createModebar(buttons);
            var modebarParent = modebar.element.parentNode;
            modebar.cleanup();
            expect(modebar.element.innerHTML).toEqual('');
            expect(modebarParent.querySelector('.modebar'))
                .toBeNull();
        });
    });

    describe('Test modebarHasButtons:', function() {

        var modeButtons2d,
            modeButtons3d;

        // Same as in ../graph_interact.js
        beforeEach( function() {
            modeButtons2d = [
                ['zoom2d', 'pan2d'],
                ['zoomIn2d', 'zoomOut2d', 'autoScale2d'],
                ['hoverClosest2d', 'hoverCompare2d']
            ];

            modeButtons3d = [
                ['rotate3d', 'zoom3d', 'pan3d'],
                ['resetCameraDefault3d', 'resetCameraLastSave3d'],
                ['hoverClosest3d']
            ];
        });

        it('should return true going from 3D -> 3D buttons.', function() {
            var modebar = createModebar(modeButtons3d);
            expect(modebar.hasButtons(modeButtons3d)).toBe(true);
        });

        it('should return true going from 2D -> 2D buttons.', function() {
            var modebar = createModebar(modeButtons2d);
            expect(modebar.hasButtons(modeButtons2d)).toBe(true);
        });

        it('should return false going from 2D -> 3D buttons.', function() {
            var modebar = createModebar(modeButtons2d);
            expect(modebar.hasButtons(modeButtons3d)).toBe(false);
        });

        it('should return false going from 3D -> 2D buttons.', function() {
            var modebar = createModebar(modeButtons3d);
            expect(modebar.hasButtons(modeButtons2d)).toBe(false);
        });
    });
});
<commit_msg>update tests with new modebar option<commit_after>var Plotly = require('../src/plotly');

describe('Test Modebar', function() {
    'use strict';

    var getMockGraphInfo = function() {
        var graphInfo = {
            _fullLayout: {
                dragmode: 'zoom'
            },
            _context: {
                displayModeBar: true,
                displaylogo: true
            }
        };
        return graphInfo;
    };

    var getMockContainerTree = function() {
        var root = document.createElement('div');
        root.className = 'plot-container';
        var parent = document.createElement('div');
        parent.className = 'svg-container';
        root.appendChild(parent);
        return parent;
    };

    var createModebar = function(buttons) {

        var container = getMockContainerTree(),
            graphInfo = getMockGraphInfo();

        var modebar = new Plotly.ModeBar({
            buttons: buttons,
            container: container,
            Plotly: Plotly,
            graphInfo: graphInfo
        });
        return modebar;
    };

    describe('Test modebarCleanup:', function() {

        it('should make a cleanup.', function() {
            var buttons = [['zoom2d']];
            var modebar = createModebar(buttons);
            var modebarParent = modebar.element.parentNode;
            modebar.cleanup();
            expect(modebar.element.innerHTML).toEqual('');
            expect(modebarParent.querySelector('.modebar'))
                .toBeNull();
        });
    });

    describe('Test modebarHasButtons:', function() {

        var modeButtons2d,
            modeButtons3d;

        // Same as in ../graph_interact.js
        beforeEach( function() {
            modeButtons2d = [
                ['zoom2d', 'pan2d'],
                ['zoomIn2d', 'zoomOut2d', 'autoScale2d'],
                ['hoverClosest2d', 'hoverCompare2d']
            ];

            modeButtons3d = [
                ['orbitRotation', 'tableRotation', 'zoom3d', 'pan3d'],
                ['resetCameraDefault3d', 'resetCameraLastSave3d'],
                ['hoverClosest3d']
            ];
        });

        it('should return true going from 3D -> 3D buttons.', function() {
            var modebar = createModebar(modeButtons3d);
            expect(modebar.hasButtons(modeButtons3d)).toBe(true);
        });

        it('should return true going from 2D -> 2D buttons.', function() {
            var modebar = createModebar(modeButtons2d);
            expect(modebar.hasButtons(modeButtons2d)).toBe(true);
        });

        it('should return false going from 2D -> 3D buttons.', function() {
            var modebar = createModebar(modeButtons2d);
            expect(modebar.hasButtons(modeButtons3d)).toBe(false);
        });

        it('should return false going from 3D -> 2D buttons.', function() {
            var modebar = createModebar(modeButtons3d);
            expect(modebar.hasButtons(modeButtons2d)).toBe(false);
        });
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['c<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['co<|endoftext|>


<commit_before>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
});

Router.map(function() {
  this.route('club', { path: '/clubs/:club_id' }, function() {
    this.route('pilots');
    this.route('edit');
  });
  this.route('clubs', { path: '/clubs' });

  this.route('users', { path: '/users' });

  this.route('stats', { path: '/statistics' }, function() {
    this.route('wildcard', { path: '/*wildcard' });
  });

  this.route('flight-upload', { path: '/flights/upload' });

  this.route('flight', { path: '/flights/:flight_id' });

  this.route('flights', { path: '/flights' }, function() {
    this.route('all');
    this.route('latest');
    this.route('date', { path: '/date/:date' });
    this.route('airport', { path: '/airport/:airport_id' });
    this.route('club', { path: '/club/:club_id' });
    this.route('pilot', { path: '/pilot/:pilot_id' });
    this.route('unassigned');
    this.route('pinned');
    this.route('list', { path: '/list/:list' });
  });

  this.route('tracking', function() {
    this.route('details', { path: '/:user_ids' });
  });

  this.route('ranking', function() {
    this.route('clubs');
    this.route('pilots');
    this.route('airports');
  });

  this.route('search');

  this.route('timeline');
  this.route('notifications');

  this.route('settings', function() {
    this.route('profile');
    this.route('password');
    this.route('club');
    this.route('tracking');
  });

  this.route('islands', { path: '/*wildcard' });
});

export default Router;
<commit_msg>router: Add "flight" subroutes<commit_after>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
});

Router.map(function() {
  this.route('club', { path: '/clubs/:club_id' }, function() {
    this.route('pilots');
    this.route('edit');
  });
  this.route('clubs', { path: '/clubs' });

  this.route('users', { path: '/users' });

  this.route('stats', { path: '/statistics' }, function() {
    this.route('wildcard', { path: '/*wildcard' });
  });

  this.route('flight-upload', { path: '/flights/upload' });

  this.route('flight', { path: '/flights/:flight_id' }, function() {
    this.route('change-aircraft', { path: '/change_aircraft' });
    this.route('change-pilot', { path: '/change_pilot' });
  });

  this.route('flights', { path: '/flights' }, function() {
    this.route('all');
    this.route('latest');
    this.route('date', { path: '/date/:date' });
    this.route('airport', { path: '/airport/:airport_id' });
    this.route('club', { path: '/club/:club_id' });
    this.route('pilot', { path: '/pilot/:pilot_id' });
    this.route('unassigned');
    this.route('pinned');
    this.route('list', { path: '/list/:list' });
  });

  this.route('tracking', function() {
    this.route('details', { path: '/:user_ids' });
  });

  this.route('ranking', function() {
    this.route('clubs');
    this.route('pilots');
    this.route('airports');
  });

  this.route('search');

  this.route('timeline');
  this.route('notifications');

  this.route('settings', function() {
    this.route('profile');
    this.route('password');
    this.route('club');
    this.route('tracking');
  });

  this.route('islands', { path: '/*wildcard' });
});

export default Router;
<|endoftext|>


<commit_before>/**
 * Cross-Site Request Forgery Protection Settings
 * (sails.config.csrf)
 *
 * CSRF tokens are like a tracking chip.  While a session tells the server that a user
 * "is who they say they are", a csrf token tells the server "you are where you say you are".
 *
 * When enabled, all non-GET requests to the Sails server must be accompanied by
 * a special token, identified as the '_csrf' parameter.
 *
 * This option protects your Sails app against cross-site request forgery (or CSRF) attacks.
 * A would-be attacker needs not only a user's session cookie, but also this timestamped,
 * secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain.
 *
 * This allows us to have certainty that our users' requests haven't been hijacked,
 * and that the requests they're making are intentional and legitimate.
 *
 * This token has a short-lived expiration timeline, and must be acquired by either:
 *
 * (a)		For traditional view-driven web apps:
 *			Fetching it from one of your views, where it may be accessed as
 *			a local variable, e.g.:
 *			<form>
 *				<input type="hidden" name="_csrf" value="<%= _csrf %>" />
 *			</form>
 *
 * or (b)	For AJAX/Socket-heavy and/or single-page apps:
 *			Sending a GET request to the `/csrfToken` route, where it will be returned
 *			as JSON, e.g.:
 *			{ _csrf: 'ajg4JD(JGdajhLJALHDa' }
 *
 *
 * Enabling this option requires managing the token in your front-end app.
 * For traditional web apps, it's as easy as passing the data from a view into a form action.
 * In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token.
 *
 * For more information on CSRF, check out:
 * http://en.wikipedia.org/wiki/Cross-site_request_forgery
 *
 * For more information on this configuration file, including info on CSRF + CORS, see:
 * http://sailsjs.org/documentation/reference/configuration/sails-config-csrf
 *
 */

/****************************************************************************
*                                                                           *
* Enabled CSRF protection for your site?                                    *
*                                                                           *
****************************************************************************/

// module.exports.csrf = false;

/****************************************************************************
*                                                                           *
* You may also specify more fine-grained settings for CSRF, including the   *
* domains which are allowed to request the CSRF token via AJAX. These       *
* settings override the general CORS settings in your config/cors.js file.  *
*                                                                           *
****************************************************************************/

// module.exports.csrf = {
//   grantTokenViaAjax: true,
//   origin: '',
//   routesDisabled: [ 'POST /webhooks/stripe/*' ]
// }
<commit_msg>Fix generated comments for CSRF config, and simplify the explanation.<commit_after>/**
 * Cross-Site Request Forgery Protection Settings
 * (sails.config.csrf)
 *
 * CSRF tokens are like a tracking chip.  While a session tells the server that a user
 * "is who they say they are", a csrf token tells the server "you are where you say you are".
 *
 * When enabled, all non-GET requests to the Sails server must be accompanied by
 * a special token, identified as the '_csrf' parameter.
 *
 * This option protects your Sails app against cross-site request forgery (or CSRF) attacks.
 * A would-be attacker needs not only a user's session cookie, but also this timestamped,
 * secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain.
 *
 * This allows us to have certainty that our users' requests haven't been hijacked,
 * and that the requests they're making are intentional and legitimate.
 *
 * This token has a short-lived expiration timeline, and must be acquired by either:
 *
 * (a)		For traditional view-driven web apps:
 *			Fetching it from one of your views, where it may be accessed as
 *			a local variable, e.g.:
 *			<form>
 *				<input type="hidden" name="_csrf" value="<%= _csrf %>" />
 *			</form>
 *
 * or (b)	For AJAX/Socket-heavy and/or single-page apps:
 *			Sending a GET request to the `/csrfToken` route, where it will be returned
 *			as JSON, e.g.:
 *			{ _csrf: 'ajg4JD(JGdajhLJALHDa' }
 *
 *
 * Enabling this option requires managing the token in your front-end app.
 * For traditional web apps, it's as easy as passing the data from a view into a form action.
 * In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token.
 *
 * For more information on CSRF, check out:
 * http://en.wikipedia.org/wiki/Cross-site_request_forgery
 *
 * For more information on this configuration file, including info on CSRF + CORS, see:
 * http://sailsjs.org/documentation/reference/configuration/sails-config-csrf
 *
 */

/****************************************************************************
*                                                                           *
* By default, Sails' built-in CSRF protection is disabled.                  *
* To enable CSRF protection with usual settings, set this to `true`.        *
* Or for more flexibility, specify a dictionary with any of the properties  *
* described in the Sails reference documentation (see link above).          *
*                                                                           *
****************************************************************************/

// module.exports.csrf = false;
<|endoftext|>


<commit_before>const TAU = 2 * Math.PI;
// 10000 arbitrary units of time is one perfect loop.
const AUTS_PER_LOOP = 10000;
const AUTS_PER_SECOND = 500;
const LARGEST_ORBIT_RADIUS = 386;

const orbitCount = 12;

const orbitRadius = function(index) {
    return index / (orbitCount + 3) * LARGEST_ORBIT_RADIUS;
};

const getX = function(index, auts) {
    const radius = orbitRadius(index);
    const actualRevolutions = auts / AUTS_PER_LOOP * (orbitCount + 5 - index);
    return radius * Math.sin(actualRevolutions * TAU);
};

const getY = function(index, auts) {
    const radius = orbitRadius(index);
    const actualRevolutions = auts / AUTS_PER_LOOP * (orbitCount + 5 - index);
    return radius * Math.cos(actualRevolutions * TAU);
};

const draw = function(auts) {
    planets
        .attr("cx", o => { return getX(o, auts) })
        .attr("cy", o => { return getY(o, auts) })
};

const surface = d3.select("svg");

const orbits = surface
    .selectAll(".orbit")
    .data(_.range(3, orbitCount + 3))
    .enter().append("circle")
        .classed("orbit", true)
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", orbitRadius)
        .attr("stroke", "blue")
        .attr("fill-opacity", 0);

const planets = surface
    .selectAll(".planet")
    .data(_.range(3, orbitCount + 3))
    .enter().append("circle")
        .classed("planet", true)
        .attr("cx", getX)
        .attr("cy", getY)
        .attr("r", 8)
        .attr("stroke", "black")
        .attr("fill", "purple");

d3.timer(time => {
    const auts = time/1000 * AUTS_PER_SECOND;
    draw(auts);
});<commit_msg>Continue code cleanup<commit_after>const TAU = 2 * Math.PI;
// This many arbitrary units of time is one perfect loop.
const AUTS_PER_LOOP = 10000;
const AUTS_PER_SECOND = 500;
const LARGEST_ORBIT_RADIUS = 386;

// The divisor starts at this number and increases by 1 for each orbit closer to the center.
const OUTERMOST_DIVISOR = 2;
// Don't draw any orbits smaller than this one.
const INNERMOST_ORBIT_INDEX = 3;

const orbitCount = 12;

const getX = function(index, auts) {
    return polarToCartesian(index, auts, Math.sin);
};

const getY = function(index, auts) {
    return polarToCartesian(index, auts, Math.cos);
};

const polarToCartesian = function(index, auts, fn) {
    const radius = orbitRadius(index);
    const revolutions = auts / AUTS_PER_LOOP * (orbitCount + INNERMOST_ORBIT_INDEX + OUTERMOST_DIVISOR - index);
    return radius * fn(revolutions * TAU);
};

const orbitRadius = function(index) {
    return index / (orbitCount + INNERMOST_ORBIT_INDEX) * LARGEST_ORBIT_RADIUS;
};

const draw = function(auts) {
    planets
        .attr("cx", o => { return getX(o, auts) })
        .attr("cy", o => { return getY(o, auts) })
};

const surface = d3.select("svg");

const orbits = surface
    .selectAll(".orbit")
    .data(_.range(INNERMOST_ORBIT_INDEX, orbitCount + INNERMOST_ORBIT_INDEX))
    .enter().append("circle")
        .classed("orbit", true)
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", orbitRadius)
        .attr("stroke", "blue")
        .attr("fill-opacity", 0);

const planets = surface
    .selectAll(".planet")
    .data(_.range(INNERMOST_ORBIT_INDEX, orbitCount + INNERMOST_ORBIT_INDEX))
    .enter().append("circle")
        .classed("planet", true)
        .attr("cx", getX)
        .attr("cy", getY)
        .attr("r", 8)
        .attr("stroke", "black")
        .attr("fill", "purple");

d3.timer(time => {
    const auts = time/1000 * AUTS_PER_SECOND;
    draw(auts);
});<|endoftext|>


<commit_before>/* eslint quotes: 0 */

import * as t from "../../types";

/**
 * Prints Identifier, prints name.
 */

export function Identifier(node) {
  this.push(node.name);
}

/**
 * Prints RestElement, prints argument.
 */

export function RestElement(node, print) {
  this.push("...");
  print.plain(node.argument);
}

/**
 * Alias RestElement printer as SpreadElement,
 * and RestElement printer as SpreadProperty.
 */

export { RestElement as SpreadElement, RestElement as SpreadProperty };

/**
 * Prints ObjectExpression, prints properties.
 */

export function ObjectExpression(node, print) {
  var props = node.properties;

  this.push("{");
  print.printInnerComments();

  if (props.length) {
    this.space();
    print.list(props, { indent: true });
    this.space();
  }

  this.push("}");
}

/**
 * Alias ObjectExpression printer as ObjectPattern.
 */

export { ObjectExpression as ObjectPattern };

/**
 * Prints Property, prints decorators, key, and value, handles kind, computed, and shorthand.
 */

export function Property(node, print) {
  print.list(node.decorators, { separator: "" });

  if (node.method || node.kind === "get" || node.kind === "set") {
    this._method(node, print);
  } else {
    if (node.computed) {
      this.push("[");
      print.plain(node.key);
      this.push("]");
    } else {
      // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
      if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
        print.plain(node.value);
        return;
      }

      print.plain(node.key);

      // shorthand!
      if (node.shorthand &&
        (t.isIdentifier(node.key) &&
         t.isIdentifier(node.value) &&
         node.key.name === node.value.name)) {
        return;
      }
    }

    this.push(":");
    this.space();
    print.plain(node.value);
  }
}

/**
 * Prints ArrayExpression, prints elements.
 */

export function ArrayExpression(node, print) {
  var elems = node.elements;
  var len   = elems.length;

  this.push("[");
  print.printInnerComments();

  for (var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    if (!elem) {
      // If the array expression ends with a hole, that hole
      // will be ignored by the interpreter, but if it ends with
      // two (or more) holes, we need to write out two (or more)
      // commas so that the resulting code is interpreted with
      // both (all) of the holes.
      this.push(",");
    } else {
      if (i > 0) this.space();
      print.plain(elem);
      if (i < len - 1) this.push(",");
    }
  }

  this.push("]");
}

/**
 * Alias ArrayExpression printer as ArrayPattern.
 */

export { ArrayExpression as ArrayPattern };

/**
 * Prints Literal, prints value, regex, raw, handles val type.
 */

export function Literal(node, print) {
  this.push(""); // hack: catch up indentation
  this._push(this._Literal(node));
}

export function _Literal(node) {
  var val = node.value;

  // just use the raw property if our current value is equivalent to the one we got
  // when we populated raw
  if (node.raw != null && node.rawValue != null && val === node.rawValue) {
    return node.raw;
  }

  if (node.regex) {
    return `/${node.regex.pattern}/${node.regex.flags}`;
  }

  switch (typeof val) {
    case "string":
      return this._stringLiteral(val);

    case "number":
      return val + "";

    case "boolean":
      return val ? "true" : "false";

    default:
      if (val === null) {
        return "null";
      } else {
        throw new Error("Invalid Literal type");
      }
  }
}

/**
 * Prints string literals, handles format.
 */

export function _stringLiteral(val) {
  val = JSON.stringify(val);

  // escape illegal js but valid json unicode characters
  val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
    return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
  });

  if (this.format.quotes === "single") {
    // remove double quotes
    val = val.slice(1, -1);

    // unescape double quotes
    val = val.replace(/\\"/g, '"');

    // escape single quotes
    val = val.replace(/'/g, "\\'");

    // add single quotes
    val = `'${val}'`;
  }

  return val;
}
<commit_msg>move up regex Literal generation<commit_after>/* eslint quotes: 0 */

import * as t from "../../types";

/**
 * Prints Identifier, prints name.
 */

export function Identifier(node) {
  this.push(node.name);
}

/**
 * Prints RestElement, prints argument.
 */

export function RestElement(node, print) {
  this.push("...");
  print.plain(node.argument);
}

/**
 * Alias RestElement printer as SpreadElement,
 * and RestElement printer as SpreadProperty.
 */

export { RestElement as SpreadElement, RestElement as SpreadProperty };

/**
 * Prints ObjectExpression, prints properties.
 */

export function ObjectExpression(node, print) {
  var props = node.properties;

  this.push("{");
  print.printInnerComments();

  if (props.length) {
    this.space();
    print.list(props, { indent: true });
    this.space();
  }

  this.push("}");
}

/**
 * Alias ObjectExpression printer as ObjectPattern.
 */

export { ObjectExpression as ObjectPattern };

/**
 * Prints Property, prints decorators, key, and value, handles kind, computed, and shorthand.
 */

export function Property(node, print) {
  print.list(node.decorators, { separator: "" });

  if (node.method || node.kind === "get" || node.kind === "set") {
    this._method(node, print);
  } else {
    if (node.computed) {
      this.push("[");
      print.plain(node.key);
      this.push("]");
    } else {
      // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
      if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
        print.plain(node.value);
        return;
      }

      print.plain(node.key);

      // shorthand!
      if (node.shorthand &&
        (t.isIdentifier(node.key) &&
         t.isIdentifier(node.value) &&
         node.key.name === node.value.name)) {
        return;
      }
    }

    this.push(":");
    this.space();
    print.plain(node.value);
  }
}

/**
 * Prints ArrayExpression, prints elements.
 */

export function ArrayExpression(node, print) {
  var elems = node.elements;
  var len   = elems.length;

  this.push("[");
  print.printInnerComments();

  for (var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    if (!elem) {
      // If the array expression ends with a hole, that hole
      // will be ignored by the interpreter, but if it ends with
      // two (or more) holes, we need to write out two (or more)
      // commas so that the resulting code is interpreted with
      // both (all) of the holes.
      this.push(",");
    } else {
      if (i > 0) this.space();
      print.plain(elem);
      if (i < len - 1) this.push(",");
    }
  }

  this.push("]");
}

/**
 * Alias ArrayExpression printer as ArrayPattern.
 */

export { ArrayExpression as ArrayPattern };

/**
 * Prints Literal, prints value, regex, raw, handles val type.
 */

export function Literal(node, print) {
  this.push(""); // hack: catch up indentation
  this._push(this._Literal(node));
}

export function _Literal(node) {
  var val = node.value;

  if (node.regex) {
    return `/${node.regex.pattern}/${node.regex.flags}`;
  }

  // just use the raw property if our current value is equivalent to the one we got
  // when we populated raw
  if (node.raw != null && node.rawValue != null && val === node.rawValue) {
    return node.raw;
  }

  switch (typeof val) {
    case "string":
      return this._stringLiteral(val);

    case "number":
      return val + "";

    case "boolean":
      return val ? "true" : "false";

    default:
      if (val === null) {
        return "null";
      } else {
        throw new Error("Invalid Literal type");
      }
  }
}

/**
 * Prints string literals, handles format.
 */

export function _stringLiteral(val) {
  val = JSON.stringify(val);

  // escape illegal js but valid json unicode characters
  val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
    return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
  });

  if (this.format.quotes === "single") {
    // remove double quotes
    val = val.slice(1, -1);

    // unescape double quotes
    val = val.replace(/\\"/g, '"');

    // escape single quotes
    val = val.replace(/'/g, "\\'");

    // add single quotes
    val = `'${val}'`;
  }

  return val;
}
<|endoftext|>


<commit_before>(function(){
  window.Controller = function(data,instanceName,paletteId,widthFieldId,heightFieldId,canvasId,saveDataId) {
    var defaultColors = ["red","blue","green"];
    var coeff = 25;
    var updateSaveData = function() {
      document.getElementById(saveDataId).value = JSON.stringify(data);
    }
    var buildCanvas = function(grid) {
      build(document.getElementById(canvasId),[{
        tag: "svg",
        attrs: {
          width: "50%",
          height: "50%",
          viewBox: [0,0,(coeff * data.width),(coeff * data.height)].join(" ")
        },
        children: [{
          tag: "defs",
          children: [{
            tag: "rect",
            attrs: {
              id: "#r0",
              width: coeff,
              height: coeff,
              stroke: "black",
              "stroke-width": 1,
              fill: "white"
            }
          }].concat(data.palette.map(function(color, n){
            if (color === "") {
              color = "none";
            }
            return {
              tag: "rect",
              attrs: {
                id: "r" + n,
                width: coeff,
                height: coeff,
                stroke: "black",
                "stroke-width": 1,
                fill: color
              }
            }
          }))
        }].concat(range(data.height).reduce(function(out,y){
          return out.concat(range(data.width).map(function(x){
            var id = x + "-" + y;
            var color = (id in grid)?"#r" + grid[id]:"#r0";
            return {
              tag: "use",
              attrs: {
                id: x + "-" + y,
                href: color,
                x: x * coeff,
                y: y * coeff,
                onClick: instanceName + ".setColor(" + x + "," + y + ")"
              }
            }
          }));
        },[]))
      }])
    };
    this.init = function() {
        document.getElementById(widthFieldId).value = data.width;
        document.getElementById(heightFieldId).value = data.height;
        while(colorCount < data.palette.length) {
          this.addColor();
        }
        data.palette.forEach(function(color, index) {
          document.getElementById("color" + index).value = color;
        });
        buildCanvas(data.grid);
        updateSaveData();
    };
    this.addColor = function() {
      data.palette.push("white");
      build(document.getElementById(paletteId),data.palette.map(function(color,n){
        var index = n + 1;
        return {
          tag: "li",
          children: [{
            tag: "input",
            attrs: {
              type: "radio",
              name: "colors",
              id: "colorSelect" + index,
              checked: true,
              value: index
            }
          },{
            tag: "input",
            attrs: {
              type: "text",
              id: "color" + index,
              value: color,
              onChange: instanceName + ".updateColor(" + index + ")"
            }
          }]
        };
      }));
      buildCanvas(data.grid);
    };
    var updateColor = function(index) {
      var colorField = document.getElementById("color" + index);
      var colorObj = document.getElementById("r" + index);
      var fill = colorObj.attributes.getNamedItem("fill");
      fill.value = colorField.value;
      data.color[n] = colorField.value;
      updateSaveData();
    }
    this.resize = function() {
      data.width = document.getElementById(widthFieldId).value;
      data.height = document.getElementById(heightFieldId).value;
      buildCanvas(data.grid);
      updateSaveData();
    };
    this.setColor = function(x, y) {
      console.log("set color: (" + x + "," + y + ")");
      var colorIndex = range(colorCount).map(function(n){
        return document.getElementById("colorSelect" + n);
      }).filter(function(radio,n){
        console.log("checking radio item " + n);
        return radio.checked;
      }).map(function(radio){
        return radio.value;
      })[0];
      var color = ((colorIndex) && (colorIndex > 0))?"#r"+colorIndex:"#r0";
      var id = x + "-" + y;
      var pixel = document.getElementById(id);
      var href = pixel.attributes.getNamedItem("href");
      href.value = "#r" + colorIndex;
      if (colorIndex > 0) {
          data.grid[id] = colorIndex;
      } else {
        delete data.grid[id];
      }
      updateSaveData();
    }
  };
})()
<commit_msg>fixing javascript<commit_after>(function(){
  window.Controller = function(data,instanceName,paletteId,widthFieldId,heightFieldId,canvasId,saveDataId) {
    var defaultColors = ["red","blue","green"];
    var coeff = 25;
    var updateSaveData = function() {
      document.getElementById(saveDataId).value = JSON.stringify(data);
    }
    var buildCanvas = function(grid) {
      build(document.getElementById(canvasId),[{
        tag: "svg",
        attrs: {
          width: "50%",
          height: "50%",
          viewBox: [0,0,(coeff * data.width),(coeff * data.height)].join(" ")
        },
        children: [{
          tag: "defs",
          children: [{
            tag: "rect",
            attrs: {
              id: "#r0",
              width: coeff,
              height: coeff,
              stroke: "black",
              "stroke-width": 1,
              fill: "white"
            }
          }].concat(data.palette.map(function(color, n){
            if (color === "") {
              color = "none";
            }
            return {
              tag: "rect",
              attrs: {
                id: "r" + n,
                width: coeff,
                height: coeff,
                stroke: "black",
                "stroke-width": 1,
                fill: color
              }
            }
          }))
        }].concat(range(data.height).reduce(function(out,y){
          return out.concat(range(data.width).map(function(x){
            var id = x + "-" + y;
            var color = (id in grid)?"#r" + grid[id]:"#r0";
            return {
              tag: "use",
              attrs: {
                id: x + "-" + y,
                href: color,
                x: x * coeff,
                y: y * coeff,
                onClick: instanceName + ".setColor(" + x + "," + y + ")"
              }
            }
          }));
        },[]))
      }])
    };
    this.init = function() {
        document.getElementById(widthFieldId).value = data.width;
        document.getElementById(heightFieldId).value = data.height;
        data.palette.forEach(function(color, index) {
          while(document.getElementById("color" + index) === null) {
            this.addColor();
          }
          document.getElementById("color" + index).value = color;
        });
        buildCanvas(data.grid);
        updateSaveData();
    };
    this.addColor = function() {
      data.palette.push("white");
      build(document.getElementById(paletteId),data.palette.map(function(color,n){
        var index = n + 1;
        return {
          tag: "li",
          children: [{
            tag: "input",
            attrs: {
              type: "radio",
              name: "colors",
              id: "colorSelect" + index,
              checked: true,
              value: index
            }
          },{
            tag: "input",
            attrs: {
              type: "text",
              id: "color" + index,
              value: color,
              onChange: instanceName + ".updateColor(" + index + ")"
            }
          }]
        };
      }));
      buildCanvas(data.grid);
    };
    var updateColor = function(index) {
      var colorField = document.getElementById("color" + index);
      var colorObj = document.getElementById("r" + index);
      var fill = colorObj.attributes.getNamedItem("fill");
      fill.value = colorField.value;
      data.color[n] = colorField.value;
      updateSaveData();
    }
    this.resize = function() {
      data.width = document.getElementById(widthFieldId).value;
      data.height = document.getElementById(heightFieldId).value;
      buildCanvas(data.grid);
      updateSaveData();
    };
    this.setColor = function(x, y) {
      console.log("set color: (" + x + "," + y + ")");
      var colorIndex = range(colorCount).map(function(n){
        return document.getElementById("colorSelect" + n);
      }).filter(function(radio,n){
        console.log("checking radio item " + n);
        return radio.checked;
      }).map(function(radio){
        return radio.value;
      })[0];
      var color = ((colorIndex) && (colorIndex > 0))?"#r"+colorIndex:"#r0";
      var id = x + "-" + y;
      var pixel = document.getElementById(id);
      var href = pixel.attributes.getNamedItem("href");
      href.value = "#r" + colorIndex;
      if (colorIndex > 0) {
          data.grid[id] = colorIndex;
      } else {
        delete data.grid[id];
      }
      updateSaveData();
    }
  };
})()
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';

let { computed, Component } = Ember;
let { capitalize, camelize } = Ember.String;

export const ADD_HOOK = 'addComponent';
export const REMOVE_HOOK = 'removeComponent';
const EDITOR_CARD_SUFFIX = '-editor';

function arrayToMap(array, propertyName) {
  let map = Object.create(null);
  array.forEach(item => {
    if (item[propertyName]) {
      item = `is${capitalize(camelize(item[propertyName]))}`;
      map[item] = true;
    }
  });
  return map;
}

export default Component.extend({
  layout,
  tagName: 'article',
  classNames: ['mobiledoc-editor'],

  placeholder: 'Write here...',
  spellcheck: true,
  autofocus: true,

  options: {},

  // merge in named options with the `options` property data bag
  editorOptions: computed(function() {
    let options = this.get('options');

    return Ember.merge({
      placeholder: this.get('placeholder'),
      spellcheck: this.get('spellcheck'),
      autofocus: this.get('autofocus'),
      cards: this.get('cards') || []
    }, options);
  }),

  init() {
    this._super(...arguments);
    let mobiledoc = this.get('mobiledoc');
    if (!mobiledoc) {
      mobiledoc = {
        version: '0.2.0',
        sections: [[], []]
      };
      this.set('mobiledoc', mobiledoc);
    }
    this.set('componentCards', Ember.A([]));
    this.set('linkOffsets', null);
    this.set('activeMarkupTagNames', {});
    this.set('activeSectionTagNames', {});
    this._ignoreCursorDidChange = false;
  },

  actions: {
    toggleMarkup(markupTagName) {
      let editor = this.get('editor');
      editor.run(postEditor => postEditor.toggleMarkup(markupTagName));
    },

    toggleSectionTagName(newTagName) {
      const editor = this.get('editor');
      const sections = editor.activeSections;
      let hasSectionsOfTagName = false;

      editor.run(postEditor => {
        hasSectionsOfTagName = Ember.A(sections).any(
          s => s.tagName === newTagName);

        if (hasSectionsOfTagName) {
          sections.forEach(s => postEditor.resetSectionTagName(s));
        } else {
          sections.forEach(s => postEditor.changeSectionTagName(s, newTagName));
        }
        postEditor.scheduleAfterRender(() => {
          editor.selectSections(sections);
        });
      });
    },

    createListSection(tagName) {
      const editor = this.get('editor');
      const section = editor.activeSections[0];
      if (!section) { return; }

      // can only convert a section *into* an li, do nothing to
      // sections that are already li sections
      if (section.tagName === 'li') { return; }

      const listItem = editor.run(postEditor => {
        const { builder } = postEditor;
        const listItem = builder.createListItem();
        const listSection = builder.createListSection(tagName, [listItem]);
        section.markers.forEach(m => listItem.markers.append(m.clone()));
        postEditor.replaceSection(section, listSection);
        return listItem;
      });

      editor.selectSections([listItem]);
    },

    addCard(cardName, data={}) {
      this._addCard(cardName, data);
    },

    addCardInEditMode(cardName, data={}) {
      let editMode = true;
      this._addCard(cardName, data, editMode);
    },

    toggleLink() {
      let editor = this.get('editor');
      let offsets = editor.cursor.offsets;
      let hasMarkup = editor.detectMarkupInRange(offsets, 'a');
      if (hasMarkup) {
        editor.run(postEditor => {
          postEditor.removeMarkupFromRange(offsets, hasMarkup);
        });
      } else {
        this._ignoreCursorDidChange = true;
        this.set('linkOffsets', offsets);
      }
    },

    completeLink(href) {
      let offsets = this.get('linkOffsets');
      this.set('linkOffsets', null);
      let editor = this.get('editor');
      editor.run(postEditor => {
        let markup = postEditor.builder.createMarkup('a', {
          href: href
        });
        postEditor.addMarkupToRange(offsets, markup);
      });
    },

    cancelLink() {
      this.set('linkOffsets', null);
    }

  },

  editingContexts: computed(function() {
    return Ember.A([]);
  }),

  editor: computed('mobiledoc', 'isEditingDisabled', function() {
    if (this._lastEditor) {
      this._lastEditor.destroy();
      this._lastEditor = null;
    }
    let editor;
    let mobiledoc = this.get('mobiledoc');
    let editorOptions = this.get('editorOptions');

    editorOptions.mobiledoc = mobiledoc;
    editorOptions.cardOptions = {
      [ADD_HOOK]: ({env, options, payload}, isEditing=false) => {
        let cardId = Ember.uuid();
        let cardName = env.name;
        if (isEditing) {
          cardName = cardName + EDITOR_CARD_SUFFIX;
        }
        let destinationElementId = `mobiledoc-editor-card-${cardId}`;
        let element = document.createElement('div');
        element.id = destinationElementId;

        // The data must be copied to avoid sharing the reference
        payload = Ember.copy(payload, true);

        let card = Ember.Object.create({
          destinationElementId,
          cardName,
          data: payload,
          callbacks: env,
          editor,
          postModel: env.postModel
        });
        Ember.run.schedule('afterRender', () => {
          this.get('componentCards').pushObject(card);
        });
        return { card, element };
      },
      [REMOVE_HOOK]: (card) => {
        Ember.run.join(() => {
          this.get('componentCards').removeObject(card);
        });
      }
    };
    editor = new window.Mobiledoc.Editor(editorOptions);
    editor.on('update', () => {
      let updatedMobileDoc = editor.serialize();
      this.sendAction('on-change', updatedMobileDoc);
    });
    editor.cursorDidChange(() => {
      if (this.isDestroyed) { return; }

      const markupTags = arrayToMap(editor.markupsInSelection, 'tagName');
      const sectionTags = arrayToMap(editor.activeSections, 'tagName');

      Ember.run(() => {
        this.set('activeMarkupTagNames', markupTags);
        this.set('activeSectionTagNames', sectionTags);
      });

      let isCursorOffEditor = !this.get('editor').cursor.offsets.head.section;
      if (!isCursorOffEditor && !this._ignoreCursorDidChange) {
        this.set('linkOffsets', null);
      } else {
        this._ignoreCursorDidChange = false;
      }
    });
    if (this.get('isEditingDisabled')) {
      editor.disableEditing();
    }
    this._lastEditor = editor;
    return editor;
  }),

  didRender() {
    let editor = this.get('editor');
    let editorElement = this.$('.mobiledoc-editor__editor')[0];
    if (this._renderedEditor !== editor) {
      this._renderedEditor = editor;
      editor.render(editorElement);
    }
  },

  willDestroyElement() {
    let editor = this.get('editor');
    editor.destroy();
  },

  _addCard(cardName, data, editMode=false) {
    let editor = this.get('editor');
    let section = editor.activeSection;
    editor.run(postEditor => {
      let card = editor.builder.createCardSection(cardName, data);
      if (editMode) {
        editor.editCard(card);
      }
      let nextSection = section && section.next;
      postEditor.insertSectionBefore(editor.post.sections, card, nextSection);
      if (section && section.isBlank) {
        postEditor.removeSection(section);
      }
    });
  }

});
<commit_msg>Pass atoms through to the editor<commit_after>import Ember from 'ember';
import layout from './template';

let { computed, Component } = Ember;
let { capitalize, camelize } = Ember.String;

export const ADD_HOOK = 'addComponent';
export const REMOVE_HOOK = 'removeComponent';
const EDITOR_CARD_SUFFIX = '-editor';

function arrayToMap(array, propertyName) {
  let map = Object.create(null);
  array.forEach(item => {
    if (item[propertyName]) {
      item = `is${capitalize(camelize(item[propertyName]))}`;
      map[item] = true;
    }
  });
  return map;
}

export default Component.extend({
  layout,
  tagName: 'article',
  classNames: ['mobiledoc-editor'],

  placeholder: 'Write here...',
  spellcheck: true,
  autofocus: true,

  options: {},

  // merge in named options with the `options` property data bag
  editorOptions: computed(function() {
    let options = this.get('options');

    return Ember.merge({
      placeholder: this.get('placeholder'),
      spellcheck: this.get('spellcheck'),
      autofocus: this.get('autofocus'),
      cards: this.get('cards') || [],
      atoms: this.get('atoms') || []
    }, options);
  }),

  init() {
    this._super(...arguments);
    let mobiledoc = this.get('mobiledoc');
    if (!mobiledoc) {
      mobiledoc = {
        version: '0.2.0',
        sections: [[], []]
      };
      this.set('mobiledoc', mobiledoc);
    }
    this.set('componentCards', Ember.A([]));
    this.set('linkOffsets', null);
    this.set('activeMarkupTagNames', {});
    this.set('activeSectionTagNames', {});
    this._ignoreCursorDidChange = false;
  },

  actions: {
    toggleMarkup(markupTagName) {
      let editor = this.get('editor');
      editor.run(postEditor => postEditor.toggleMarkup(markupTagName));
    },

    toggleSectionTagName(newTagName) {
      const editor = this.get('editor');
      const sections = editor.activeSections;
      let hasSectionsOfTagName = false;

      editor.run(postEditor => {
        hasSectionsOfTagName = Ember.A(sections).any(
          s => s.tagName === newTagName);

        if (hasSectionsOfTagName) {
          sections.forEach(s => postEditor.resetSectionTagName(s));
        } else {
          sections.forEach(s => postEditor.changeSectionTagName(s, newTagName));
        }
        postEditor.scheduleAfterRender(() => {
          editor.selectSections(sections);
        });
      });
    },

    createListSection(tagName) {
      const editor = this.get('editor');
      const section = editor.activeSections[0];
      if (!section) { return; }

      // can only convert a section *into* an li, do nothing to
      // sections that are already li sections
      if (section.tagName === 'li') { return; }

      const listItem = editor.run(postEditor => {
        const { builder } = postEditor;
        const listItem = builder.createListItem();
        const listSection = builder.createListSection(tagName, [listItem]);
        section.markers.forEach(m => listItem.markers.append(m.clone()));
        postEditor.replaceSection(section, listSection);
        return listItem;
      });

      editor.selectSections([listItem]);
    },

    addCard(cardName, data={}) {
      this._addCard(cardName, data);
    },

    addCardInEditMode(cardName, data={}) {
      let editMode = true;
      this._addCard(cardName, data, editMode);
    },

    toggleLink() {
      let editor = this.get('editor');
      let offsets = editor.cursor.offsets;
      let hasMarkup = editor.detectMarkupInRange(offsets, 'a');
      if (hasMarkup) {
        editor.run(postEditor => {
          postEditor.removeMarkupFromRange(offsets, hasMarkup);
        });
      } else {
        this._ignoreCursorDidChange = true;
        this.set('linkOffsets', offsets);
      }
    },

    completeLink(href) {
      let offsets = this.get('linkOffsets');
      this.set('linkOffsets', null);
      let editor = this.get('editor');
      editor.run(postEditor => {
        let markup = postEditor.builder.createMarkup('a', {
          href: href
        });
        postEditor.addMarkupToRange(offsets, markup);
      });
    },

    cancelLink() {
      this.set('linkOffsets', null);
    }

  },

  editingContexts: computed(function() {
    return Ember.A([]);
  }),

  editor: computed('mobiledoc', 'isEditingDisabled', function() {
    if (this._lastEditor) {
      this._lastEditor.destroy();
      this._lastEditor = null;
    }
    let editor;
    let mobiledoc = this.get('mobiledoc');
    let editorOptions = this.get('editorOptions');

    editorOptions.mobiledoc = mobiledoc;
    editorOptions.cardOptions = {
      [ADD_HOOK]: ({env, options, payload}, isEditing=false) => {
        let cardId = Ember.uuid();
        let cardName = env.name;
        if (isEditing) {
          cardName = cardName + EDITOR_CARD_SUFFIX;
        }
        let destinationElementId = `mobiledoc-editor-card-${cardId}`;
        let element = document.createElement('div');
        element.id = destinationElementId;

        // The data must be copied to avoid sharing the reference
        payload = Ember.copy(payload, true);

        let card = Ember.Object.create({
          destinationElementId,
          cardName,
          data: payload,
          callbacks: env,
          editor,
          postModel: env.postModel
        });
        Ember.run.schedule('afterRender', () => {
          this.get('componentCards').pushObject(card);
        });
        return { card, element };
      },
      [REMOVE_HOOK]: (card) => {
        Ember.run.join(() => {
          this.get('componentCards').removeObject(card);
        });
      }
    };
    editor = new window.Mobiledoc.Editor(editorOptions);
    editor.on('update', () => {
      let updatedMobileDoc = editor.serialize();
      this.sendAction('on-change', updatedMobileDoc);
    });
    editor.cursorDidChange(() => {
      if (this.isDestroyed) { return; }

      const markupTags = arrayToMap(editor.markupsInSelection, 'tagName');
      const sectionTags = arrayToMap(editor.activeSections, 'tagName');

      Ember.run(() => {
        this.set('activeMarkupTagNames', markupTags);
        this.set('activeSectionTagNames', sectionTags);
      });

      let isCursorOffEditor = !this.get('editor').cursor.offsets.head.section;
      if (!isCursorOffEditor && !this._ignoreCursorDidChange) {
        this.set('linkOffsets', null);
      } else {
        this._ignoreCursorDidChange = false;
      }
    });
    if (this.get('isEditingDisabled')) {
      editor.disableEditing();
    }
    this._lastEditor = editor;
    return editor;
  }),

  didRender() {
    let editor = this.get('editor');
    let editorElement = this.$('.mobiledoc-editor__editor')[0];
    if (this._renderedEditor !== editor) {
      this._renderedEditor = editor;
      editor.render(editorElement);
    }
  },

  willDestroyElement() {
    let editor = this.get('editor');
    editor.destroy();
  },

  _addCard(cardName, data, editMode=false) {
    let editor = this.get('editor');
    let section = editor.activeSection;
    editor.run(postEditor => {
      let card = editor.builder.createCardSection(cardName, data);
      if (editMode) {
        editor.editCard(card);
      }
      let nextSection = section && section.next;
      postEditor.insertSectionBefore(editor.post.sections, card, nextSection);
      if (section && section.isBlank) {
        postEditor.removeSection(section);
      }
    });
  }

});
<|endoftext|>