<commit_before>var request = require('request'),
  qs = require('querystring'),
  helpers = require('./helpers');

/**
 * hubspot API wrapper for the API version 3. This object should not be
 * instantiated directly but by using the version wrapper {@link hubspotAPI}.
 *
 * @param options Configuration options
 * @return Instance of {@link hubspotAPI}
 */
function hubspotAPI(options) {

  if (!options) {
    throw new Error('You have to provide a authentication details for this to work.');
  }

  if (!options.api_key && !options.access_token) {
    throw new Error('API requires api_key or access_token');
  }

  /**
   * Authenticate using either the API key or with oauth but not both.
   */
  if (options.api_key) {

    /**
     * if user has api_key, ignore oauth stuff.
     */

    this.api_key = options.api_key;
  } else {

    this.access_token = options.access_token;
  }

  this.httpUri = 'https://api.hubapi.com';
  this.DEBUG = options.DEBUG || false;
  this.contentType = options.contentType || 'application/json';
  this.userAgent = options.userAgent || 'node-hubspot';
}

module.exports = hubspotAPI;

/**
 * Sends a given request as a JSON object to the hubspot API and finally
 * calls the given callback function with the resulting JSON object. This
 * method should not be called directly but will be used internally by all API
 * methods defined.
 *
 * @param resource hubspot API resource to call
 * @param method hubspot API method to call
 * @param availableParams Parameters available for the specified API method
 * @param givenParams Parameters to call the hubspot API with
 * @param callback Callback function to call on success
 */
hubspotAPI.prototype.execute = function (verb, path, availableParams, givenParams, callback) {
  var self = this,
    headers,
    uri,
    body,
    finalParams,
    currentParam,
    parsedResponse,
    requestOptions;

  headers = {
    "Content-Type": this.contentType,
    "User-Agent": this.userAgent
  };

  uri = this.httpUri + '/' + path;

  finalParams = {};

  for (var i = 0; i < availableParams.length; i++) {
    currentParam = availableParams[i];
    if (typeof givenParams[currentParam] !== 'undefined')
      finalParams[currentParam] = givenParams[currentParam];
  }

  /**
   * For OAuth: &access_token=TOKEN
   * For API Keys: &hapikey=KEY
   * @see http://developers.hubspot.com/auth/oauth_overview
   */
  if (this.api_key) {
    finalParams.hapikey = this.api_key;
  }

  if (this.access_token) {
    finalParams.access_token = this.access_token;
  }

  // some endpoints use array-like parameters that must be stringified.
  // also must user querystring instead of qs.
  // qs output is param[0]=a&param[1]=b&param[2]=c
  // querystring output is param=a&param=b&param=c and this is required.
  uri = uri + "?" + qs.stringify(finalParams)

  requestOptions = {
    uri: uri,
    method: verb,
    headers: headers
  };

  if (verb === "POST") {
    if (typeof givenParams == 'string') {
      requestOptions.body = givenParams;
    } else {
      requestOptions.form = finalParams;
    }
  }

  if (self.DEBUG) {
    console.log("req", requestOptions);
  }

  request(requestOptions, function (error, res, body) {
    if (self.DEBUG) {
      console.log("error", error);
      console.log("res statusCode", res.statusCode);
      console.log("body", body);
    }
    if (error) {
      return callback(new Error('Unable to connect to the hubspot API endpoint.'));
    }

    if (helpers.isAnError(res.statusCode)) {
      return callback(helpers.createHubspotError(body, res.statusCode));
    }

    try {
      parsedResponse = JSON.parse(body);
    } catch (error) {
      return callback(new Error('Error parsing JSON answer from hubspot API.'));
    }

    if (parsedResponse.status === "error" || helpers.isAnError(res.statusCode)) {
      return callback(helpers.createHubspotError(parsedResponse, res.statusCode));
    }

    return callback(null, parsedResponse);
  });

};

hubspotAPI.prototype.get = function (path, availableParams, givenParams, callback) {
  this.execute("GET", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.post = function (path, availableParams, givenParams, callback) {
  this.execute("POST", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.put = function (path, availableParams, givenParams, callback) {
  this.execute("PUT", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.patch = function (path, availableParams, givenParams, callback) {
  this.execute("PATCH", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.delete = function (path, availableParams, givenParams, callback) {
  this.execute("DELETE", path, availableParams, givenParams, callback);
};

/*****************************************************************************/
/************************* EVENT Methods *************************************/
/*****************************************************************************/

// un-published API endpoint.
hubspotAPI.prototype.event_completions = function (params, callback) {
  var path = "analytics/v2/event/completions/total",
    availableParams = [
      "offset"
    ];

  this.post(path, availableParams, params, callback);
};

hubspotAPI.prototype.events = function (params, callback) {
  var path = "reports/v1/events",
    availableParams = [];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* SOURCES Methods ***********************************/
/*****************************************************************************/

// un-published API endpoint.
hubspotAPI.prototype.sources_daily = function (params, callback) {
  var path = "analytics/v2/sources/summary/daily",
    availableParams = [];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* PAGES Methods *************************************/
/*****************************************************************************/

/*****************************************************************************/
/************************* CONTACTS Methods **********************************/
/*****************************************************************************/

/**
 * http://developers.hubspot.com/docs/methods/contacts/get_contacts
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_statistics = function (params, callback) {
  var path = "contacts/v1/contacts/statistics",
    availableParams = [];
  this.get(path, availableParams, params, callback);
};

/**
 * http://developers.hubspot.com/docs/methods/contacts/get_contacts
 * contacts/v1/lists/all/contacts/all
 * @param params
 * @param callback
 */

hubspotAPI.prototype.all_contacts = function (params, callback) {
  var path = "contacts/v1/lists/all/contacts/all",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ],
    defaultProps = [
      'city',
      'zip',
      'closedate',
      'company',
      'conversion',
      'createdate',
      'days_to_close',
      'hs_analytics_num_visits',
      'hs_analytics_last_visit_timestamp',
      'hs_email_first_open_date',
      'email',
      'first_conversion_date',
      'firstname',
      'hubspotscore',
      'lastmodifieddate',
      'lastname',
      'lifecyclestage',
      'hs_lifecyclestage_customer_date',
      'hs_lifecyclestage_marketingqualifiedlead_date',
      'hs_lifecyclestage_subscriber_date',
      'hs_lifecyclestage_salesqualifiedlead_date',
      'website'
    ];

  if (params.property && Array.isArray(params.property)) {
    params.property = helpers.unique(params.property.concat(defaultProps))
  } else {
    params.property = defaultProps;
  }
  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/contact
 */
hubspotAPI.prototype.contacts_contact = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/contact",
    availableParams = [

    ];

  var properties = [];
  for (var key in params) {
    properties.push({
      property: key,
      value: params[key]
    });
  }

  params = JSON.stringify({
    properties: properties
  });

  this.post(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists
 */
hubspotAPI.prototype.contacts_lists = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/lists",
    availableParams = [
      "count",
      "offset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists/static
 */
hubspotAPI.prototype.contacts_static_lists = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/lists/static",
    availableParams = [
      "count",
      "offset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists/:list_id/add
 */
hubspotAPI.prototype.contacts_lists_add = function (params, callback) {
  var version = params.version ? params.version : "v1";
  var list_id = params['list_id'];
  var contact_id = params['contact_id'];

  var path = "contacts/" + version + "/lists/" + list_id + "/add";
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.post(path, availableParams, JSON.stringify({'vids':[contact_id]}), callback);
};

/**
 * contacts/v1/properties
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_properties = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/properties",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/forms and contacts/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_forms = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/forms",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* WORKFLOWS Methods *************************************/
/*****************************************************************************/
/**
 * automation/v2/workflows
 * @param params
 * @param callback
 */
hubspotAPI.prototype.automation_workflows = function (params, callback) {
  var path = "automation/v2/workflows",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* LEADS Methods *************************************/
/*****************************************************************************/

/**
 * leads/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.leads_forms = function (params, callback) {
  var path = "leads/v2/forms",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* PROPECTS Methods **********************************/
/*****************************************************************************/

/**
 * leads/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.prospects = function (params, callback) {
  var path = "prospects/v1/timeline",
    availableParams = [
      "timeOffset",
      "orgOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* SETTINGS Methods **********************************/
/*****************************************************************************/

//http://developers.hubspot.com/docs/methods/settings/get_settings
hubspotAPI.prototype.settings = function (params, callback) {
  var verb = params.verb ? params.verb : "get";

  var path = "settings/v1/settings",
    availableParams = [
      "sm",
      "name",
      "value",
      "domains",
      "readOnly"
    ];

  this[verb](path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* EMAIL Methods **********************************/
/*****************************************************************************/

//These are un-documented - use at your own risk.
hubspotAPI.prototype.cosemail = function (params, callback) {
  var path = "cosemail/v1/emaildashboard";
  var availableParams = [
    "limit",
    "offset",
    "property",
  ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* AUTH Methods **********************************/
/*****************************************************************************/

//These are un-documented - use at your own risk.
hubspotAPI.prototype.refresh = function (params, callback) {
  var path = "auth/v1/refresh";
  var availableParams = [
    "refresh_token",
    "client_id",
    "grant_type",
  ];

  if (!params) {
    params = {};
  }
  params.grant_type = "refresh_token";

  this.post(path, availableParams, params, callback);
};

<commit_msg>decode gzip<commit_after>var request = require('request'),
  qs = require('querystring'),
  helpers = require('./helpers');

/**
 * hubspot API wrapper for the API version 3. This object should not be
 * instantiated directly but by using the version wrapper {@link hubspotAPI}.
 *
 * @param options Configuration options
 * @return Instance of {@link hubspotAPI}
 */
function hubspotAPI(options) {

  if (!options) {
    throw new Error('You have to provide a authentication details for this to work.');
  }

  if (!options.api_key && !options.access_token) {
    throw new Error('API requires api_key or access_token');
  }

  /**
   * Authenticate using either the API key or with oauth but not both.
   */
  if (options.api_key) {

    /**
     * if user has api_key, ignore oauth stuff.
     */

    this.api_key = options.api_key;
  } else {

    this.access_token = options.access_token;
  }

  this.httpUri = 'https://api.hubapi.com';
  this.DEBUG = options.DEBUG || false;
  this.contentType = options.contentType || 'application/json';
  this.userAgent = options.userAgent || 'node-hubspot';
}

module.exports = hubspotAPI;

/**
 * Sends a given request as a JSON object to the hubspot API and finally
 * calls the given callback function with the resulting JSON object. This
 * method should not be called directly but will be used internally by all API
 * methods defined.
 *
 * @param resource hubspot API resource to call
 * @param method hubspot API method to call
 * @param availableParams Parameters available for the specified API method
 * @param givenParams Parameters to call the hubspot API with
 * @param callback Callback function to call on success
 */
hubspotAPI.prototype.execute = function (verb, path, availableParams, givenParams, callback) {
  var self = this,
    headers,
    uri,
    body,
    finalParams,
    currentParam,
    parsedResponse,
    requestOptions;

  headers = {
    "Content-Type": this.contentType,
    "User-Agent": this.userAgent
  };

  uri = this.httpUri + '/' + path;

  finalParams = {};

  for (var i = 0; i < availableParams.length; i++) {
    currentParam = availableParams[i];
    if (typeof givenParams[currentParam] !== 'undefined')
      finalParams[currentParam] = givenParams[currentParam];
  }

  /**
   * For OAuth: &access_token=TOKEN
   * For API Keys: &hapikey=KEY
   * @see http://developers.hubspot.com/auth/oauth_overview
   */
  if (this.api_key) {
    finalParams.hapikey = this.api_key;
  }

  if (this.access_token) {
    finalParams.access_token = this.access_token;
  }

  // some endpoints use array-like parameters that must be stringified.
  // also must user querystring instead of qs.
  // qs output is param[0]=a&param[1]=b&param[2]=c
  // querystring output is param=a&param=b&param=c and this is required.
  uri = uri + "?" + qs.stringify(finalParams)

  requestOptions = {
    uri: uri,
    method: verb,
    headers: headers,
    gzip: true
  };

  if (verb === "POST") {
    if (typeof givenParams == 'string') {
      requestOptions.body = givenParams;
    } else {
      requestOptions.form = finalParams;
    }
  }

  if (self.DEBUG) {
    console.log("req", requestOptions);
  }

  request(requestOptions, function (error, res, body) {
    if (self.DEBUG) {
      console.log("error", error);
      console.log("res statusCode", res.statusCode);
      console.log("body", body);
    }
    if (error) {
      return callback(new Error('Unable to connect to the hubspot API endpoint.'));
    }

    if (helpers.isAnError(res.statusCode)) {
      return callback(helpers.createHubspotError(body, res.statusCode));
    }

    try {
      parsedResponse = JSON.parse(body);
    } catch (error) {
      return callback(new Error('Error parsing JSON answer from hubspot API.'));
    }

    if (parsedResponse.status === "error" || helpers.isAnError(res.statusCode)) {
      return callback(helpers.createHubspotError(parsedResponse, res.statusCode));
    }

    return callback(null, parsedResponse);
  });

};

hubspotAPI.prototype.get = function (path, availableParams, givenParams, callback) {
  this.execute("GET", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.post = function (path, availableParams, givenParams, callback) {
  this.execute("POST", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.put = function (path, availableParams, givenParams, callback) {
  this.execute("PUT", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.patch = function (path, availableParams, givenParams, callback) {
  this.execute("PATCH", path, availableParams, givenParams, callback);
};

hubspotAPI.prototype.delete = function (path, availableParams, givenParams, callback) {
  this.execute("DELETE", path, availableParams, givenParams, callback);
};

/*****************************************************************************/
/************************* EVENT Methods *************************************/
/*****************************************************************************/

// un-published API endpoint.
hubspotAPI.prototype.event_completions = function (params, callback) {
  var path = "analytics/v2/event/completions/total",
    availableParams = [
      "offset"
    ];

  this.post(path, availableParams, params, callback);
};

hubspotAPI.prototype.events = function (params, callback) {
  var path = "reports/v1/events",
    availableParams = [];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* SOURCES Methods ***********************************/
/*****************************************************************************/

// un-published API endpoint.
hubspotAPI.prototype.sources_daily = function (params, callback) {
  var path = "analytics/v2/sources/summary/daily",
    availableParams = [];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* PAGES Methods *************************************/
/*****************************************************************************/

/*****************************************************************************/
/************************* CONTACTS Methods **********************************/
/*****************************************************************************/

/**
 * http://developers.hubspot.com/docs/methods/contacts/get_contacts
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_statistics = function (params, callback) {
  var path = "contacts/v1/contacts/statistics",
    availableParams = [];
  this.get(path, availableParams, params, callback);
};

/**
 * http://developers.hubspot.com/docs/methods/contacts/get_contacts
 * contacts/v1/lists/all/contacts/all
 * @param params
 * @param callback
 */

hubspotAPI.prototype.all_contacts = function (params, callback) {
  var path = "contacts/v1/lists/all/contacts/all",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ],
    defaultProps = [
      'city',
      'zip',
      'closedate',
      'company',
      'conversion',
      'createdate',
      'days_to_close',
      'hs_analytics_num_visits',
      'hs_analytics_last_visit_timestamp',
      'hs_email_first_open_date',
      'email',
      'first_conversion_date',
      'firstname',
      'hubspotscore',
      'lastmodifieddate',
      'lastname',
      'lifecyclestage',
      'hs_lifecyclestage_customer_date',
      'hs_lifecyclestage_marketingqualifiedlead_date',
      'hs_lifecyclestage_subscriber_date',
      'hs_lifecyclestage_salesqualifiedlead_date',
      'website'
    ];

  if (params.property && Array.isArray(params.property)) {
    params.property = helpers.unique(params.property.concat(defaultProps))
  } else {
    params.property = defaultProps;
  }
  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/contact
 */
hubspotAPI.prototype.contacts_contact = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/contact",
    availableParams = [

    ];

  var properties = [];
  for (var key in params) {
    properties.push({
      property: key,
      value: params[key]
    });
  }

  params = JSON.stringify({
    properties: properties
  });

  this.post(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists
 */
hubspotAPI.prototype.contacts_lists = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/lists",
    availableParams = [
      "count",
      "offset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists/static
 */
hubspotAPI.prototype.contacts_static_lists = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/lists/static",
    availableParams = [
      "count",
      "offset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/lists/:list_id/add
 */
hubspotAPI.prototype.contacts_lists_add = function (params, callback) {
  var version = params.version ? params.version : "v1";
  var list_id = params['list_id'];
  var contact_id = params['contact_id'];

  var path = "contacts/" + version + "/lists/" + list_id + "/add";
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.post(path, availableParams, JSON.stringify({'vids':[contact_id]}), callback);
};

/**
 * contacts/v1/properties
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_properties = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/properties",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/**
 * contacts/v1/forms and contacts/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.contacts_forms = function (params, callback) {
  var version = params.version ? params.version : "v1";

  var path = "contacts/" + version + "/forms",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* WORKFLOWS Methods *************************************/
/*****************************************************************************/
/**
 * automation/v2/workflows
 * @param params
 * @param callback
 */
hubspotAPI.prototype.automation_workflows = function (params, callback) {
  var path = "automation/v2/workflows",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* LEADS Methods *************************************/
/*****************************************************************************/

/**
 * leads/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.leads_forms = function (params, callback) {
  var path = "leads/v2/forms",
    availableParams = [
      "count",
      "property",
      "vidOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* PROPECTS Methods **********************************/
/*****************************************************************************/

/**
 * leads/v2/forms
 * @param params
 * @param callback
 */
hubspotAPI.prototype.prospects = function (params, callback) {
  var path = "prospects/v1/timeline",
    availableParams = [
      "timeOffset",
      "orgOffset"
    ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* SETTINGS Methods **********************************/
/*****************************************************************************/

//http://developers.hubspot.com/docs/methods/settings/get_settings
hubspotAPI.prototype.settings = function (params, callback) {
  var verb = params.verb ? params.verb : "get";

  var path = "settings/v1/settings",
    availableParams = [
      "sm",
      "name",
      "value",
      "domains",
      "readOnly"
    ];

  this[verb](path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* EMAIL Methods **********************************/
/*****************************************************************************/

//These are un-documented - use at your own risk.
hubspotAPI.prototype.cosemail = function (params, callback) {
  var path = "cosemail/v1/emaildashboard";
  var availableParams = [
    "limit",
    "offset",
    "property",
  ];

  this.get(path, availableParams, params, callback);
};

/*****************************************************************************/
/************************* AUTH Methods **********************************/
/*****************************************************************************/

//These are un-documented - use at your own risk.
hubspotAPI.prototype.refresh = function (params, callback) {
  var path = "auth/v1/refresh";
  var availableParams = [
    "refresh_token",
    "client_id",
    "grant_type",
  ];

  if (!params) {
    params = {};
  }
  params.grant_type = "refresh_token";

  this.post(path, availableParams, params, callback);
};

<|endoftext|>


<commit_before>var IEditor = (function() {

    /*
     * Input is idea of document body
     */
    function IEditor(editorPlace, terminalPlace) {

        var esprima_options = {
            comment: false,
            raw: false,
            range: false,
            loc: true
        };
        // good timer between series of input
        var parserTimeout = 1000; //ms
        var timerId;
        var isAutoFormatted = false;

        function parse() {
            // clear out timer id
            timerId = undefined;
            try {
                var tree = esprima.parse(editor.getValue(), esprima_options);
                var result = Tracer.trace(tree);
                Format.align(editor, result.snapshot);
                //isAutoFormatted = true;
                //editor.setValue(result.code);

            } catch (e) { }
        }

        function editorOnChange(editor, changes) {
            if (isAutoFormatted) {
                isAutoFormatted = false;
            }
            else {
                if (timerId !== undefined) {
                    window.clearTimeout(timerId);
                }

                // create new timer
                timerId = window.setTimeout(parse, parserTimeout);
            }
        }

        function terminalOnChange(terminal, changes) {
        }

        var editorTextArea = document.getElementById(editorPlace);
        var terminalTextArea = document.getElementById(terminalPlace);

        if (!editorTextArea) {
            console.log("editor element doesn't exist.");
            return;
        }

        if (!terminalTextArea) {
            console.log("terminal element doesn't exist.");
            return;
        }

        var editor = CodeMirror.fromTextArea(editorTextArea, {
            mode: "javascript",
            indentUnit: 4,
            lineNumbers: true,
            matchBrackets: true,
            onChange: editorOnChange
        });

        var terminal = CodeMirror.fromTextArea(terminalTextArea, {
            mode: "javascript",
            onChange: terminalOnChange
        });

        return {editor: editor, terminal: terminal};

    }

    return IEditor;
})();
<commit_msg>get cursor location before format<commit_after>var IEditor = (function() {

    /*
     * Input is idea of document body
     */
    function IEditor(editorPlace, terminalPlace) {

        var esprima_options = {
            comment: false,
            raw: false,
            range: false,
            loc: true
        };
        // good timer between series of input
        var parserTimeout = 1000; //ms
        var timerId;
        var isAutoFormatted = false;

        function parse() {
            // clear out timer id
            timerId = undefined;
            try {
                var tree = esprima.parse(editor.getValue(), esprima_options);
                var result = Tracer.trace(tree);
                Format.align(editor, result.snapshot);
                //isAutoFormatted = true;
                //editor.setValue(result.code);
                //var curloc = editor.getCursor();

            } catch (e) { }
        }

        function editorOnChange(editor, changes) {
            if (isAutoFormatted) {
                isAutoFormatted = false;
            }
            else {
                if (timerId !== undefined) {
                    window.clearTimeout(timerId);
                }

                // create new timer
                timerId = window.setTimeout(parse, parserTimeout);
            }
        }

        function terminalOnChange(terminal, changes) {
        }

        var editorTextArea = document.getElementById(editorPlace);
        var terminalTextArea = document.getElementById(terminalPlace);

        if (!editorTextArea) {
            console.log("editor element doesn't exist.");
            return;
        }

        if (!terminalTextArea) {
            console.log("terminal element doesn't exist.");
            return;
        }

        var editor = CodeMirror.fromTextArea(editorTextArea, {
            mode: "javascript",
            indentUnit: 4,
            lineNumbers: true,
            matchBrackets: true,
            onChange: editorOnChange
        });

        var terminal = CodeMirror.fromTextArea(terminalTextArea, {
            mode: "javascript",
            onChange: terminalOnChange
        });

        return {editor: editor, terminal: terminal};

    }

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


<commit_before>var Transform = require('pipestream').Transform;
var EventEmitter = require('events').EventEmitter;
var util = require('../../util');
var config = util.config;
var TIMEOUT = config.timeout || 36000;
var KEYS = ['statusCode', 'httpVersion', 'headers', 'trailers',
            'method', 'httpVersionMajo', 'httpVersionMino', 'upgrade'];

function addDataEvents(req, res, proxy) {
	if (req._fromProxy || !EventEmitter.listenerCount(proxy, 'request')) {
		return;
	}

	var request = new Transform();
	var response = new Transform();
	var emitted;

	function emitError(obj, err) {
		if (emitted) {
			return;
		}
		emitted = true;
		util.emitErrorIfExist(obj, err);
	}

	function emitReqError(err) {
		emitError(request, err);
	}

	function emitResError(err) {
		emitError(response, err);
	}

	req.on('dest', function(_req) {
		_req.on('error', emitReqError);
	}).on('error', emitReqError)
	.on('close', emitReqError);

	res.on('src', function(_res) {
		_res.on('error', emitResError);
	}).on('error', emitResError);

	req.append(request, {pipeError: false});
	res.append(response, {pipeError: false});

	KEYS.forEach(function(key) {
		request[key] = req[key];
	});
	request.url = util.getFullUrl(req);
	request.path = req.url;
	proxy.emit('request', request);

	res.on('src', function() {
		response.headers = res.headers;
		response.host = req.hostIp || '127.0.0.1';
		request.emit('response', response);
	});

}

function addTimeout(req, res, timeout) {
	if (!(timeout > 0)) {
		return;
	}
	var timeoutId, responsed;
	var preReq = new Transform();
	var endReq = new Transform();
	var preRes = new Transform();
	var endRes = new Transform();

	preReq._transform = preRes._transform = function(chunk, encoding, callback) {
		timeoutId && clearTimeout(timeoutId);
		timeoutId = null;
		callback(null, chunk);
	};

	endReq._transform = endRes._transform = function(chunk, encoding, callback) {
		timeoutId && clearTimeout(timeoutId);
		if (!responsed || chunk) {
			timeoutId = setTimeout(emitTimeoutError, timeout);
		}

		if (!chunk) {
			responsed = true;
		}

		callback(null, chunk);
	};

	function emitTimeoutError() {
		util.emitErrorIfExist(responsed ? res : req, new Error('_Timeout..'));
	}

	req.prepend(preReq).append(endReq);
	res.prepend(preRes).append(endRes);
}

module.exports = function(req, res, next) {
	addDataEvents(req, res, this);
	var timeout = req.timeout; //从req里面获取
	addTimeout(req, res, timeout || TIMEOUT);
	next();
};

<commit_msg>emit error<commit_after>var Transform = require('pipestream').Transform;
var EventEmitter = require('events').EventEmitter;
var util = require('../../util');
var config = util.config;
var TIMEOUT = config.timeout || 36000;
var KEYS = ['statusCode', 'httpVersion', 'headers', 'trailers',
            'method', 'httpVersionMajo', 'httpVersionMino', 'upgrade'];

function addDataEvents(req, res, proxy) {
	if (req._fromProxy || !EventEmitter.listenerCount(proxy, 'request')) {
		return;
	}

	var request = new Transform();
	var response = new Transform();
	var emitted;

	function emitError(obj, err) {
		if (emitted) {
			return;
		}
		emitted = true;
		util.emitErrorIfExist(obj, err);
	}

	function emitReqError(err) {
		emitError(request, err);
	}

	function emitResError(err) {
		emitError(response, err);
	}

	req.on('dest', function(_req) {
		_req.on('error', emitReqError);
	}).on('error', emitReqError)
	.on('close', emitReqError);

	res.on('src', function(_res) {
		_res.on('error', emitResError);
	}).on('error', emitResError);

	req.append(request, {pipeError: false});
	res.append(response, {pipeError: false});

	KEYS.forEach(function(key) {
		request[key] = req[key];
	});
	request.url = util.getFullUrl(req);
	request.path = req.url;
	proxy.emit('request', request);

	res.on('src', function() {
		response.headers = res.headers;
		response.host = req.hostIp || '127.0.0.1';
		request.emit('response', response);
	});

}

function addTimeout(req, res, timeout) {
	if (!(timeout > 0)) {
		return;
	}
	var timeoutId, responsed;
	var preReq = new Transform();
	var endReq = new Transform();
	var preRes = new Transform();
	var endRes = new Transform();

	preReq._transform = preRes._transform = function(chunk, encoding, callback) {
		timeoutId && clearTimeout(timeoutId);
		timeoutId = null;
		callback(null, chunk);
	};

	endReq._transform = endRes._transform = function(chunk, encoding, callback) {
		timeoutId && clearTimeout(timeoutId);
		if (!responsed || chunk) {
			timeoutId = setTimeout(emitTimeoutError, timeout);
		}

		if (!chunk) {
			responsed = true;
		}

		callback(null, chunk);
	};

	function emitTimeoutError() {
		util.emitErrorIfExist(responsed ? res : req, new Error('timeout!!'));
	}

	req.prepend(preReq).append(endReq);
	res.prepend(preRes).append(endRes);
}

module.exports = function(req, res, next) {
	addDataEvents(req, res, this);
	var timeout = req.timeout; //从req里面获取
	addTimeout(req, res, timeout || TIMEOUT);
	next();
};

<|endoftext|>


<commit_before>const KeenTracking = require('keen-tracking');

const client = new KeenTracking({
  projectId: process.env.KEEN_PROJECT_ID,
  writeKey: process.env.KEEN_WRITE_KEY
});

module.exports = (req, res, next) => {

  // Setup event data
  const eventData = {
    method: req.method,
    url: {
      string: `${req.protocol}://${req.headers.host}${req.originalUrl}`
    },
    ip: req.ip,
    userAgent: {
      string: req.headers['user-agent']
    },
    referrer: {
      url: req.headers.referer
    }
  };

  // Enable keen date time addon
  eventData.keen = {
    addons: [
      {
        name: 'keen:date_time_parser',
        input: {
          date_time: 'keen.timestamp',
        },
        output: 'timestamp_info'
      }
    ]
  };

  // Only enable other keen addons if we have the required input
  const keenAddons = [
    {
      name: 'keen:url_parser',
      input: {
        url: 'url.string'
      },
      output: 'url.components'
    },
    {
      name: 'keen:ip_to_geo',
      input: {
        ip: 'ip'
      },
      output: 'location'
    },
    {
      name: 'keen:ua_parser',
      input: {
        ua_string: 'userAgent.string'
      },
      output: 'userAgent.info'
    },
    {
      name: 'keen:referrer_parser',
      input: {
        referrer_url: 'referrer.url',
        page_url: 'url.string'
      },
      output: 'referrer.info'
    }
  ];
  keenAddons.forEach(addon => {
    const hasRequiredProperties = Object
      .keys(addon.input)
      .map(key => addon.input[key])
      .every(requiredProp => requiredProp.split('.').reduce((obj, i) => obj[i], eventData));

    if(hasRequiredProperties) {
      eventData.keen.addons.push(addon);
    }
  });

  // Send event data
  client.recordEvent('pageviewsv2', eventData);
  next();
}
<commit_msg>Parse ip to ipv4<commit_after>const KeenTracking = require('keen-tracking');

const client = new KeenTracking({
  projectId: process.env.KEEN_PROJECT_ID,
  writeKey: process.env.KEEN_WRITE_KEY
});

module.exports = (req, res, next) => {

  // Setup event data
  const eventData = {
    method: req.method,
    url: {
      string: `${req.protocol}://${req.headers.host}${req.originalUrl}`
    },
    ip: req.ip.substr(0, 7) == '::ffff:' ? req.ip.substr(7) : req.ip,
    userAgent: {
      string: req.headers['user-agent']
    },
    referrer: {
      url: req.headers.referer
    }
  };

  // Enable keen date time addon
  eventData.keen = {
    addons: [
      {
        name: 'keen:date_time_parser',
        input: {
          date_time: 'keen.timestamp',
        },
        output: 'timestamp_info'
      }
    ]
  };

  // Only enable other keen addons if we have the required input
  const keenAddons = [
    {
      name: 'keen:url_parser',
      input: {
        url: 'url.string'
      },
      output: 'url.components'
    },
    {
      name: 'keen:ip_to_geo',
      input: {
        ip: 'ip'
      },
      output: 'location'
    },
    {
      name: 'keen:ua_parser',
      input: {
        ua_string: 'userAgent.string'
      },
      output: 'userAgent.info'
    },
    {
      name: 'keen:referrer_parser',
      input: {
        referrer_url: 'referrer.url',
        page_url: 'url.string'
      },
      output: 'referrer.info'
    }
  ];
  keenAddons.forEach(addon => {
    const hasRequiredProperties = Object
      .keys(addon.input)
      .map(key => addon.input[key])
      .every(requiredProp => requiredProp.split('.').reduce((obj, i) => obj[i], eventData));

    if(hasRequiredProperties) {
      eventData.keen.addons.push(addon);
    }
  });

  // Send event data
  client.recordEvent('pageviewsv2', eventData);
  next();
}
<|endoftext|>


<commit_before>var _ = require('underscore'),
    fs = require('fs'),
    nconf = require('nconf');

// ### Default configuration settings
// This could go in `kumascript_settings.json` in the parent project.
var DEFAULT_CONFIG = {
    log: {
        console: false,
        file: {
            filename: 'kumascript.log',
            maxsize: 1024 * 100, // 100k
            maxFiles: 5
        }
    },
    statsd: {
        enabled: false,
        host: '127.0.0.1',
        port: 8125
    },
    newrelic: {
        high_security: true,
        app_name: ['developer-local.allizom.org-kumascript'],
        license_key: '',
        logging: {
            level: 'info'
        }
    },
    server: {
        port: 9080,
        numWorkers: 4,
        workerConcurrency: 4,
        workerTimeout: 1000 * 60,
        workerMaxJobs: 8,
        workerRetries: 3,
        document_url_template:
            "https://developer.mozilla.org/en-US/docs/{path}?raw=1",
        template_url_template:
            "https://developer.mozilla.org/en-US/docs/en-US/Template:{name}?raw=1",
        template_cache_control: 'max-age=3600'
    },
    repl: {
        enabled: true,
        host: "127.0.0.1",
        port: 9070
    }
};

// ### Initialize configuration
//
// Attempt to load from a prioritized series of configuration files.
//
// 1. Environ var `KUMASCRIPT_CONFIG`
// 2. `kumascript_settings_local.json` in current dir
// 3. `kumascript_settings.json` in current dir
var cwd = process.cwd(),
    conf_fns = [
        cwd + '/kumascript_settings.json',
        cwd + '/kumascript_settings_local.json',
        process.env.KUMASCRIPT_CONFIG
    ];
_.each(conf_fns, function (conf_fn) {
    if (!conf_fn) { return; }
    try { fs.statSync(conf_fn).isFile(); }
    catch (e) { return; }
    nconf.file({ file: conf_fn });
});

// Include the fallback defaults.
nconf.defaults(DEFAULT_CONFIG);

module.exports = {
    nconf: nconf
};
<commit_msg>bug 1218563: Load config from environment<commit_after>var _ = require('underscore'),
    fs = require('fs'),
    nconf = require('nconf');

// ### Default configuration settings
// This could go in `kumascript_settings.json` in the parent project.
var DEFAULT_CONFIG = {
    log: {
        console: false,
        file: {
            filename: 'kumascript.log',
            maxsize: 1024 * 100, // 100k
            maxFiles: 5
        }
    },
    statsd: {
        enabled: false,
        host: '127.0.0.1',
        port: 8125
    },
    newrelic: {
        high_security: true,
        app_name: ['developer-local.allizom.org-kumascript'],
        license_key: '',
        logging: {
            level: 'info'
        }
    },
    server: {
        port: 9080,
        numWorkers: 4,
        workerConcurrency: 4,
        workerTimeout: 1000 * 60,
        workerMaxJobs: 8,
        workerRetries: 3,
        document_url_template:
            "https://developer.mozilla.org/en-US/docs/{path}?raw=1",
        template_url_template:
            "https://developer.mozilla.org/en-US/docs/en-US/Template:{name}?raw=1",
        template_cache_control: 'max-age=3600'
    },
    repl: {
        enabled: true,
        host: "127.0.0.1",
        port: 9070
    }
};

// ### Initialize configuration
//
// Load from environment
// Use '__' as separator
// server__port=9080
nconf.env('__');

//
// Attempt to load from a prioritized series of configuration files.
//
// 1. Environ var `KUMASCRIPT_CONFIG`
// 2. `kumascript_settings_local.json` in current dir
// 3. `kumascript_settings.json` in current dir
var cwd = process.cwd(),
    conf_fns = [
        cwd + '/kumascript_settings.json',
        cwd + '/kumascript_settings_local.json',
        process.env.KUMASCRIPT_CONFIG
    ];
_.each(conf_fns, function (conf_fn) {
    if (!conf_fn) { return; }
    try { fs.statSync(conf_fn).isFile(); }
    catch (e) { return; }
    nconf.file({ file: conf_fn });
});

// Include the fallback defaults.
nconf.defaults(DEFAULT_CONFIG);

module.exports = {
    nconf: nconf
};
<|endoftext|>


<commit_before>/**
 * @todo Integrate with {@link collections.Collection}
 */

var _ = require('lodash')

var HttpErrors = require('@carbon-io/carbon-core').HttpErrors
var oo = require('@carbon-io/carbon-core').atom.oo(module)
var o = require('@carbon-io/carbon-core').atom.o(module)

/******************************************************************************
 * @interface Limiter
 */
var Limiter = oo({
  _ctorName: 'Limiter',
  _C: function() {
    if (this.constructor === Limiter) {
      throw new Error('Interface')
    }
    /**
     * @member {carbond.Service}
     */
    this.service = undefined

    /**
     * @member {Service|Endpoint|Operation}
     *
     * @todo better name for this? node represents the top level {@link Service},
     *       an {@link Endpoint}, or an {@link Operation}
     */
    this.node = undefined

    /**
     * @member {boolean}
     */
    this.preAuth = false

    /**
     * @member {Atom}
     */
    this.throttlingResponse = undefined

    /**
     * @member {boolean}
     */
    this.logRejections = false

  },

  /**********************************************************************
   * method initialize
   *
   * @param {Service} service - the root `Service` object
   * @param {Service|carbond.Endpoint|carbond.Operation} [node] -
   *        the endpoint that this limiter is guarding
   */
  initialize: function(service, node) {
    this.service = service
    this.node = node
  },

  _init: function() {
    if (_.isUndefined(this.throttlingResponse) || _.isNull(this.throttlingResponse)) {
      this.throttlingResponse = o({
        error: HttpErrors.ServiceUnavailable,
        message: 'Service unavailable.'
      });
    }
  },

  /**********************************************************************
   * method process
   *
   * @param {Request} req - the request received
   * @param {Response} res - the response to be sent
   * @param {Function} next - pass control to the next request processor
   */
  process: function(req, res, next) {
    throw new Error('Not implemented')
  },

  /**********************************************************************
   * method sendUnavailable
   *
   * Send a generic "service unavailable" response. Subclasses should
   * customize if they need to message something more specific.
   *
   * @param {Response} res - the Response object
   * @param {function} - next function
   * @param {string|object} [message] - any other data you want to bubble up
   *                                    to the user (should be JSON
   *                                    serializable)
   * @param {integer} [retryAfter=60] - amount of time the client should
   *                                    wait before retrying the request
   *                                    (if null, do not include the header)
   * @throws TypeError
   */
  sendUnavailable: function(res, next, retryAfter) {
    const {error, message} = this.throttlingResponse;

    const err = new error(message)

    if (_.isUndefined(res)) {
      throw new TypeError('Expected a Response object but got undefined')
    }
    // XXX: probably shouldn't be using protected method
    if (_.isUndefined(retryAfter)) {
      retryAfter = 60
    }
    if (!(_.isNull(retryAfter) || _.isInteger(retryAfter))) {
      throw new TypeError('retryAfter must be undefined, null, or an integer')
    }
    if (!_.isNull(retryAfter)) {
      res.append('Retry-After', retryAfter.toString())
    }

    if (this.logRejections) {
      const endpoint = node.endpoint ? node.endpoint : node;
      const path = endpoint.path;

      this.service.logInfo(`Limiter rejected request at ${path}`);
    }

    if (next) {
      return next(err)
    }
    this.service._handleError(err, res)
  }
})

module.exports = Limiter
<commit_msg>Limiter.js: node -> this.node<commit_after>/**
 * @todo Integrate with {@link collections.Collection}
 */

var _ = require('lodash')

var HttpErrors = require('@carbon-io/carbon-core').HttpErrors
var oo = require('@carbon-io/carbon-core').atom.oo(module)
var o = require('@carbon-io/carbon-core').atom.o(module)

/******************************************************************************
 * @interface Limiter
 */
var Limiter = oo({
  _ctorName: 'Limiter',
  _C: function() {
    if (this.constructor === Limiter) {
      throw new Error('Interface')
    }
    /**
     * @member {carbond.Service}
     */
    this.service = undefined

    /**
     * @member {Service|Endpoint|Operation}
     *
     * @todo better name for this? node represents the top level {@link Service},
     *       an {@link Endpoint}, or an {@link Operation}
     */
    this.node = undefined

    /**
     * @member {boolean}
     */
    this.preAuth = false

    /**
     * @member {Atom}
     */
    this.throttlingResponse = undefined

    /**
     * @member {boolean}
     */
    this.logRejections = false

  },

  /**********************************************************************
   * method initialize
   *
   * @param {Service} service - the root `Service` object
   * @param {Service|carbond.Endpoint|carbond.Operation} [node] -
   *        the endpoint that this limiter is guarding
   */
  initialize: function(service, node) {
    this.service = service
    this.node = node
  },

  _init: function() {
    if (_.isUndefined(this.throttlingResponse) || _.isNull(this.throttlingResponse)) {
      this.throttlingResponse = o({
        error: HttpErrors.ServiceUnavailable,
        message: 'Service unavailable.'
      });
    }
  },

  /**********************************************************************
   * method process
   *
   * @param {Request} req - the request received
   * @param {Response} res - the response to be sent
   * @param {Function} next - pass control to the next request processor
   */
  process: function(req, res, next) {
    throw new Error('Not implemented')
  },

  /**********************************************************************
   * method sendUnavailable
   *
   * Send a generic "service unavailable" response. Subclasses should
   * customize if they need to message something more specific.
   *
   * @param {Response} res - the Response object
   * @param {function} - next function
   * @param {string|object} [message] - any other data you want to bubble up
   *                                    to the user (should be JSON
   *                                    serializable)
   * @param {integer} [retryAfter=60] - amount of time the client should
   *                                    wait before retrying the request
   *                                    (if null, do not include the header)
   * @throws TypeError
   */
  sendUnavailable: function(res, next, retryAfter) {
    const {error, message} = this.throttlingResponse;

    const err = new error(message)

    if (_.isUndefined(res)) {
      throw new TypeError('Expected a Response object but got undefined')
    }
    // XXX: probably shouldn't be using protected method
    if (_.isUndefined(retryAfter)) {
      retryAfter = 60
    }
    if (!(_.isNull(retryAfter) || _.isInteger(retryAfter))) {
      throw new TypeError('retryAfter must be undefined, null, or an integer')
    }
    if (!_.isNull(retryAfter)) {
      res.append('Retry-After', retryAfter.toString())
    }

    if (this.logRejections) {
      const endpoint = this.node.endpoint ? this.node.endpoint : this.node;
      const path = endpoint.path;

      this.service.logInfo(`Limiter rejected request at ${path}`);
    }

    if (next) {
      return next(err)
    }
    this.service._handleError(err, res)
  }
})

module.exports = Limiter
<|endoftext|>


<commit_before>'use babel'

/* @flow */

import { Emitter, CompositeDisposable } from 'atom'
import type { TextEditor, Disposable } from 'atom'
import { linter as validateLinter, messages as validateMessages, messagesLegacy as validateMessagesLegacy } from './validate'
import { normalizeMessages, normalizeMessagesLegacy, isPathIgnored, shouldTriggerLinter, $version, $activated, $requestLatest, $requestLastReceived } from './helpers'
import type { Linter } from './types'

export default class LinterRegistry {
  emitter: Emitter;
  linters: Set<Linter>;
  lintOnFly: boolean;
  ignoreVCS: boolean;
  ignoreGlob: string;
  lintPreviewTabs: boolean;
  subscriptions: CompositeDisposable;

  constructor() {
    this.emitter = new Emitter()
    this.linters = new Set()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(atom.config.observe('linter.lintOnFly', lintOnFly => {
      this.lintOnFly = lintOnFly
    }))
    this.subscriptions.add(atom.config.observe('core.excludeVcsIgnoredPaths', ignoreVCS => {
      this.ignoreVCS = ignoreVCS
    }))
    this.subscriptions.add(atom.config.observe('linter.ignoreGlob', ignoreGlob => {
      this.ignoreGlob = ignoreGlob
    }))
    this.subscriptions.add(atom.config.observe('linter.lintPreviewTabs', lintPreviewTabs => {
      this.lintPreviewTabs = lintPreviewTabs
    }))
    this.subscriptions.add(this.emitter)
  }
  hasLinter(linter: Linter): boolean {
    return this.linters.has(linter)
  }
  addLinter(linter: Linter, legacy: boolean = false) {
    if (!validateLinter(linter)) {
      return
    }
    linter[$activated] = true
    if (typeof linter[$requestLatest] === 'undefined') {
      linter[$requestLatest] = 0
    }
    if (typeof linter[$requestLastReceived] === 'undefined') {
      linter[$requestLastReceived] = 0
    }
    linter[$version] = legacy ? 1 : 2
    this.linters.add(linter)
  }
  deleteLinter(linter: Linter) {
    if (!this.linters.has(linter)) {
      return
    }
    linter[$activated] = false
    this.linters.delete(linter)
  }
  async lint({ onChange, editor } : { onChange: boolean, editor: TextEditor }): Promise<boolean> {
    /* eslint-disable no-multi-spaces */
    const filePath = editor.getPath()

    if (
      (onChange && !this.lintOnFly)                                             || // Lint-on-fly mismatch
      !filePath                                                                 || // Not saved anywhere yet
      editor !== atom.workspace.getActiveTextEditor()                           || // Not active
      isPathIgnored(editor.getPath(), this.ignoreGlob, this.ignoreVCS)          || // Ignored by VCS or Glob
      (!this.lintPreviewTabs && editor.hasTerminatedPendingState === false)        // Ignore Preview tabs
    ) {
      return false
    }

    const scopes = editor.scopeDescriptorForBufferPosition(editor.getCursorBufferPosition()).getScopesArray()
    scopes.push('*')

    const promises = []
    for (const linter of this.linters) {
      if (!shouldTriggerLinter(linter, onChange, scopes)) {
        continue
      }
      const number = ++linter[$requestLatest]
      this.emitter.emit('did-begin-linting', { number, linter })
      promises.push(new Promise(function(resolve) {
        resolve(linter.lint(editor))
      }).then(messages => {
        this.emitter.emit('did-finish-linting', { number, linter })
        if (Array.isArray(messages) && linter[$requestLastReceived] < number && linter[$activated]) {
          linter[$requestLastReceived] = number
          const buffer = linter.scope === 'project' ? null : editor.getBuffer()
          if (!buffer || buffer.isAlive()) {
            const validity = atom.inDevMode() ? (linter[$version] === 2 ? validateMessages(linter.name, messages) : validateMessagesLegacy(linter.name, messages)) : true
            if (validity) {
              if (linter[$version] === 2) {
                normalizeMessages(linter.name, messages)
              } else {
                normalizeMessagesLegacy(linter.name, messages)
              }
              this.emitter.emit('did-update-messages', { messages, linter, buffer })
            }
          }
        }
      }, function(error) {
        atom.notifications.addError(`[Linter] Error running ${linter.name}`, {
          detail: 'See console for more info',
        })
        console.error(`[Linter] Error running ${linter.name}`, error)
      }))
    }

    await Promise.all(promises)
    return true
  }
  onDidUpdateMessages(callback: Function): Disposable {
    return this.emitter.on('did-update-messages', callback)
  }
  onDidBeginLinting(callback: Function): Disposable {
    return this.emitter.on('did-begin-linting', callback)
  }
  onDidFinishLinting(callback: Function): Disposable {
    return this.emitter.on('did-finish-linting', callback)
  }
  dispose() {
    this.linters.clear()
    this.subscriptions.dispose()
  }
}
<commit_msg>:bug: Specify filePath with linting progress properly<commit_after>'use babel'

/* @flow */

import { Emitter, CompositeDisposable } from 'atom'
import type { TextEditor, Disposable } from 'atom'
import { linter as validateLinter, messages as validateMessages, messagesLegacy as validateMessagesLegacy } from './validate'
import { normalizeMessages, normalizeMessagesLegacy, isPathIgnored, shouldTriggerLinter, $version, $activated, $requestLatest, $requestLastReceived } from './helpers'
import type { Linter } from './types'

export default class LinterRegistry {
  emitter: Emitter;
  linters: Set<Linter>;
  lintOnFly: boolean;
  ignoreVCS: boolean;
  ignoreGlob: string;
  lintPreviewTabs: boolean;
  subscriptions: CompositeDisposable;

  constructor() {
    this.emitter = new Emitter()
    this.linters = new Set()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(atom.config.observe('linter.lintOnFly', lintOnFly => {
      this.lintOnFly = lintOnFly
    }))
    this.subscriptions.add(atom.config.observe('core.excludeVcsIgnoredPaths', ignoreVCS => {
      this.ignoreVCS = ignoreVCS
    }))
    this.subscriptions.add(atom.config.observe('linter.ignoreGlob', ignoreGlob => {
      this.ignoreGlob = ignoreGlob
    }))
    this.subscriptions.add(atom.config.observe('linter.lintPreviewTabs', lintPreviewTabs => {
      this.lintPreviewTabs = lintPreviewTabs
    }))
    this.subscriptions.add(this.emitter)
  }
  hasLinter(linter: Linter): boolean {
    return this.linters.has(linter)
  }
  addLinter(linter: Linter, legacy: boolean = false) {
    if (!validateLinter(linter)) {
      return
    }
    linter[$activated] = true
    if (typeof linter[$requestLatest] === 'undefined') {
      linter[$requestLatest] = 0
    }
    if (typeof linter[$requestLastReceived] === 'undefined') {
      linter[$requestLastReceived] = 0
    }
    linter[$version] = legacy ? 1 : 2
    this.linters.add(linter)
  }
  deleteLinter(linter: Linter) {
    if (!this.linters.has(linter)) {
      return
    }
    linter[$activated] = false
    this.linters.delete(linter)
  }
  async lint({ onChange, editor } : { onChange: boolean, editor: TextEditor }): Promise<boolean> {
    /* eslint-disable no-multi-spaces */
    const filePath = editor.getPath()

    if (
      (onChange && !this.lintOnFly)                                             || // Lint-on-fly mismatch
      !filePath                                                                 || // Not saved anywhere yet
      editor !== atom.workspace.getActiveTextEditor()                           || // Not active
      isPathIgnored(editor.getPath(), this.ignoreGlob, this.ignoreVCS)          || // Ignored by VCS or Glob
      (!this.lintPreviewTabs && editor.hasTerminatedPendingState === false)        // Ignore Preview tabs
    ) {
      return false
    }

    const scopes = editor.scopeDescriptorForBufferPosition(editor.getCursorBufferPosition()).getScopesArray()
    scopes.push('*')

    const promises = []
    for (const linter of this.linters) {
      if (!shouldTriggerLinter(linter, onChange, scopes)) {
        continue
      }
      const number = ++linter[$requestLatest]
      this.emitter.emit('did-begin-linting', { number, linter, filePath: linter.scope === 'file' ? filePath : null })
      promises.push(new Promise(function(resolve) {
        resolve(linter.lint(editor))
      }).then(messages => {
        this.emitter.emit('did-finish-linting', { number, linter, filePath: linter.scope === 'file' ? filePath : null })
        if (Array.isArray(messages) && linter[$requestLastReceived] < number && linter[$activated]) {
          linter[$requestLastReceived] = number
          const buffer = linter.scope === 'project' ? null : editor.getBuffer()
          if (!buffer || buffer.isAlive()) {
            const validity = atom.inDevMode() ? (linter[$version] === 2 ? validateMessages(linter.name, messages) : validateMessagesLegacy(linter.name, messages)) : true
            if (validity) {
              if (linter[$version] === 2) {
                normalizeMessages(linter.name, messages)
              } else {
                normalizeMessagesLegacy(linter.name, messages)
              }
              this.emitter.emit('did-update-messages', { messages, linter, buffer })
            }
          }
        }
      }, function(error) {
        atom.notifications.addError(`[Linter] Error running ${linter.name}`, {
          detail: 'See console for more info',
        })
        console.error(`[Linter] Error running ${linter.name}`, error)
      }))
    }

    await Promise.all(promises)
    return true
  }
  onDidUpdateMessages(callback: Function): Disposable {
    return this.emitter.on('did-update-messages', callback)
  }
  onDidBeginLinting(callback: Function): Disposable {
    return this.emitter.on('did-begin-linting', callback)
  }
  onDidFinishLinting(callback: Function): Disposable {
    return this.emitter.on('did-finish-linting', callback)
  }
  dispose() {
    this.linters.clear()
    this.subscriptions.dispose()
  }
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var gulp = require('gulp');
var config = require('../project.config');

gulp.task('default', false, function () {
  gulp.tasks.help.fn();
});

gulp.task('build', 'Clean, Copy assets, Build CSS and Build JS', ['clean'], function () {
  gulp.run('copy');
  gulp.run('build:css');
  gulp.run('build:js');
});
<commit_msg>small build help copy change`<commit_after>'use strict';

var path = require('path');
var gulp = require('gulp');
var config = require('../project.config');

gulp.task('default', false, function () {
  gulp.tasks.help.fn();
});

gulp.task('build', 'Clean then Copy assets and build CSS+JS', ['clean'], function () {
  gulp.run('copy');
  gulp.run('build:css');
  gulp.run('build:js');
});
<|endoftext|>


<commit_before> /**
 *
 * Gulpfile > Tasks > JS
 *
 * Copyright 2016, Web Framework by Stewart Dellow
 * MIT License (MIT)
 *
**/

;(function(GulpTask1, GulpTask2, GulpTask3){

	/* =========================================================================== */
	/* Config
	/* =========================================================================== */
	var config = require('../config.json');

	/* =========================================================================== */
	/* Libs
	/* =========================================================================== */
	var handleErrors = require('../lib/handle-errors');

	/* =========================================================================== */
	/* Global Dependencies
	/* =========================================================================== */
	var gulp   = require('gulp'),
		args   = require('yargs').argv,
		gulpif = require('gulp-if'),
		notify = require('gulp-notify'),
		buffer = require('vinyl-buffer'),
		source = require('vinyl-source-stream');

	/* =========================================================================== */
	/* Task Dependencies
	/* =========================================================================== */
	var browserify = require('browserify'),
	    header     = require('gulp-header'),
	    rename     = require('gulp-rename'),
	    concat     = require('gulp-concat');

	/* =========================================================================== */
	/* Task (Common Libraries & Vendors.)
	/* =========================================================================== */
	GulpTask1 = function(){
		return browserify(config.js.src1).bundle()
			.on('error', handleErrors)
			.pipe(source('index.js'))
		    .pipe(buffer())
			.pipe(rename('common.js'))
			.pipe(gulp.dest(config.js.dest1))
			.pipe(notify({message: 'JS Common task complete.'}));
	}

	/* =========================================================================== */
	/* Task (All Files.)
	/* =========================================================================== */
	GulpTask2 = function(){
		return browserify(config.js.src2).bundle()
			.on('error', handleErrors)
		    .pipe(source('index.js'))
		    .pipe(buffer())
			.pipe(rename('all.js'))
			.pipe(gulp.dest(config.js.dest2))
			.pipe(notify({message: 'JS All task complete.'}));
	}

	/* =========================================================================== */
	/* Task
	/* =========================================================================== */
	GulpTask3 = function(){
		// Vars
		var version = config.version, // Need this for Headers.
			is_development = (args.config == 'development' || args.config == undefined) ? true : false,
			is_production  = (args.config == 'production') ? true : false;

		// Set environment in JS file.
		var header_tpl_env = ['// Set environment variable',
			'window.gulp_env = "<%= env %>";',
			'',
			''].join('\n');

		// Header template.
		var header_tpl = ['/* ==========================================================================',
			'JavaScript',
			'Application Version: <%= version %>',
			'Compiled: <%= date %>',
			'========================================================================== */',
			'',
			''].join('\n');

		return gulp.src(config.js.src3)
		    .pipe(concat('build.js'))
			.pipe(header(header_tpl_env, {
				env: (is_production) ? 'production' : 'development'
			}))
			.pipe(header(header_tpl, {
				version: version,
				date   : Date()
			}))
			.pipe(gulp.dest(config.js.dest3))
			.on('error', handleErrors)
			.pipe(notify({message: 'JS Build task complete.'}));
	}

	// Task
	gulp.task('js:common', GulpTask1);
	gulp.task('js:all', GulpTask2);
	gulp.task('js', ['js:all'], GulpTask3);

	// Export
	module.exports = {
	    'common': GulpTask1,
	    'all': GulpTask2,
	    'js': GulpTask3
	};

}(function(){}, function(){}, function(){}));<commit_msg>Removed header<commit_after> /**
 *
 * Gulpfile > Tasks > JS
 *
 * Copyright 2016, Web Framework by Stewart Dellow
 * MIT License (MIT)
 *
**/

;(function(GulpTask1, GulpTask2, GulpTask3){

	/* =========================================================================== */
	/* Config
	/* =========================================================================== */
	var config = require('../config.json');

	/* =========================================================================== */
	/* Libs
	/* =========================================================================== */
	var handleErrors = require('../lib/handle-errors');

	/* =========================================================================== */
	/* Global Dependencies
	/* =========================================================================== */
	var gulp   = require('gulp'),
		args   = require('yargs').argv,
		gulpif = require('gulp-if'),
		notify = require('gulp-notify'),
		buffer = require('vinyl-buffer'),
		source = require('vinyl-source-stream');

	/* =========================================================================== */
	/* Task Dependencies
	/* =========================================================================== */
	var browserify = require('browserify'),
	    header     = require('gulp-header'),
	    rename     = require('gulp-rename'),
	    concat     = require('gulp-concat');

	/* =========================================================================== */
	/* Task (Common Libraries & Vendors.)
	/* =========================================================================== */
	GulpTask1 = function(){
		return browserify(config.js.src1).bundle()
			.on('error', handleErrors)
			.pipe(source('index.js'))
		    .pipe(buffer())
			.pipe(rename('common.js'))
			.pipe(gulp.dest(config.js.dest1))
			.pipe(notify({message: 'JS Common task complete.'}));
	}

	/* =========================================================================== */
	/* Task (All Files.)
	/* =========================================================================== */
	GulpTask2 = function(){
		return browserify(config.js.src2).bundle()
			.on('error', handleErrors)
		    .pipe(source('index.js'))
		    .pipe(buffer())
			.pipe(rename('all.js'))
			.pipe(gulp.dest(config.js.dest2))
			.pipe(notify({message: 'JS All task complete.'}));
	}

	/* =========================================================================== */
	/* Task
	/* =========================================================================== */
	GulpTask3 = function(){
		// Vars
		var version = config.version, // Need this for Headers.
			is_development = (args.config == 'development' || args.config == undefined) ? true : false,
			is_production  = (args.config == 'production') ? true : false;

		// Set environment in JS file.
		var header_tpl_env = ['// Set environment variable',
			'window.gulp_env = "<%= env %>";',
			'',
			''].join('\n');

		return gulp.src(config.js.src3)
		    .pipe(concat('build.js'))
			.pipe(header(header_tpl_env, {
				env: (is_production) ? 'production' : 'development'
			}))
			.pipe(gulp.dest(config.js.dest3))
			.on('error', handleErrors)
			.pipe(notify({message: 'JS Build task complete.'}));
	}

	// Task
	gulp.task('js:common', GulpTask1);
	gulp.task('js:all', GulpTask2);
	gulp.task('js', ['js:all'], GulpTask3);

	// Export
	module.exports = {
	    'common': GulpTask1,
	    'all': GulpTask2,
	    'js': GulpTask3
	};

}(function(){}, function(){}, function(){}));<|endoftext|>


<commit_before>const event = require('../event');
const container = require('../container');
const recorder = require('../recorder');
const { deepMerge } = require('../utils');
const { debug } = require('../output');
/**
 * Enable Helpers to listen to test events
 */
module.exports = function () {
  const helpers = container.helpers();

  event.dispatcher.on(event.suite.before, (suite) => {
    function updateHelperConfig(helper, config) {
      const oldConfig = Object.assign({}, helper.options);
      try {
        helper._setConfig(deepMerge(Object.assign({}, oldConfig), config));
        debug(`[Suite Config] ${helper.constructor.name} ${JSON.stringify(config)}`);
      } catch (err) {
        recorder.throw(err);
        return;
      }
      const eventId = Math.random().toString(36).substr(2, 9);
      suite.eventId = eventId; // additional check we work for the same suite
      event.dispatcher.once(event.suite.after, (t) => {
        if (t.eventId && t.eventId === eventId) {
          helper._setConfig(oldConfig);
          debug(`[Suite Config] Reverted for ${helper.constructor.name}`);
        }
      });
    }

    // change config
    if (suite.config) {
      for (let name in suite.config) {
        const config = suite.config[name];
        if (name === '0') { // first helper
          name = Object.keys(helpers);
        }
        const helper = helpers[name];
        updateHelperConfig(helper, config);
      }
    }
  });

  event.dispatcher.on(event.test.before, (test) => {
    if (!test) return;
    function updateHelperConfig(helper, config) {
      const oldConfig = Object.assign({}, helper.options);
      try {
        helper._setConfig(deepMerge(Object.assign({}, oldConfig), config));
        debug(`[Test Config] ${helper.constructor.name} ${JSON.stringify(config)}`);
      } catch (err) {
        recorder.throw(err);
        return;
      }
      const eventId = Math.random().toString(36).substr(2, 9);
      test.eventId = eventId; // additional check we work for the same test
      event.dispatcher.once(event.test.finished, (t) => {
        if (t.eventId && t.eventId === eventId) {
          helper._setConfig(oldConfig);
          debug(`[Test Config] Reverted for ${helper.constructor.name}`);
        }
      });
    }

    // change config
    if (test.config) {
      for (let name in test.config) {
        const config = test.config[name];
        if (name === '0') { // first helper
          name = Object.keys(helpers);
        }
        const helper = helpers[name];
        updateHelperConfig(helper, config);
      }
    }
  });
};

<commit_msg>removed hash creation for event as it has no sense :(<commit_after>const event = require('../event');
const container = require('../container');
const recorder = require('../recorder');
const { deepMerge } = require('../utils');
const { debug } = require('../output');
/**
 * Enable Helpers to listen to test events
 */
module.exports = function () {
  const helpers = container.helpers();

  event.dispatcher.on(event.suite.before, (suite) => {
    function updateHelperConfig(helper, config) {
      const oldConfig = Object.assign({}, helper.options);
      try {
        helper._setConfig(deepMerge(Object.assign({}, oldConfig), config));
        debug(`[Suite Config] ${helper.constructor.name} ${JSON.stringify(config)}`);
      } catch (err) {
        recorder.throw(err);
        return;
      }
      event.dispatcher.once(event.suite.after, (t) => {
        helper._setConfig(oldConfig);
        debug(`[Suite Config] Reverted for ${helper.constructor.name}`);
      });
    }

    // change config
    if (suite.config) {
      for (let name in suite.config) {
        const config = suite.config[name];
        if (name === '0') { // first helper
          name = Object.keys(helpers);
        }
        const helper = helpers[name];
        updateHelperConfig(helper, config);
      }
    }
  });

  event.dispatcher.on(event.test.before, (test) => {
    if (!test) return;
    function updateHelperConfig(helper, config) {
      const oldConfig = Object.assign({}, helper.options);
      try {
        helper._setConfig(deepMerge(Object.assign({}, oldConfig), config));
        debug(`[Test Config] ${helper.constructor.name} ${JSON.stringify(config)}`);
      } catch (err) {
        recorder.throw(err);
        return;
      }
      event.dispatcher.once(event.test.finished, (t) => {
        helper._setConfig(oldConfig);
        debug(`[Test Config] Reverted for ${helper.constructor.name}`);
      });
    }

    // change config
    if (test.config) {
      for (let name in test.config) {
        const config = test.config[name];
        if (name === '0') { // first helper
          name = Object.keys(helpers);
        }
        const helper = helpers[name];
        updateHelperConfig(helper, config);
      }
    }
  });
};

<|endoftext|>


<commit_before>import {AccountStore} from 'nylas-exports'
import NylasLongConnection from './nylas-long-connection'

// A 0 code is when an error returns without a status code, like "ESOCKETTIMEDOUT"
const TimeoutErrorCodes = [0, 408, "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "ENETDOWN", "ENETUNREACH"]
const PermanentErrorCodes = [400, 401, 402, 403, 404, 405, 429, 500, "ENOTFOUND", "ECONNREFUSED", "EHOSTDOWN", "EHOSTUNREACH"]
const CanceledErrorCode = [-123, "ECONNABORTED"]
const SampleTemporaryErrorCode = 504

class NylasAPIChangeLockTracker {
  constructor() {
    this._locks = {}
  }

  acceptRemoteChangesTo(klass, id) {
    const key = `${klass.name}-${id}`
    return this._locks[key] === undefined
  }

  increment(klass, id) {
    const key = `${klass.name}-${id}`
    this._locks[key] = this._locks[key] || 0
    this._locks[key] += 1
  }

  decrement(klass, id) {
    const key = `${klass.name}-${id}`
    if (!this._locks[key]) return
    this._locks[key] -= 1
    if (this._locks[key] <= 0) {
      delete this._locks[key]
    }
  }

  print() {
    console.log("The following models are locked:")
    console.log(this._locks)
  }
}

class NylasAPI {

  constructor() {
    this.lockTracker = new NylasAPIChangeLockTracker()
    this.APIRoot = "http://localhost:2578"

    this.TimeoutErrorCodes = TimeoutErrorCodes
    this.PermanentErrorCodes = PermanentErrorCodes
    this.CanceledErrorCode = CanceledErrorCode
    this.SampleTemporaryErrorCode = SampleTemporaryErrorCode
    this.LongConnectionStatus = NylasLongConnection.Status
  }

  accessTokenForAccountId(aid) {
    return AccountStore.tokensForAccountId(aid).localSync
  }

  longConnection = (opts) => {
    const connection = new NylasLongConnection(this, opts.accountId, opts)
    connection.onResults(opts.onResults)
    return connection
  }

  startLongConnection = (opts) => {
    this.longConnection(opts).start()
  }

  incrementRemoteChangeLock = (klass, id) => {
    this.lockTracker.increment(klass, id)
  }

  decrementRemoteChangeLock = (klass, id) => {
    this.lockTracker.decrement(klass, id)
  }
}

export default new NylasAPI()
<commit_msg>fix(startLongConnection) Return the connection<commit_after>import {AccountStore} from 'nylas-exports'
import NylasLongConnection from './nylas-long-connection'

// A 0 code is when an error returns without a status code, like "ESOCKETTIMEDOUT"
const TimeoutErrorCodes = [0, 408, "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "ENETDOWN", "ENETUNREACH"]
const PermanentErrorCodes = [400, 401, 402, 403, 404, 405, 429, 500, "ENOTFOUND", "ECONNREFUSED", "EHOSTDOWN", "EHOSTUNREACH"]
const CanceledErrorCode = [-123, "ECONNABORTED"]
const SampleTemporaryErrorCode = 504

class NylasAPIChangeLockTracker {
  constructor() {
    this._locks = {}
  }

  acceptRemoteChangesTo(klass, id) {
    const key = `${klass.name}-${id}`
    return this._locks[key] === undefined
  }

  increment(klass, id) {
    const key = `${klass.name}-${id}`
    this._locks[key] = this._locks[key] || 0
    this._locks[key] += 1
  }

  decrement(klass, id) {
    const key = `${klass.name}-${id}`
    if (!this._locks[key]) return
    this._locks[key] -= 1
    if (this._locks[key] <= 0) {
      delete this._locks[key]
    }
  }

  print() {
    console.log("The following models are locked:")
    console.log(this._locks)
  }
}

class NylasAPI {

  constructor() {
    this.lockTracker = new NylasAPIChangeLockTracker()
    this.APIRoot = "http://localhost:2578"

    this.TimeoutErrorCodes = TimeoutErrorCodes
    this.PermanentErrorCodes = PermanentErrorCodes
    this.CanceledErrorCode = CanceledErrorCode
    this.SampleTemporaryErrorCode = SampleTemporaryErrorCode
    this.LongConnectionStatus = NylasLongConnection.Status
  }

  accessTokenForAccountId(aid) {
    return AccountStore.tokensForAccountId(aid).localSync
  }

  longConnection = (opts) => {
    const connection = new NylasLongConnection(this, opts.accountId, opts)
    connection.onResults(opts.onResults)
    return connection
  }

  startLongConnection = (opts) => {
    return this.longConnection(opts).start()
  }

  incrementRemoteChangeLock = (klass, id) => {
    this.lockTracker.increment(klass, id)
  }

  decrementRemoteChangeLock = (klass, id) => {
    this.lockTracker.decrement(klass, id)
  }
}

export default new NylasAPI()
<|endoftext|>


<commit_before>/*
 * JavaScript tracker for SnowPlow: init.js
 *
 * Significant portions copyright 2010 Anthon Pang. Remainder copyright
 * 2012-2013 SnowPlow Analytics Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Anthon Pang nor SnowPlow Analytics Ltd nor the
 *   names of their contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// SnowPlow Asynchronous Queue
var _snaq = _snaq || [];

/**
 * SnowPlow namespace.
 * Add classes and functions in this namespace.
 */
var SnowPlow = SnowPlow || function() {
	var windowAlias = window;
	return {

		/* Tracker identifier with version */
		version: 'js-0.11.0',

		expireDateTime: null,

		/* Plugins */
		plugins: {},

		/* DOM Ready */
		hasLoaded: false,
		registeredOnLoadHandlers: [],

		/* Alias frequently used globals for added minification */
		documentAlias: document,
		windowAlias: windowAlias,
		navigatorAlias: navigator,
		screenAlias: screen,

		/* Encode */
		encodeWrapper: windowAlias.encodeURIComponent,

		/* Decode */
		decodeWrapper: windowAlias.decodeURIComponent,

		/* decodeUrl */
		decodeUrl: unescape,

		/* Asynchronous tracker */
		asyncTracker: null
	}
}();

<commit_msg>Added reminder about updating banner.js<commit_after>/*
 * JavaScript tracker for SnowPlow: init.js
 *
 * Significant portions copyright 2010 Anthon Pang. Remainder copyright
 * 2012-2013 SnowPlow Analytics Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Anthon Pang nor SnowPlow Analytics Ltd nor the
 *   names of their contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// SnowPlow Asynchronous Queue
var _snaq = _snaq || [];

/**
 * SnowPlow namespace.
 * Add classes and functions in this namespace.
 */
var SnowPlow = SnowPlow || function() {
	var windowAlias = window;
	return {

		/* Tracker identifier with version */
		version: 'js-0.11.0', // Update banner.js too

		expireDateTime: null,

		/* Plugins */
		plugins: {},

		/* DOM Ready */
		hasLoaded: false,
		registeredOnLoadHandlers: [],

		/* Alias frequently used globals for added minification */
		documentAlias: document,
		windowAlias: windowAlias,
		navigatorAlias: navigator,
		screenAlias: screen,

		/* Encode */
		encodeWrapper: windowAlias.encodeURIComponent,

		/* Decode */
		decodeWrapper: windowAlias.decodeURIComponent,

		/* decodeUrl */
		decodeUrl: unescape,

		/* Asynchronous tracker */
		asyncTracker: null
	}
}();

<|endoftext|>


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

foam.CLASS({
  package: 'foam.util',
  name: 'Timer',

  documentation: 'Timer object. Useful for creating animations.',

  properties: [
    {
      class: 'Int',
      name: 'interval',
      help: 'Interval of time between updating time.',
      // units: 'ms',
      value: 10
    },
    {
      class: 'Int',
      name: 'i',
      value: 0
    },
    {
      class: 'Float',
      name: 'timeWarp',
      value: 1.0
    },
    {
      class: 'Int',
      name:  'duration',
      units: 'ms',
      value: -1
    },
    {
      class: 'Float',
      name: 'percent',
      value: 0
    },
    {
      class: 'Int',
      name:  'startTime',
      value: 0
    },
    {
      class: 'Int',
      name:  'time',
      help:  'The current time in milliseconds since epoch.',
      adapt: function(_, t) { return Math.ceil(t); },
      value: 0
    },
    {
      class: 'Int',
      name:  'second',
      help:  'The second of the current minute.',
      value: 0
    },
    {
      class: 'Int',
      name:  'minute',
      help:  'The minute of the current hour.',
      value: 0
    },
    {
      class: 'Int',
      name:  'hour',
      help:  'The hour of the current day.',
      value: 0
    },
    {
      class: 'Boolean',
      name: 'isStarted',
      hidden: true
    },
    {
      class: 'Int',
      name: 'startTime_',
      hidden: true
    }
  ],

  methods: [
    function cycle(frequency, a, b) {
      /**
         cycle(frequency)             - cycle between -1 and 1 frequency times a second
         cycle(frequency, amplitude)  - cycle between -amplitude and amplitude frequency times a second
         cycle(frequency, start, end) - cycle between start and end frequency times a second
      */
      var s = Math.sin(this.time/1000*frequency*Math.PI*2);
      if ( arguments.length === 1 ) return s;
      if ( arguments.length === 2 ) return s * a;
      return a + (1 + s) * (b-a)/2;
    }
  ],

  actions: [
    {
      name:  'start',
      help:  'Start the timer.',
      isEnabled:   function(isStarted) { return ! isStarted; },
      code:        function() { this.isStarted = true; this.tick(); }
    },
    {
      name:  'step',
      help:  'Step the timer.',
      code: function()      {
        this.i++;
        this.time  += this.interval * this.timeWarp;
        this.second = this.time /    1000 % 60 << 0;
        this.minute = this.time /   60000 % 60 << 0;
        this.hour   = this.time / 3600000 % 24 << 0;
      }
    },
    {
      name:  'stop',
      help:  'Stop the timer.',
      isEnabled:   function(isStarted) { return isStarted; },
      code:        function() { this.isStarted = false; }
    }
  ],

  listeners: [
    {
      name: 'tick',
      isFramed: true,
      code: function(e) {
        if ( ! this.isStarted ) return;

        var prevTime = this.startTime_;
        this.startTime_ = Date.now();
        this.interval = Math.min(100, this.startTime_ - prevTime);
        this.step();
        this.tick();
      }
    }
  ]
});
<commit_msg>Formatting.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.util',
  name: 'Timer',

  documentation: 'Timer object. Useful for creating animations.',

  properties: [
    {
      class: 'Int',
      name: 'interval',
      help: 'Interval of time between updating time.',
      // units: 'ms',
      value: 10
    },
    {
      class: 'Int',
      name: 'i',
      value: 0
    },
    {
      class: 'Float',
      name: 'timeWarp',
      value: 1.0
    },
    {
      class: 'Int',
      name:  'duration',
      units: 'ms',
      value: -1
    },
    {
      class: 'Float',
      name: 'percent',
      value: 0
    },
    {
      class: 'Int',
      name:  'startTime',
      value: 0
    },
    {
      class: 'Int',
      name:  'time',
      help:  'The current time in milliseconds since epoch.',
      adapt: function(_, t) { return Math.ceil(t); },
      value: 0
    },
    {
      class: 'Int',
      name:  'second',
      help:  'The second of the current minute.',
      value: 0
    },
    {
      class: 'Int',
      name:  'minute',
      help:  'The minute of the current hour.',
      value: 0
    },
    {
      class: 'Int',
      name:  'hour',
      help:  'The hour of the current day.',
      value: 0
    },
    {
      class: 'Boolean',
      name: 'isStarted',
      hidden: true
    },
    {
      class: 'Int',
      name: 'startTime_',
      hidden: true
    }
  ],

  methods: [
    function cycle(frequency, a, b) {
      /**
         cycle(frequency)             - cycle between -1 and 1 frequency times a second
         cycle(frequency, amplitude)  - cycle between -amplitude and amplitude frequency times a second
         cycle(frequency, start, end) - cycle between start and end frequency times a second
      */
      var s = Math.sin(this.time/1000*frequency*Math.PI*2);
      if ( arguments.length === 1 ) return s;
      if ( arguments.length === 2 ) return s * a;
      return a + (1 + s) * (b-a)/2;
    }
  ],

  actions: [
    {
      name:  'start',
      help:  'Start the timer.',
      isEnabled: function(isStarted) { return ! isStarted; },
      code:      function() { this.isStarted = true; this.tick(); }
    },
    {
      name:  'step',
      help:  'Step the timer.',
      code: function() {
        this.i++;
        this.time  += this.interval * this.timeWarp;
        this.second = this.time /    1000 % 60 << 0;
        this.minute = this.time /   60000 % 60 << 0;
        this.hour   = this.time / 3600000 % 24 << 0;
      }
    },
    {
      name:  'stop',
      help:  'Stop the timer.',
      isEnabled: function(isStarted) { return isStarted; },
      code:      function() { this.isStarted = false; }
    }
  ],

  listeners: [
    {
      name: 'tick',
      isFramed: true,
      code: function(e) {
        if ( ! this.isStarted ) return;

        var prevTime = this.startTime_;
        this.startTime_ = Date.now();
        this.interval = Math.min(100, this.startTime_ - prevTime);
        this.step();
        this.tick();
      }
    }
  ]
});
<|endoftext|>


<commit_before>/** Simulator module
 *
 * @module simulator
 */

import {CycleStopOperator} from './operator'

/** Executes the simulator for a single cycle.
 *
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let cycle = (state) => {
    //An operation can change the ops that will execute in
    //the next cycle (but only in the next)
    //Operations should not do inconsistent changes between them...
    for (let operator of state.operators) {
        operator.change(state)
    }
    state.cycle += 1
}

/**
 * Do n cycles of simulation
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let do_n_cycles = (n, individuals, operators, previous_cycle=0,
    callback) => {
    let add_operators = operators.slice()
    add_operators.push(new CycleStopOperator(n + previous_cycle))
        if (callback) {
        do_async_cycles(individuals, add_operators, previous_cycle, {}, callback)
    }
    else {
        return do_unspecified_cycles(individuals, add_operators, previous_cycle)
    }
}

/**
 * Do unspecified cycles of simulation.
 *
 * One operator will add a stop=true to global_parameters
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let do_unspecified_cycles = (individuals, operators, previous_cycle=0) => {
    let state = {
        global_parameters: {stop: false}, individuals,
        operators, cycle: previous_cycle
    }
    while (state.global_parameters.stop === false) {
        cycle(state)
    }
    return state
}

/**
 * Do async (unspecified) cycles of simulation.
 *
 * One operator will add a stop=true to global_parameters
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 * @param callback
 */
export let do_async_cycles = (individuals, operators,
    previous_cycle=0, global_parameters={}, callback) => {
    let state = {
        global_parameters: {stop: false}, individuals,
        operators, cycle: previous_cycle
    }
    cycle(state)
    let return_callback
    if (!state.global_parameters.stop) {
        return_callback = do_async_cycles.bind(null, individuals, operators,
            previous_cycle + 1, state.global_parameters, callback)
    }
    callback(state, return_callback)
}<commit_msg>async simulator<commit_after>/** Simulator module
 *
 * @module simulator
 */

import {CycleStopOperator} from './operator'

/** Executes the simulator for a single cycle.
 *
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let cycle = (state) => {
    //An operation can change the ops that will execute in
    //the next cycle (but only in the next)
    //Operations should not do inconsistent changes between them...
    for (let operator of state.operators) {
        operator.change(state)
    }
    state.cycle += 1
}

/**
 * Do n cycles of simulation
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let do_n_cycles = (n, individuals, operators, previous_cycle=0,
    callback) => {
    let add_operators = operators.slice()
    add_operators.push(new CycleStopOperator(n + previous_cycle))
        if (callback) {
        do_async_cycles(individuals, add_operators, previous_cycle, {}, callback)
    }
    else {
        return do_unspecified_cycles(individuals, add_operators, previous_cycle)
    }
}

/**
 * Do unspecified cycles of simulation.
 *
 * One operator will add a stop=true to global_parameters
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 */
export let do_unspecified_cycles = (individuals, operators, previous_cycle=0) => {
    let state = {
        global_parameters: {stop: false}, individuals,
        operators, cycle: previous_cycle
    }
    while (state.global_parameters.stop === false) {
        cycle(state)
    }
    return state
}

/**
 * Do async (unspecified) cycles of simulation.
 *
 * One operator will add a stop=true to global_parameters
 *
 * @param {integer} number of cycles
 * @param {individuals[]} individuals List of individuals
 * @param {BaseOperator[]} operators List of operators
 * @param {integer} operator
 * @param callback
 */
export let do_async_cycles = (individuals, operators,
    previous_cycle=0, global_parameters={}, callback) => {
    let state = {
        global_parameters: {stop: false}, individuals,
        operators, cycle: previous_cycle
    }
    cycle(state)
    let return_callback
    if (!state.global_parameters.stop) {
        return_callback = do_async_cycles.bind(null, state.individuals,
            state.operators,
            previous_cycle + 1, state.global_parameters, callback)
    }
    callback(state, return_callback)
}<|endoftext|>