<commit_before>/**
* Copyright (c) Microsoft.  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.
*/

// Module dependencies.
var http = require('http');
var url = require('url');
var util = require('util');
var qs = require('qs');
var crypto = require('crypto');
var xml2js = require('xml2js');

var azureutil = require('../../util/util');

var StorageServiceSettings = require('../core/storageservicesettings');

var ServiceClient = require('./serviceclient');
var Constants = require('../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HttpConstants = Constants.HttpConstants;
var Logger = require('../../diagnostics/logger');

// Expose 'StorageServiceClient'.
exports = module.exports = StorageServiceClient;

// Validation error messages
StorageServiceClient.incorrectStorageAccountErr = 'You must supply an account name or use the environment variable AZURE_STORAGE_ACCOUNT if you are not running in the emulator.';
StorageServiceClient.incorrectStorageAccessKeyErr = 'You must supply an account key or use the environment variable AZURE_STORAGE_ACCESS_KEY if you are not running in the emulator.';

/**
* Creates a new ServiceClient object.
*
* @constructor
* @param {string} storageAccount           The storage account.
* @param {string} storageAccessKey         The storage access key.
* @param {string} host                     The host for the service.
* @param {bool}   usePathStyleUri          Boolean value indicating wether to use path style uris.
* @param {object} authenticationProvider   The authentication provider object (e.g. sharedkey / sharedkeytable / sharedaccesssignature).
*/
function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, authenticationProvider) {
  this._setAccountCredentials(storageAccount, storageAccessKey);
  this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
  this.usePathStyleUri = usePathStyleUri;

  StorageServiceClient.super_.call(this, host, authenticationProvider);

  this._initDefaultFilter();
}

util.inherits(StorageServiceClient, ServiceClient);

/**
* Gets the storage settings.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string} [host]                              The host address.
*
* @return {StorageServiceSettings}
*/
StorageServiceClient.getStorageSettings = function (storageAccountOrConnectionString, storageAccessKey, host) {
  var storageServiceSettings;

  if (storageAccountOrConnectionString && !storageAccessKey) {
    // If storageAccountOrConnectionString was passed and no accessKey was passed, assume connection string
    storageServiceSettings = StorageServiceSettings.createFromConnectionString(storageAccountOrConnectionString);
  } else if (!(storageAccountOrConnectionString && storageAccessKey) && ServiceClient.isEmulated()) {
    // Dev storage scenario
    storageServiceSettings = StorageServiceSettings.getDevelopmentStorageAccountSettings();
  } else {
    // Explicit or environment variable credentials scenario
    storageServiceSettings = StorageServiceSettings._getStorageSettingsExplicitOrEnvironment(
      storageAccountOrConnectionString,
      storageAccessKey,
      host);
  }

  return storageServiceSettings;
};

/**
* Gets the storage settings from the parameters or environment variables.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string} [host]                              The host address.
*
* @return {StorageServiceSettings}
*/
StorageServiceClient._getStorageSettingsExplicitOrEnvironment = function (storageAccount, storageAccessKey, host) {
  var usePathStyleUri = false;

  if (!storageAccountOrConnectionString) {
    storageAccountOrConnectionString = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
  }

  if (!storageAccessKey) {
    storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
  }

  // Default endpoints
  var blobendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_BLOB_HOST });
  var tableendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_TABLE_HOST });
  var queueendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_QUEUE_HOST });

  if (host) {
    var parsedHost = ServiceClient._parseHost(host);

    var parsedHostUrl = url.format(parsedHost);
    if (parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_BLOB_HOST)) ||
        parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_TABLE_HOST)) ||
        parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_QUEUE_HOST))) {
      usePathStyleUri = true;
    }

    blobendpoint = url.format(parsedHostUrl);
    tableendpoint = url.format(parsedHostUrl);
    queueendpoint = url.format(parsedHostUrl);
  }

  var settings = {
    accountname: storageAccountOrConnectionString,
    accountkey: storageAccessKey,
    blobendpoint: blobendpoint,
    tableendpoint: tableendpoint,
    queueendpoint: queueendpoint
  };

  var storageServiceSettings = StorageServiceSettings.createFromSettings(settings);
  storageServiceSettings._usePathStyleUri = usePathStyleUri;

  return storageServiceSettings;
};

/**
* Builds the request options to be passed to the http.request method.
*
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object}      options     The request options.
* @param {function(error, requestOptions)}  callback  The callback function.
* @return {undefined}
*/
StorageServiceClient.prototype._buildRequestOptions = function (webResource, options, callback) {
  var self = this;

  if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_TYPE]) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, '');
  }

  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_LENGTH, 0);
  } else if(webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_LENGTH];
  }

  webResource.addOptionalHeader(HeaderConstants.STORAGE_VERSION_HEADER, this.apiVersion);
  webResource.addOptionalHeader(HeaderConstants.DATE_HEADER, new Date().toUTCString());
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_HEADER, 'application/atom+xml,application/xml');
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8');

  webResource.addOptionalHeader(HeaderConstants.HOST_HEADER, this.host + ':' + this.port);

  if (options) {
    if (options.timeoutIntervalInMs) {
      webResource.addOptionalQueryParam(QueryStringConstants.TIMEOUT, options.timeoutIntervalInMs);
    }

    if (options.accessConditions) {
      webResource.addOptionalAccessConditionHeader(options.accessConditions);
    }

    if (options.sourceAccessConditions) {
      webResource.addOptionalSourceAccessConditionHeader(options.sourceAccessConditions);
    }
  }

  // Sets the request url in the web resource.
  this._setRequestUrl(webResource);

  // Now that the web request is finalized, sign it
  this.authenticationProvider.signRequest(webResource, function (error) {
    var requestOptions = null;

    if (!error) {
      requestOptions = {
        url: url.format({
          protocol: self._isHttps() ? 'https:' : 'http:',
          hostname: self.host,
          port: self.port,
          pathname: webResource.path + webResource.getQueryString(true)
        }),
        method: webResource.httpVerb,
        headers: webResource.headers
      };

      self._setRequestOptionsProxy(requestOptions);
    }

    callback(error, requestOptions);
  });
};

/**
* Retrieves the normalized path to be used in a request.
* This takes into consideration the usePathStyleUri object field
* which specifies if the request is against the emulator or against
* the live service. It also adds a leading "/" to the path in case
* it's not there before.
*
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
StorageServiceClient.prototype._getPath = function (path) {
  if (path === null || path === undefined) {
    path = '/';
  } else if (path.indexOf('/') !== 0) {
    path = '/' + path;
  }

  if (this.usePathStyleUri) {
    path = '/' + this.storageAccount + path;
  }

  return path;
};

/**
* Sets the account credentials taking into consideration the isEmulated value and the environment variables:
* AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY.
*
* @param {string} storageAccount          The storage account.
* @param {string} storageAccessKey        The storage access key.
* @return {undefined}
*/
StorageServiceClient.prototype._setAccountCredentials = function (storageAccount, storageAccessKey) {
  if (azureutil.objectIsNull(storageAccount)) {
    if (process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT]) {
      storageAccount = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
    } else if (ServiceClient.isEmulated()) {
      storageAccount = ServiceClient.DEVSTORE_STORAGE_ACCOUNT;
    }
  }

  if (azureutil.objectIsNull(storageAccessKey)) {
    if (process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY]) {
      storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
    } else if (ServiceClient.isEmulated()) {
      storageAccessKey = ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY;
    }
  }

  if (!azureutil.objectIsString(storageAccount) || azureutil.stringIsEmpty(storageAccount)) {
    throw new Error(StorageServiceClient.incorrectStorageAccountErr);
  }

  if (!azureutil.objectIsString(storageAccessKey) || azureutil.stringIsEmpty(storageAccessKey)) {
    throw new Error(StorageServiceClient.incorrectStorageAccessKeyErr);
  }

  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
};<commit_msg>Fixing reference.<commit_after>/**
* Copyright (c) Microsoft.  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.
*/

// Module dependencies.
var http = require('http');
var url = require('url');
var util = require('util');
var qs = require('qs');
var crypto = require('crypto');
var xml2js = require('xml2js');

var azureutil = require('../../util/util');

var StorageServiceSettings = require('../core/storageservicesettings');

var ServiceClient = require('./serviceclient');
var Constants = require('../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HttpConstants = Constants.HttpConstants;
var Logger = require('../../diagnostics/logger');

// Expose 'StorageServiceClient'.
exports = module.exports = StorageServiceClient;

// Validation error messages
StorageServiceClient.incorrectStorageAccountErr = 'You must supply an account name or use the environment variable AZURE_STORAGE_ACCOUNT if you are not running in the emulator.';
StorageServiceClient.incorrectStorageAccessKeyErr = 'You must supply an account key or use the environment variable AZURE_STORAGE_ACCESS_KEY if you are not running in the emulator.';

/**
* Creates a new ServiceClient object.
*
* @constructor
* @param {string} storageAccount           The storage account.
* @param {string} storageAccessKey         The storage access key.
* @param {string} host                     The host for the service.
* @param {bool}   usePathStyleUri          Boolean value indicating wether to use path style uris.
* @param {object} authenticationProvider   The authentication provider object (e.g. sharedkey / sharedkeytable / sharedaccesssignature).
*/
function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, authenticationProvider) {
  this._setAccountCredentials(storageAccount, storageAccessKey);
  this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
  this.usePathStyleUri = usePathStyleUri;

  StorageServiceClient.super_.call(this, host, authenticationProvider);

  this._initDefaultFilter();
}

util.inherits(StorageServiceClient, ServiceClient);

/**
* Gets the storage settings.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string} [host]                              The host address.
*
* @return {StorageServiceSettings}
*/
StorageServiceClient.getStorageSettings = function (storageAccountOrConnectionString, storageAccessKey, host) {
  var storageServiceSettings;

  if (storageAccountOrConnectionString && !storageAccessKey) {
    // If storageAccountOrConnectionString was passed and no accessKey was passed, assume connection string
    storageServiceSettings = StorageServiceSettings.createFromConnectionString(storageAccountOrConnectionString);
  } else if (!(storageAccountOrConnectionString && storageAccessKey) && ServiceClient.isEmulated()) {
    // Dev storage scenario
    storageServiceSettings = StorageServiceSettings.getDevelopmentStorageAccountSettings();
  } else {
    // Explicit or environment variable credentials scenario
    storageServiceSettings = StorageServiceClient._getStorageSettingsExplicitOrEnvironment(
      storageAccountOrConnectionString,
      storageAccessKey,
      host);
  }

  return storageServiceSettings;
};

/**
* Gets the storage settings from the parameters or environment variables.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string} [host]                              The host address.
*
* @return {StorageServiceSettings}
*/
StorageServiceClient._getStorageSettingsExplicitOrEnvironment = function (storageAccount, storageAccessKey, host) {
  var usePathStyleUri = false;

  if (!storageAccountOrConnectionString) {
    storageAccountOrConnectionString = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
  }

  if (!storageAccessKey) {
    storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
  }

  // Default endpoints
  var blobendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_BLOB_HOST });
  var tableendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_TABLE_HOST });
  var queueendpoint = url.format({ protocol: 'http:', hostname: storageAccountOrConnectionString + '.' + ServiceClient.CLOUD_QUEUE_HOST });

  if (host) {
    var parsedHost = ServiceClient._parseHost(host);

    var parsedHostUrl = url.format(parsedHost);
    if (parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_BLOB_HOST)) ||
        parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_TABLE_HOST)) ||
        parsedHostUrl === url.format(ServiceClient._parseHost(ServiceClient.DEVSTORE_QUEUE_HOST))) {
      usePathStyleUri = true;
    }

    blobendpoint = url.format(parsedHostUrl);
    tableendpoint = url.format(parsedHostUrl);
    queueendpoint = url.format(parsedHostUrl);
  }

  var settings = {
    accountname: storageAccountOrConnectionString,
    accountkey: storageAccessKey,
    blobendpoint: blobendpoint,
    tableendpoint: tableendpoint,
    queueendpoint: queueendpoint
  };

  var storageServiceSettings = StorageServiceSettings.createFromSettings(settings);
  storageServiceSettings._usePathStyleUri = usePathStyleUri;

  return storageServiceSettings;
};

/**
* Builds the request options to be passed to the http.request method.
*
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object}      options     The request options.
* @param {function(error, requestOptions)}  callback  The callback function.
* @return {undefined}
*/
StorageServiceClient.prototype._buildRequestOptions = function (webResource, options, callback) {
  var self = this;

  if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_TYPE]) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, '');
  }

  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_LENGTH, 0);
  } else if(webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_LENGTH];
  }

  webResource.addOptionalHeader(HeaderConstants.STORAGE_VERSION_HEADER, this.apiVersion);
  webResource.addOptionalHeader(HeaderConstants.DATE_HEADER, new Date().toUTCString());
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_HEADER, 'application/atom+xml,application/xml');
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8');

  webResource.addOptionalHeader(HeaderConstants.HOST_HEADER, this.host + ':' + this.port);

  if (options) {
    if (options.timeoutIntervalInMs) {
      webResource.addOptionalQueryParam(QueryStringConstants.TIMEOUT, options.timeoutIntervalInMs);
    }

    if (options.accessConditions) {
      webResource.addOptionalAccessConditionHeader(options.accessConditions);
    }

    if (options.sourceAccessConditions) {
      webResource.addOptionalSourceAccessConditionHeader(options.sourceAccessConditions);
    }
  }

  // Sets the request url in the web resource.
  this._setRequestUrl(webResource);

  // Now that the web request is finalized, sign it
  this.authenticationProvider.signRequest(webResource, function (error) {
    var requestOptions = null;

    if (!error) {
      requestOptions = {
        url: url.format({
          protocol: self._isHttps() ? 'https:' : 'http:',
          hostname: self.host,
          port: self.port,
          pathname: webResource.path + webResource.getQueryString(true)
        }),
        method: webResource.httpVerb,
        headers: webResource.headers
      };

      self._setRequestOptionsProxy(requestOptions);
    }

    callback(error, requestOptions);
  });
};

/**
* Retrieves the normalized path to be used in a request.
* This takes into consideration the usePathStyleUri object field
* which specifies if the request is against the emulator or against
* the live service. It also adds a leading "/" to the path in case
* it's not there before.
*
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
StorageServiceClient.prototype._getPath = function (path) {
  if (path === null || path === undefined) {
    path = '/';
  } else if (path.indexOf('/') !== 0) {
    path = '/' + path;
  }

  if (this.usePathStyleUri) {
    path = '/' + this.storageAccount + path;
  }

  return path;
};

/**
* Sets the account credentials taking into consideration the isEmulated value and the environment variables:
* AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY.
*
* @param {string} storageAccount          The storage account.
* @param {string} storageAccessKey        The storage access key.
* @return {undefined}
*/
StorageServiceClient.prototype._setAccountCredentials = function (storageAccount, storageAccessKey) {
  if (azureutil.objectIsNull(storageAccount)) {
    if (process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT]) {
      storageAccount = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
    } else if (ServiceClient.isEmulated()) {
      storageAccount = ServiceClient.DEVSTORE_STORAGE_ACCOUNT;
    }
  }

  if (azureutil.objectIsNull(storageAccessKey)) {
    if (process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY]) {
      storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
    } else if (ServiceClient.isEmulated()) {
      storageAccessKey = ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY;
    }
  }

  if (!azureutil.objectIsString(storageAccount) || azureutil.stringIsEmpty(storageAccount)) {
    throw new Error(StorageServiceClient.incorrectStorageAccountErr);
  }

  if (!azureutil.objectIsString(storageAccessKey) || azureutil.stringIsEmpty(storageAccessKey)) {
    throw new Error(StorageServiceClient.incorrectStorageAccessKeyErr);
  }

  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
};<|endoftext|>


<commit_before>'use strict';

var cachedTabs = [];

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.status !== 'loading') return;

  chrome.tabs.executeScript(tabId, {
    code: 'var injected = window.octotreeInjected; window.octotreeInjected = true; console.log("INJECTING DATA '+ tabId + '"); injected;',
    runAt: 'document_start'
  }, function (res) {
    if (chrome.runtime.lastError || // don't continue if error (i.e. page isn't in permission list)
    res[0]) // value of `injected` above: don't inject twice
      return;

    var cssFiles = ['jstree.css', 'octotree.css'];

    var jsFiles = ['jquery.js', 'jquery-ui.js', 'jstree.js'];

    cachedTabs[tabId] = true;

    eachTask([function (cb) {
      return eachItem(cssFiles, inject('insertCSS'), cb);
    }, function (cb) {
      return eachItem(jsFiles, inject('executeScript'), cb);
    }]);

    function inject(fn) {
      return function (file, cb) {
        chrome.tabs[fn](tabId, { file: file, runAt: 'document_start' }, cb);
      };
    }
  });
});

var workingEnvironment = [];
var snippetsList = [];

chrome.runtime.onMessage.addListener(function (req, sender, sendRes) {
  var handler = {
    requestPermissions: function requestPermissions() {
      var urls = (req.urls || []).filter(function (url) {
        return url.trim() !== '';
      }).map(function (url) {
        if (url.slice(-2) === '/*') return url;
        if (url.slice(-1) === '/') return url + '*';
        return url + '/*';
      });

      if (urls.length === 0) {
        sendRes(true);
        removeUnnecessaryPermissions();
      } else {
        chrome.permissions.request({ origins: urls }, function (granted) {
          sendRes(granted);
          removeUnnecessaryPermissions();
        });
      }
      return true;

      function removeUnnecessaryPermissions() {
        var whitelist = urls.concat(['https://github.com/*', 'https://gitlab.com/*']);
        chrome.permissions.getAll(function (permissions) {
          var toBeRemovedUrls = permissions.origins.filter(function (url) {
            return ! ~whitelist.indexOf(url);
          });

          if (toBeRemovedUrls.length) {
            chrome.permissions.remove({ origins: toBeRemovedUrls });
          }
        });
      }
    },
    saveSnippet: function gotReportFromTheTab(data) {
      for (var r in cachedTabs) {
        console.log("DO SOME STUFF");
        console.dir(r);
        chrome.tabs.executeScript(parseInt(r), {
          code: 'console.log("BROADCAST !!!!");'
        });
      }
      return true;
    },
    initialItems: function(payload) {
      console.log("GET INITIAL ITEMS: " + sender.tab.id);
      // has opened snippet
      console.dir(workingEnvironment);
      var pos = workingEnvironment[sender.tab.id];
      if (pos != undefined && pos >= 0) {
        return sendRes({working: pos, snippets: snippetsList});
      }
      console.log("GET INITIAL ITEMS EMPTY");
      sendRes({snippets: snippetsList});
    },
    createSnippet: function(payload) {
      console.log("CREATE SNIPPET !Q!!!! " + snippetsList.length );
      // init snippet by id
      workingEnvironment[sender.tab.id] = snippetsList.length;
      snippetsList.push({title: payload.title, items:[]});
      sendRes({working: workingEnvironment[sender.tab.id]});
    },
    closeSnippet: function(data) {
      workingEnvironment[sender.tab.id] = null;
    },
    addNewItem: function(payload) {
       var pos = workingEnvironment[sender.tab.id];
       console.log("POSITION IS: " + pos);
       console.dir(payload);
       if (pos != undefined) {
         console.log("ADD PAYLOAD");
         snippetsList[pos].items.push(payload);
         sendRes(true);
         return true;
       }
      sendRes(false);
       return false;

    },
    openItem: function(itemId) {
      console.dir(sender.tab);
      chrome.tabs.create({url: "http://google.com", active:true});
      sendRes(true);
    }
  };
  console.log("HANDLE :" + req.type);
  return handler[req.type](req.payload);
});

function eachTask(tasks, done) {
  (function next() {
    var index = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];

    if (index === tasks.length) done && done();else tasks[index](function () {
      return next(++index);
    });
  })();
}

function eachItem(arr, iter, done) {
  var tasks = arr.map(function (item) {
    return function (cb) {
      return iter(item, cb);
    };
  });
  return eachTask(tasks, done);
}
<commit_msg>OPEN GOOGLE TAB<commit_after>'use strict';

var cachedTabs = [];

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.status !== 'loading') return;

  chrome.tabs.executeScript(tabId, {
    code: 'var injected = window.octotreeInjected; window.octotreeInjected = true; console.log("INJECTING DATA '+ tabId + '"); injected;',
    runAt: 'document_start'
  }, function (res) {
    if (chrome.runtime.lastError || // don't continue if error (i.e. page isn't in permission list)
    res[0]) // value of `injected` above: don't inject twice
      return;

    var cssFiles = ['jstree.css', 'octotree.css'];

    var jsFiles = ['jquery.js', 'jquery-ui.js', 'jstree.js'];

    cachedTabs[tabId] = true;

    eachTask([function (cb) {
      return eachItem(cssFiles, inject('insertCSS'), cb);
    }, function (cb) {
      return eachItem(jsFiles, inject('executeScript'), cb);
    }]);

    function inject(fn) {
      return function (file, cb) {
        chrome.tabs[fn](tabId, { file: file, runAt: 'document_start' }, cb);
      };
    }
  });
});

var workingEnvironment = [];
var snippetsList = [];

chrome.runtime.onMessage.addListener(function (req, sender, sendRes) {
  var handler = {
    requestPermissions: function requestPermissions() {
      var urls = (req.urls || []).filter(function (url) {
        return url.trim() !== '';
      }).map(function (url) {
        if (url.slice(-2) === '/*') return url;
        if (url.slice(-1) === '/') return url + '*';
        return url + '/*';
      });

      if (urls.length === 0) {
        sendRes(true);
        removeUnnecessaryPermissions();
      } else {
        chrome.permissions.request({ origins: urls }, function (granted) {
          sendRes(granted);
          removeUnnecessaryPermissions();
        });
      }
      return true;

      function removeUnnecessaryPermissions() {
        var whitelist = urls.concat(['https://github.com/*', 'https://gitlab.com/*']);
        chrome.permissions.getAll(function (permissions) {
          var toBeRemovedUrls = permissions.origins.filter(function (url) {
            return ! ~whitelist.indexOf(url);
          });

          if (toBeRemovedUrls.length) {
            chrome.permissions.remove({ origins: toBeRemovedUrls });
          }
        });
      }
    },
    saveSnippet: function gotReportFromTheTab(data) {
      for (var r in cachedTabs) {
        console.log("DO SOME STUFF");
        console.dir(r);
        chrome.tabs.executeScript(parseInt(r), {
          code: 'console.log("BROADCAST !!!!");'
        });
      }
      return true;
    },
    initialItems: function(payload) {
      console.log("GET INITIAL ITEMS: " + sender.tab.id);
      // has opened snippet
      console.dir(workingEnvironment);
      var pos = workingEnvironment[sender.tab.id];
      if (pos != undefined && pos >= 0) {
        return sendRes({working: pos, snippets: snippetsList});
      }
      console.log("GET INITIAL ITEMS EMPTY");
      sendRes({snippets: snippetsList});
    },
    createSnippet: function(payload) {
      console.log("CREATE SNIPPET !Q!!!! " + snippetsList.length );
      // init snippet by id
      workingEnvironment[sender.tab.id] = snippetsList.length;
      snippetsList.push({title: payload.title, items:[]});
      sendRes({working: workingEnvironment[sender.tab.id]});
    },
    closeSnippet: function(data) {
      workingEnvironment[sender.tab.id] = null;
    },
    addNewItem: function(payload) {
       var pos = workingEnvironment[sender.tab.id];
       console.log("POSITION IS: " + pos);
       console.dir(payload);
       if (pos != undefined) {
         console.log("ADD PAYLOAD");
         snippetsList[pos].items.push(payload);
         sendRes(true);
         return true;
       }
      sendRes(false);
       return false;

    },
    openItem: function(itemId) {
      console.dir(sender.tab);
      chrome.tabs.create({'url': "http://google.com", active:true}, function(x) {
        console.dir(arguments);
      });
      sendRes(true);
    }
  };
  console.log("HANDLE :" + req.type);
  return handler[req.type](req.payload);
});

function eachTask(tasks, done) {
  (function next() {
    var index = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];

    if (index === tasks.length) done && done();else tasks[index](function () {
      return next(++index);
    });
  })();
}

function eachItem(arr, iter, done) {
  var tasks = arr.map(function (item) {
    return function (cb) {
      return iter(item, cb);
    };
  });
  return eachTask(tasks, done);
}
<|endoftext|>


<commit_before>/**
 * Created by kuroky360 on 16-1-25.
 */
!function(window,document,undefined){
    // initial variable
    var angular=window.angular||{},
        angularModule,
        toString=Object.prototype.toString,
        slice=[].slice,
        splice=[].splice,
        isArray=Array.isArray,
        msie,
        jQuery,
        jqLite,
        uid= 0,
        hasOwnProperty=Object.prototype.hasOwnProperty,
        getPrototypeOf=Object.getPrototypeOf,
        version={
            full:'0.0.1',
            major:0,
            minor:0,
            dot:1,
            codeName:'DIY angularjs'
        };

    msie = document.documentMode;
    // shadow & deep
    function copy(){

    }

    //shallow copy fn typically Array or Object
    function shallowCopy(src,dst){
        if(isArray(src)){
            dst = dst || [];
            for(var i= 0,ii=src.length;i<ii;i++){
                dst[i]=src[i];
            }
        }else if(isObject(src)){
            dst = dst||{};
            for(var key in src){
                if(!(key.charAt(0)==='$'&&key.charAt(1)==='$$')){//except $ $$ prefix for angular.
                    dst[key]=src[key];
                }
            }
        }

        return dst||src;
    }

    // a reference is DOM element or wrapped jQuery Element
    function isElement(node){
        return !!(node&&
            (node.nodeName|| //direct element
                (node.attr&&node.prop&&node.find)
            )
        )
    }

    // shadow & deep
    function baseExtend(dst,objs,deep){
        var i, ii,j,jj,obj,src,keys,key;
        for(i=0,ii=objs.length;i<ii;i++){
            obj=objs[i];
            if(!isObject(obj)&&!isFunciton(obj)) continue;
            keys = Object.keys(obj);
            for(j=0,jj=keys.length;j<jj;j++){
                key=keys[j];
                src=obj[key];
                if(deep&&isObject(src)){
                    if(isDate(src)){
                        dst[key]=new Date(src.valueOf());
                    }else if(isRegExp(src)){
                        dst[key]=new RegExp(src);
                    }else if(src.nodeName){
                        dst[key]=src.cloneNode(true);
                    }else if(isElement(src)){
                        dst[key]=src.clone();
                    }else{
                        if(!isObject(dst[key])) dst[key]=isArray(dst[key])?[]:{};
                        dst[key]=baseExtend(dst[key],[src],true);
                    }

                }else{//primitive value string number boolean...
                    dst[key]=src;
                }
            }
        }
        return dst;
    }

    function shallowExtend(dst){
        return baseExtend(dst,slice.call(arguments,1),false);
    }
    // deep merge
    function deepExtend(dst){
        return baseExtend(dst,slice.call(arguments,1),true);
    }
    // inherit
    function inherit(parent,extra){
        return shallowExtend(Object.create(parent),extra);
    }

    ////////////////////////////////////
    // Error handler todo
    ////////////////////////////////////

    ////////////////////////////////////
    // Event handler todo
    ////////////////////////////////////

    ////////////////////////////////////
    // Http $q promise todo
    ////////////////////////////////////

    ////////////////////////////////////
    // dom selectors fn todo
    ////////////////////////////////////

    function jqLite(){
        this.length=0;
    }

    jqLite.prototype={
      //todo
    };
    ////////////////////////////////////
    // fn utils
    ////////////////////////////////////
    function isFunciton(value){return typeof value ==='function';}

    function noop(){}

    function isUndefined(value){return typeof value ==='undefined';}

    function isDefined(value){return typeof value !=='undefined';}

    function isString(value){return typeof value==='string';}

    function isObject(value){return value!==null&&typeof value==='object'}

    function isNumber(value){return typeof value === 'number'}

    function isDate(value){ toString.call(value)==='[object Date]'}

    // isWindow
    function isWindow(obj){
        return obj&&obj.window===window;
    }

    //isFile
    function isFile(obj){
        return toString.call(obj)==='[object File]';
    }

    //isFormData
    function isFormData(obj){
        return toString.call(obj)==='[object FormData]';
    }

    //isBlob
    function isBlob(obj){
        return toString.call(obj)==='[object Blob]';
    }

    //isBoolean
    function isBoolean(obj){
        return typeof obj ==='boolean';
    }

    //isPromiseLike
    function isPromiseLike(obj){
        return obj&&isFunciton(obj.then);
    }

    function lowercase(value){return isString(value)?value.toLowerCase():value}

    function uppercase(value){return isString(value)?value.toUpperCase():value}

    function fromJson(value){
        return isString(value)?JSON.parse(value):value;
    }

    function identity($){return $;}

    //toJson
    function toJson(obj,pretty){
        if(isUndefined(obj)) return undefined;
        if(!isNumber(pretty)){
            pretty= pretty?2:null;
        }
        return JSON.stringify(obj,toJsonReplacer,pretty);
    }
    //toJsonReplacer
    function toJsonReplacer(key,value){
        var val=value;
        if(isString(key)&&key.charAt(0)==='$'&&key.charAt(1)==='$'){//$$ no stringify
            val=undefined;
        }else if(isWindow(val)){
            val='$WINDOW';
        }else if(isScope(val)){
            val='$SCOPE';
        }else if(val&&val===document){
            val='$DOCUMENT';
        }

        return val;
    }

    function valueFn(value){
        return function(){
            return value;
        }
    }

    function toInt(value){
        return parseInt(value,10);
    }

    function forEachSorted(obj,iterator,context){
        var keys=Object.keys(obj).sort();
        for(var i= 0;i<keys.length;i++){
            iterator.call(context,obj[keys[i]],keys[i]);
        }
        return keys;
    }

    //function isArray(value){ return Array.isArray(value);}

    // check RegExp
    function isRegExp(value){ return toString.call(value)==='[object RegExp]';}

    //reverse params
    function reverseParams(iteratorFn){
        return function(value,key){
            iteratorFn(key,value);
        };
    }

    // check blankObject -->with a null prototype
    function isBlankObject(value){
        return value!==null&&typeof value==='object'&& !getPrototypeOf(value);
    }

    // check window
    function isWindow(obj){
        return obj&&obj.window===obj;
    }

    // isScope
    function isScope(obj){
        return obj&&obj.$evalAsync&&obj.$watch;
    }
    // is ArrayLike NodeList arguments jqLite string
    function isArrayLike(obj){
        if(obj===null||isWindow(obj)) return false;
        if(isArray(obj)||isString(obj)||jqLite&&obj instanceof jqLite) return true;
        var length = 'length' in Object(obj)&&obj.length;
        return isNumber(length) && (length >=0 && (length-1) in obj ||typeof  obj.item ==='function');
    }

    function nextUid(){
        return ++uid;
    }

    //forEach fn
    function forEach(obj,iterator,context){
        var key,
            length;
        if(obj){
            if(isFunciton(obj)){
                for(key in obj){
                    if('length'!==key&&'prototype'!==key&&'name'!==key&&(!obj.hasOwnProperty||obj.hasOwnProperty(key))){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }else if(isArray(obj)||isArrayLike(obj)){
                var isPrimitive = typeof obj!=='object';
                for(key=0,length=obj.length;key<length;key++){
                    if(isPrimitive||key in obj)
                    iterator.call(context,obj[key],key,obj);
                }
            }else if(obj.forEach&&obj.forEach!==forEach){
                obj.forEach(iterator,context,obj);
            }else if(isBlankObject(obj)){
                for(key in obj){ //no inheritance :fast path
                    iterator.call(context,obj[key],key,obj);
                }
            }else if(typeof obj.hasOwnProperty!=='function'){//maybe no hasOwnProperty method
                for(key in obj){
                    if(hasOwnProperty.call(obj,key)){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }else{
                for(key in obj){
                    if(obj.hasOwnProperty(key)){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }
        }
        return obj;
    }

    // Creates a new object without a prototype.
    function createMap(){
        return Object.create(null);
    }

    // module loader setup
    function setupModuleLoader(window) {

        function ensure(obj, child, factory) {
            return obj[child] || (obj[child] = factory());
        }

        var angular = ensure(window, angular, Object);

        return ensure(angular, 'module', function () {
            var modules = {};

            return function module(name, require, config) {
                if (require && modules.hasOwnProperty(name)) {
                    modules[name] = null;
                }
                return ensure(modules, name, function () {
                    var invokeQueue=[];
                    var configBlocks=[];
                    var runBlocks=[];
                    var moduleInstance={
                        _invokeQueue:invokeQueue,
                        _configBlock:configBlocks,
                        _runBlocks:runBlocks,
                        _require:require,
                        _name:name
                    };

                    function invokeLater(provider,method,insertMethod,queue){
                        if(!queue) queue=invokeQueue;
                        return function(){
                            queue[insertMethod||'push']([provider,method,arguments]);
                            return moduleInstance;
                        }
                    }

                    function invokeLaterAndSetModuleName(provider,method){
                        if(isFunciton(method)) method.$$moduleName=name;
                        return function(recipeName,factoryName){
                            invokeQueue.push([provider,method,arguments]);
                            return moduleInstance;
                        };
                    }
                });
            };
        });
    }

    //bootstrap fn
    function bootstrap(element,modules,config){
        var modules=modules||[],
            instaneInjector;

        modules.unshift('ng');
        modules.push(['$provide',function($provide){
            $provide.value('$rootElement',element);
        }]);

        instaneInjector = createInjector(modules);
    }

    // annotate fn
    function annotate(fn){
        var $injectArray=[];
        return $injectArray;
    }

    //injector creator
    function createInjector(modulesToLoad){
        var providerSufix='Provider',
            INSTANTING={},
            path=[],
            providerCache={
                $provide:{
                    provider:supportObject(provider),
                    factory:supportObject(factory),
                    service:supportObject(service),
                    value:supportObject(value)
                }
            },
            providerInjector=(providerCache.$injector=createInternalInjector(providerCache,function(seviceName,caller){
                throw new Error('can not found provider!');
            })),
            instanceCache={},
            instanceInjector=(instanceCache.$injector=createInternalInjector(instanceCache,function(serviceName,caller){
                var provider = providerInjector.get(serviceName+providerSufix,caller);
                instanceCache.invoke(provider.$get,provider,undefined,serviceName);
            }));
        //forEach load modules
        forEach(loadMoules(modulesToLoad),function(fn){if(fn) instanceInjector.invoke(fn);});

        ////////////////////////////////////
        // Module Loading
        ////////////////////////////////////
        function loadMoules(modules){
            var runBlocks=[];
            //todo
            return runBlocks;
        }

        //support object arg
        function supportObject(delegate){
            return function(key,value){
                if(isObject(key)){
                    forEach(key,reverseParams(delegate))
                }else{
                    return delegate(key,value);
                }
            }
        }
        //provider
        function provider(name,provider_){
            if(isFunciton(provider_)||isArray(provider_)){
                provider_ = providerInjector.instantiate(provider_);
            }
            if(!provider_.$get){
                throw new Error('do not have $get method!');
            }
            return  providerCache[name+providerSufix]=provider_;
        }

        function enForceReturnValue(factoryFn){
            return function(){
                var result=instanceCache.invoke(factoryFn);
                return result;
            };
        }

        //facotry
        function factory(name,factoryFn,enForce){
            return provider(name,{
                $get:enForce===false?enForceReturnValue(factoryFn):factoryFn
            });
        }

        //service
        function service(name,contructor){
            return factory(name,['$injector',function($injector){
                return $injector.instantiate(contructor);
            }]);
        }

        //value
        function value(name,value){
            return factory(name,valueFn(value),false);
        }

        ////////////////////////////////////
        // internal injector
        ////////////////////////////////////
        function createInternalInjector(cache,factory){

            // get service
            function getService(serviceName,caller){
                if(cache.hasOwnProperty(serviceName)){
                    if(cache[serviceName]===INSTANTING){
                        throw new Error('重复循环依赖！');
                    }
                    return cache[serviceName];
                }else{
                    cache[serviceName]=INSTANTING;
                    //path.push(serviceName);
                    return  cache[serviceName]=factory(serviceName,caller);
                }
            }

            //invoke fn
            function invoke(fn,self,locals,serviceName){
                var length,
                    args=[],
                    i,
                    item,
                    annotateArray=annotate(fn);
                for(i=0,length=annotateArray.length;i<length;i++){
                    item=annotateArray[i];
                    args.push(locals&&locals.hasOwnProperty(item)?locals[item]:getService(item,serviceName));
                }

                if(isArray(fn)){
                    fn=fn[fn.length-1];
                }

                return fn.call(self,args);
            }

            // intantiate instace
            function instantiate(type,locals,serviceName){
                var instance = Object.create((isArray(type)? type[type.length-1]:type).prototype||null);
                var returnValue = invoke(type,instance,locals,serviceName);

                return isObject(returnValue)|| isFunciton(returnValue)?returnValue:instance;
            }

            return {
                instantiate:instantiate,
                invoke:invoke,
                get:getService
            };
        }
    }

    // expose angular
    function publishExternalAPI(angular){
        shallowExtend(angular,{
            noop:noop,
            version:version,
            isFunction:isFunciton,
            isArray:isArray,
            isNumber:isNumber,
            isDefined:isDefined,
            isUndefined:isUndefined,
            isString:isString,
            isBlankObject:isBlankObject,
            isRegExp:isRegExp,
            isDate:isDate,
            isObject:isObject,
            isElement:isElement,
            identity:identity,
            fromJson:fromJson,
            toJson:toJson,
            copy:copy,
            shallowExtend:shallowExtend,
            deepExtend:deepExtend,
            bootstrap:bootstrap,
            createInjector:createInjector,
            forEach:forEach,
            lowercase:lowercase,
            uppercase:uppercase
        });
        angularModule=setupModuleLoader(window);
        angularModule('ng',['ngLocale'],['$provide',function($provide){
           //todo
            $provide.provider('$compile',$CompileProvider).directive({});//lots of directives
            $provide.provider({});//lots of providers
        }]);
    }
    //compileProvider
    function $CompileProvider(){
        this.directive=function(){};
    }
    //Promise
    function Promise(){
        this.$$state={status:0};
    }

    function Defferred(){

    }

    //q factory fn
    function qFactory(nextTick,exceptionHandler){

        var $Q;
        //TODO
        return $Q;
    }
    // qprovider
    function $QProvider(){
        this.get = ['$rootScope','$exceptionHandler',function($rootScope,$exceptionHandler){
            return qFactory(function(callback){
                $rootScope.$evalAsync(callback);
            },$exceptionHandler)
        }];
    }
    //first check jquery

    //publish angular

    //bootstrap when dom ready

}(window,document);

<commit_msg>add hasCustomToString<commit_after>/**
 * Created by kuroky360 on 16-1-25.
 */
!function(window,document,undefined){
    // initial variable
    var angular=window.angular||{},
        angularModule,
        toString=Object.prototype.toString,
        slice=[].slice,
        splice=[].splice,
        isArray=Array.isArray,
        msie,
        jQuery,
        jqLite,
        uid= 0,
        hasOwnProperty=Object.prototype.hasOwnProperty,
        getPrototypeOf=Object.getPrototypeOf,
        version={
            full:'0.0.1',
            major:0,
            minor:0,
            dot:1,
            codeName:'DIY angularjs'
        };

    msie = document.documentMode;
    // shadow & deep
    function copy(){

    }

    //shallow copy fn typically Array or Object
    function shallowCopy(src,dst){
        if(isArray(src)){
            dst = dst || [];
            for(var i= 0,ii=src.length;i<ii;i++){
                dst[i]=src[i];
            }
        }else if(isObject(src)){
            dst = dst||{};
            for(var key in src){
                if(!(key.charAt(0)==='$'&&key.charAt(1)==='$$')){//except $ $$ prefix for angular.
                    dst[key]=src[key];
                }
            }
        }

        return dst||src;
    }

    // a reference is DOM element or wrapped jQuery Element
    function isElement(node){
        return !!(node&&
            (node.nodeName|| //direct element
                (node.attr&&node.prop&&node.find)
            )
        )
    }

    // shadow & deep
    function baseExtend(dst,objs,deep){
        var i, ii,j,jj,obj,src,keys,key;
        for(i=0,ii=objs.length;i<ii;i++){
            obj=objs[i];
            if(!isObject(obj)&&!isFunciton(obj)) continue;
            keys = Object.keys(obj);
            for(j=0,jj=keys.length;j<jj;j++){
                key=keys[j];
                src=obj[key];
                if(deep&&isObject(src)){
                    if(isDate(src)){
                        dst[key]=new Date(src.valueOf());
                    }else if(isRegExp(src)){
                        dst[key]=new RegExp(src);
                    }else if(src.nodeName){
                        dst[key]=src.cloneNode(true);
                    }else if(isElement(src)){
                        dst[key]=src.clone();
                    }else{
                        if(!isObject(dst[key])) dst[key]=isArray(dst[key])?[]:{};
                        dst[key]=baseExtend(dst[key],[src],true);
                    }

                }else{//primitive value string number boolean...
                    dst[key]=src;
                }
            }
        }
        return dst;
    }

    function shallowExtend(dst){
        return baseExtend(dst,slice.call(arguments,1),false);
    }
    // deep merge
    function deepExtend(dst){
        return baseExtend(dst,slice.call(arguments,1),true);
    }
    // inherit
    function inherit(parent,extra){
        return shallowExtend(Object.create(parent),extra);
    }

    ////////////////////////////////////
    // Error handler todo
    ////////////////////////////////////

    ////////////////////////////////////
    // Event handler todo
    ////////////////////////////////////

    ////////////////////////////////////
    // Http $q promise todo
    ////////////////////////////////////

    ////////////////////////////////////
    // dom selectors fn todo
    ////////////////////////////////////

    function jqLite(){
        this.length=0;
    }

    jqLite.prototype={
      //todo
    };
    ////////////////////////////////////
    // fn utils
    ////////////////////////////////////
    function isFunciton(value){return typeof value ==='function';}

    function noop(){}

    function isUndefined(value){return typeof value ==='undefined';}

    function isDefined(value){return typeof value !=='undefined';}

    function isString(value){return typeof value==='string';}

    function isObject(value){return value!==null&&typeof value==='object'}

    function isNumber(value){return typeof value === 'number'}

    function isDate(value){ toString.call(value)==='[object Date]'}

    // isWindow
    function isWindow(obj){
        return obj&&obj.window===window;
    }

    //isFile
    function isFile(obj){
        return toString.call(obj)==='[object File]';
    }

    //isFormData
    function isFormData(obj){
        return toString.call(obj)==='[object FormData]';
    }

    //isBlob
    function isBlob(obj){
        return toString.call(obj)==='[object Blob]';
    }

    //isBoolean
    function isBoolean(obj){
        return typeof obj ==='boolean';
    }

    //isPromiseLike
    function isPromiseLike(obj){
        return obj&&isFunciton(obj.then);
    }

    function lowercase(value){return isString(value)?value.toLowerCase():value}

    function uppercase(value){return isString(value)?value.toUpperCase():value}

    function fromJson(value){
        return isString(value)?JSON.parse(value):value;
    }

    function identity($){return $;}

    //toJson
    function toJson(obj,pretty){
        if(isUndefined(obj)) return undefined;
        if(!isNumber(pretty)){
            pretty= pretty?2:null;
        }
        return JSON.stringify(obj,toJsonReplacer,pretty);
    }
    //toJsonReplacer
    function toJsonReplacer(key,value){
        var val=value;
        if(isString(key)&&key.charAt(0)==='$'&&key.charAt(1)==='$'){//$$ no stringify
            val=undefined;
        }else if(isWindow(val)){
            val='$WINDOW';
        }else if(isScope(val)){
            val='$SCOPE';
        }else if(val&&val===document){
            val='$DOCUMENT';
        }

        return val;
    }

    function valueFn(value){
        return function(){
            return value;
        }
    }

    function toInt(value){
        return parseInt(value,10);
    }

    function forEachSorted(obj,iterator,context){
        var keys=Object.keys(obj).sort();
        for(var i= 0;i<keys.length;i++){
            iterator.call(context,obj[keys[i]],keys[i]);
        }
        return keys;
    }

    //function isArray(value){ return Array.isArray(value);}

    // check RegExp
    function isRegExp(value){ return toString.call(value)==='[object RegExp]';}

    //reverse params
    function reverseParams(iteratorFn){
        return function(value,key){
            iteratorFn(key,value);
        };
    }

    // check blankObject -->with a null prototype
    function isBlankObject(value){
        return value!==null&&typeof value==='object'&& !getPrototypeOf(value);
    }

    // check window
    function isWindow(obj){
        return obj&&obj.window===obj;
    }

    // isScope
    function isScope(obj){
        return obj&&obj.$evalAsync&&obj.$watch;
    }
    // is ArrayLike NodeList arguments jqLite string
    function isArrayLike(obj){
        if(obj===null||isWindow(obj)) return false;
        if(isArray(obj)||isString(obj)||jqLite&&obj instanceof jqLite) return true;
        var length = 'length' in Object(obj)&&obj.length;
        return isNumber(length) && (length >=0 && (length-1) in obj ||typeof  obj.item ==='function');
    }

    // customToString
    function hasCustomToString(obj){
        return isFunciton(obj.toString)&&obj.toString!==toString;
    }

    function nextUid(){
        return ++uid;
    }

    //forEach fn
    function forEach(obj,iterator,context){
        var key,
            length;
        if(obj){
            if(isFunciton(obj)){
                for(key in obj){
                    if('length'!==key&&'prototype'!==key&&'name'!==key&&(!obj.hasOwnProperty||obj.hasOwnProperty(key))){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }else if(isArray(obj)||isArrayLike(obj)){
                var isPrimitive = typeof obj!=='object';
                for(key=0,length=obj.length;key<length;key++){
                    if(isPrimitive||key in obj)
                    iterator.call(context,obj[key],key,obj);
                }
            }else if(obj.forEach&&obj.forEach!==forEach){
                obj.forEach(iterator,context,obj);
            }else if(isBlankObject(obj)){
                for(key in obj){ //no inheritance :fast path
                    iterator.call(context,obj[key],key,obj);
                }
            }else if(typeof obj.hasOwnProperty!=='function'){//maybe no hasOwnProperty method
                for(key in obj){
                    if(hasOwnProperty.call(obj,key)){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }else{
                for(key in obj){
                    if(obj.hasOwnProperty(key)){
                        iterator.call(context,obj[key],key,obj);
                    }
                }
            }
        }
        return obj;
    }

    // Creates a new object without a prototype.
    function createMap(){
        return Object.create(null);
    }

    // module loader setup
    function setupModuleLoader(window) {

        function ensure(obj, child, factory) {
            return obj[child] || (obj[child] = factory());
        }

        var angular = ensure(window, angular, Object);

        return ensure(angular, 'module', function () {
            var modules = {};

            return function module(name, require, config) {
                if (require && modules.hasOwnProperty(name)) {
                    modules[name] = null;
                }
                return ensure(modules, name, function () {
                    var invokeQueue=[];
                    var configBlocks=[];
                    var runBlocks=[];
                    var moduleInstance={
                        _invokeQueue:invokeQueue,
                        _configBlock:configBlocks,
                        _runBlocks:runBlocks,
                        _require:require,
                        _name:name
                    };

                    function invokeLater(provider,method,insertMethod,queue){
                        if(!queue) queue=invokeQueue;
                        return function(){
                            queue[insertMethod||'push']([provider,method,arguments]);
                            return moduleInstance;
                        }
                    }

                    function invokeLaterAndSetModuleName(provider,method){
                        if(isFunciton(method)) method.$$moduleName=name;
                        return function(recipeName,factoryName){
                            invokeQueue.push([provider,method,arguments]);
                            return moduleInstance;
                        };
                    }
                });
            };
        });
    }

    //bootstrap fn
    function bootstrap(element,modules,config){
        var modules=modules||[],
            instaneInjector;

        modules.unshift('ng');
        modules.push(['$provide',function($provide){
            $provide.value('$rootElement',element);
        }]);

        instaneInjector = createInjector(modules);
    }

    // annotate fn
    function annotate(fn){
        var $injectArray=[];
        return $injectArray;
    }

    //injector creator
    function createInjector(modulesToLoad){
        var providerSufix='Provider',
            INSTANTING={},
            path=[],
            providerCache={
                $provide:{
                    provider:supportObject(provider),
                    factory:supportObject(factory),
                    service:supportObject(service),
                    value:supportObject(value)
                }
            },
            providerInjector=(providerCache.$injector=createInternalInjector(providerCache,function(seviceName,caller){
                throw new Error('can not found provider!');
            })),
            instanceCache={},
            instanceInjector=(instanceCache.$injector=createInternalInjector(instanceCache,function(serviceName,caller){
                var provider = providerInjector.get(serviceName+providerSufix,caller);
                instanceCache.invoke(provider.$get,provider,undefined,serviceName);
            }));
        //forEach load modules
        forEach(loadMoules(modulesToLoad),function(fn){if(fn) instanceInjector.invoke(fn);});

        ////////////////////////////////////
        // Module Loading
        ////////////////////////////////////
        function loadMoules(modules){
            var runBlocks=[];
            //todo
            return runBlocks;
        }

        //support object arg
        function supportObject(delegate){
            return function(key,value){
                if(isObject(key)){
                    forEach(key,reverseParams(delegate))
                }else{
                    return delegate(key,value);
                }
            }
        }
        //provider
        function provider(name,provider_){
            if(isFunciton(provider_)||isArray(provider_)){
                provider_ = providerInjector.instantiate(provider_);
            }
            if(!provider_.$get){
                throw new Error('do not have $get method!');
            }
            return  providerCache[name+providerSufix]=provider_;
        }

        function enForceReturnValue(factoryFn){
            return function(){
                var result=instanceCache.invoke(factoryFn);
                return result;
            };
        }

        //facotry
        function factory(name,factoryFn,enForce){
            return provider(name,{
                $get:enForce===false?enForceReturnValue(factoryFn):factoryFn
            });
        }

        //service
        function service(name,contructor){
            return factory(name,['$injector',function($injector){
                return $injector.instantiate(contructor);
            }]);
        }

        //value
        function value(name,value){
            return factory(name,valueFn(value),false);
        }

        ////////////////////////////////////
        // internal injector
        ////////////////////////////////////
        function createInternalInjector(cache,factory){

            // get service
            function getService(serviceName,caller){
                if(cache.hasOwnProperty(serviceName)){
                    if(cache[serviceName]===INSTANTING){
                        throw new Error('重复循环依赖！');
                    }
                    return cache[serviceName];
                }else{
                    cache[serviceName]=INSTANTING;
                    //path.push(serviceName);
                    return  cache[serviceName]=factory(serviceName,caller);
                }
            }

            //invoke fn
            function invoke(fn,self,locals,serviceName){
                var length,
                    args=[],
                    i,
                    item,
                    annotateArray=annotate(fn);
                for(i=0,length=annotateArray.length;i<length;i++){
                    item=annotateArray[i];
                    args.push(locals&&locals.hasOwnProperty(item)?locals[item]:getService(item,serviceName));
                }

                if(isArray(fn)){
                    fn=fn[fn.length-1];
                }

                return fn.call(self,args);
            }

            // intantiate instace
            function instantiate(type,locals,serviceName){
                var instance = Object.create((isArray(type)? type[type.length-1]:type).prototype||null);
                var returnValue = invoke(type,instance,locals,serviceName);

                return isObject(returnValue)|| isFunciton(returnValue)?returnValue:instance;
            }

            return {
                instantiate:instantiate,
                invoke:invoke,
                get:getService
            };
        }
    }

    // expose angular
    function publishExternalAPI(angular){
        shallowExtend(angular,{
            noop:noop,
            version:version,
            isFunction:isFunciton,
            isArray:isArray,
            isNumber:isNumber,
            isDefined:isDefined,
            isUndefined:isUndefined,
            isString:isString,
            isBlankObject:isBlankObject,
            isRegExp:isRegExp,
            isDate:isDate,
            isObject:isObject,
            isElement:isElement,
            identity:identity,
            fromJson:fromJson,
            toJson:toJson,
            copy:copy,
            shallowExtend:shallowExtend,
            deepExtend:deepExtend,
            bootstrap:bootstrap,
            createInjector:createInjector,
            forEach:forEach,
            lowercase:lowercase,
            uppercase:uppercase
        });
        angularModule=setupModuleLoader(window);
        angularModule('ng',['ngLocale'],['$provide',function($provide){
           //todo
            $provide.provider('$compile',$CompileProvider).directive({});//lots of directives
            $provide.provider({});//lots of providers
        }]);
    }
    //compileProvider
    function $CompileProvider(){
        this.directive=function(){};
    }
    //Promise
    function Promise(){
        this.$$state={status:0};
    }

    function Defferred(){

    }

    //q factory fn
    function qFactory(nextTick,exceptionHandler){

        var $Q;
        //TODO
        return $Q;
    }
    // qprovider
    function $QProvider(){
        this.get = ['$rootScope','$exceptionHandler',function($rootScope,$exceptionHandler){
            return qFactory(function(callback){
                $rootScope.$evalAsync(callback);
            },$exceptionHandler)
        }];
    }
    //first check jquery

    //publish angular

    //bootstrap when dom ready

}(window,document);

<|endoftext|>


<commit_before>var should = require('should');
var GitHub = require('../../../model/github');

var config = require('config').github.test;

var username = config.user;

describe('model', function () {
    describe('github', function () {
        describe('#fetchAvatar', function () {
            var github;
            var res;

            before(function (done) {
                github = new GitHub(config.token);
                github.fetchUserAvatar([config.user], function (err, _res) {
                    if (err) { console.error(err); throw new Error(err); }
                    res = _res;
                    done();
                });
            });

            it('got a avatar url', function () { should(res.length).be.eql(1); });
            it('first item is start with http', function () { should(res[0].url).startWith('http'); });
            it('second item is path', function () {
                should(res[0].path).containEql('public');
                should(res[0].path).containEql('images');
                should(res[0].path).containEql('avatar');
                should(res[0].path).containEql(username + '.');
            });
        });
    });
});<commit_msg>specちょっと修正<commit_after>var should = require('should');
var GitHub = require('../../../model/github');

var config = require('config').github.test;

var username = config.user;

describe('model', function () {
    describe('github', function () {
        describe('#fetchAvatar', function () {
            var github;
            var res;

            before(function (done) {
                github = new GitHub(config.token);
                github.fetchUserAvatar([config.user], function (err, _res) {
                    if (err) { console.error(err); throw new Error(err); }
                    res = _res;
                    done();
                });
            });

            it('got a avatar url', function () { should(res.length).be.eql(1); });
            it('url at first item is start with http', function () { should(res[0].url).startWith('http'); });
            it('path at second item is path', function () {
                should(res[0].path).containEql('public').containEql('images').containEql('avatar').containEql(username + '.');
            });
        });
    });
});<|endoftext|>


<commit_before>/*
*
* */

$(function(){
    var $write = $('#write');
    $write.html("");
    var browser = navigator.appName; // will need to get more efficient name
    var previousCharacter;
    var currentWord = "";

    //Initialization function
    var init = function(){
        setupEventListeners();
    };

    var setupEventListeners = function(){
        //Setup the active region for the touch events
        var containerElement = document.getElementById('container');        // Get Container Region
        var activeRegion = new ZingTouch.Region(containerElement);
        var keyboardRegion = document.getElementById('keyboard');         // Get Keyboard Region DOM element

        //attach event listener for pan (touch and drag event)
        activeRegion.bind(keyboardRegion, 'pan', function(e){
            writeToTextPad(e, 'pan');
        });

        //attach event listener for tap( similar to the click function)
        activeRegion.bind(keyboardRegion, 'tap', function(e){
            var obj = document.createElement("audio");
            obj.src="https://kahimyang.com/resources/sound/click.mp3";
            obj.volume=0.10;
            obj.autoPlay=false;
            obj.preLoad=true;
            obj.play();
            writeToTextPad(e, 'tap');
        });
    };

    function writeToTextPad(event, gestureName){
        console.log(event);
        var target = event.detail.events['0'].originalEvent.target;
        //var target= event.detail.events["0"].originalEvent.path["0"];
        var operationType = getOperationType(target);

        switch(operationType){
            case 1:
                addCharacterToTextPad(target);
                break;
            case 2:
                addSpaceToTextPad();
                break;
            case 3:
                deleteLastCharacterFromTextPad(target);
                break;
            default:
                break;
        }

    }

    function getOperationType(target){
        var operation = null;
        var className =target.className;

        if(className === 'letter'){
            operation = 1;
        }
        if(className === 'space'){
            operation = 2;
        }

        if(operation === 'delete'){
            operation = 3
        }
        return operation;
    }

    function addCharacterToTextPad(target){
        // Add the character
        var character = target.innerHTML;
        if(previousCharacter !== character){
            currentWord += character;
            $write.html($write.html() + character);
            predictWords();
        }
        previousCharacter = character;
    }

    function addSpaceToTextPad(){
        // Delete
        var html = $write.html();
        currentWord = " "; //the start of a new word
        $write.html($write.html() + " ");
    };
    function deleteLastCharacterFromTextPad(){
        // Delete
        var html = $write.html();
        currentWord = currentWord.substr(currentWord.length - 1);
        $write.html(html.substr(0, html.length - 1));
    }

    function predictWords(){

    }
    init();
});
<commit_msg>small chnages to js<commit_after>/*
*
* */

$(function(){
    var $write = $('#write');
    $write.html("");
    var browser = navigator.appName; // will need to get more efficient name
    var previousCharacter;
    var currentWord = "";

    //Initialization function
    var init = function(){
        setupEventListeners();
    };

    var setupEventListeners = function(){
        //Setup the active region for the touch events
        var containerElement = document.getElementById('container');        // Get Container Region
        var activeRegion = new ZingTouch.Region(containerElement);
        var keyboardRegion = document.getElementById('keyboard');         // Get Keyboard Region DOM element

        //attach event listener for pan (touch and drag event)
        activeRegion.bind(keyboardRegion, 'pan', function(e){
            writeToTextPad(e, 'pan');
        });

        //attach event listener for tap( similar to the click function)
        activeRegion.bind(keyboardRegion, 'tap', function(e){
            var obj = document.createElement("audio");
            obj.src="https://kahimyang.com/resources/sound/click.mp3";
            obj.volume=0.10;
            obj.autoPlay=false;
            obj.preLoad=true;
            obj.play();
            writeToTextPad(e, 'tap');
        });
    };

    function writeToTextPad(event, gestureName){
        console.log(event);
        var target = event.detail.events['0'].originalEvent.target;
        //var target= event.detail.events["0"].originalEvent.path["0"];
        var operationType = getOperationType(target);

        switch(operationType){
            case 1:
                addCharacterToTextPad(target);
                break;
            case 2:
                addSpaceToTextPad();
                break;
            case 3:
                deleteLastCharacterFromTextPad(target);
                break;
            default:
                break;
        }

    }

    function getOperationType(target){
        var operation = null;
        var className =target.className;

        if(className.includes('letter')){
            operation = 1;
        }
        if(className.includes('space')){
            operation = 2;
        }

        if(className.includes('delete')){
            operation = 3
        }
        return operation;
    }

    function addCharacterToTextPad(target){
        // Add the character
        var character = target.innerHTML;
        if(previousCharacter !== character){
            currentWord += character;
            $write.html($write.html() + character);
            predictWords();
        }
        previousCharacter = character;
    }

    function deleteLastCharacterFromTextPad(){
        // Delete
        var html = $write.html();
        $write.html(html.substr(0, html.length - 1));
    }

    function addSpaceToTextPad(target){
        // Add space to text pad
        $write.html($write.html() + " ");
    }
    /*
    function addSpaceToTextPad(){
        // Delete
        var html = $write.html();
        currentWord = " "; //the start of a new word
        $write.html($write.html() + " ");
    };
    function deleteLastCharacterFromTextPad(){
        // Delete
        var html = $write.html();
        currentWord = currentWord.substr(currentWord.length - 1);
        $write.html(html.substr(0, html.length - 1));
    }
*/
    function predictWords(){

    }
    init();
});
<|endoftext|>


<commit_before>/*
 * GeoMap v0.2
 * https://github.com/x6doooo/GeoMap
 *
 * Copyright 2013 Dx. Yang
 * Released under the MIT license
 */

(function($){

  var convertor = {
    "xmin": 360,
    "xmax": 0,
    "ymin": 180,
    "ymax": 0,
    "makePoint": function(p){
      var self = this,
          x = (p[0] < -168.5 ? p[0] + 360 : p[0]) + 170,
          y = (90 - p[1]);

      if(self.xmin > x) self.xmin = x;
      if(self.xmax < x) self.xmax = x;
      if(self.ymin > y) self.ymin = y;
      if(self.ymax < y) self.ymax = y;

      return [x, y];
    },
    "Point": function(coordinates){
      coordinates = this.makePoint(coordinates);
      return coordinates.join(',');
    },
    "LineString": function(coordinates){
      var str = '',
          self = this;
      coordinates.forEach(function(point, idx){
        point = self.makePoint(point);
        if(idx == 0){
          str = 'M' + point.join(',');
        }else{
          str = str + 'L' + point.join(',');
        }
      });
      return str;
    },
    "Polygon": function(coordinates){
      var str = '';
      coordinates.forEach(function(line, idx){
        str = str + convertor.LineString(line) + 'z';
      });
      return str;
    },
    "MultiPoint": function(coordinates){
      var arr = [];
      coordinates.forEach(function(p){
        arr.push(convertor.Point(p));
      });
      return arr;
    },
    "MultiLineString": function(coordinates){
      var str = '';
      coordinates.forEach(function(line){
        str += convertor.LineString(line);
      });
      return str;
    },
    "MultiPolygon": function(coordinates){
      var str = '';
      coordinates.forEach(function(line){
        str += convertor.Polygon(line);
      });
      return str;
    }
  },
  GeoMap = function(cfg){
    var self = this,
        defaultCfg = {
          container: 'body',
          offset: null,
          scale: null,
          mapStyle: {
            'fill': '#fff',
            'stroke': '#999',
            'stroke-width': 0.7
          }
        };

    $.extend(true, defaultCfg, cfg);

    self.container = $(defaultCfg.container);
    self.width = defaultCfg.width || self.container.width();
    self.height = defaultCfg.height || self.container.height();
    self.canvas = new Raphael(self.container.get(0), self.width, self.height);
    self.mapStyle = defaultCfg.mapStyle;
    self.scale = defaultCfg.scale;
    self.offset = defaultCfg.offset;
    self.shapes = self.canvas.set();
    self.json = null;
    self.paths = null;
  };

  GeoMap.prototype = {
    load: function(json){
      this.paths = this.json2path(json);
    },
    render: function(){
      var self = this,
        paths = self.paths,
        canvas = self.canvas,
        style = self.mapStyle,
        aPath = null,
        offset = self.offset,
        scale = self.scale,
        width = self.width,
        height = self.height;

      if(!scale){
        scale = {
          x: 1, y: 1
        };
      }

      if(!offset){
        offset = {
          x: convertor.xmin * scale.x,
          y: convertor.ymin * scale.y
        };
      }

      paths.forEach(function(path){
        if(path.type == 'point' || path.type == 'MultiPoint'){
        }else{
          aPath = canvas.path(path.path).attr(style).scale(scale.x, scale.y, 0, 0).data('properties', path.properties);
        }
        self.shapes.push(aPath);
      });

      canvas.setViewBox(offset.x, offset.y, width, height, false);
    },
    json2path: function(json){
      var self = this,
        shapes = json.features,
        shapeType,
        shapeCoordinates,
        str,
        geometries,
        pathArray = [];

      convertor.xmin= 360;
      convertor.xmax = 0;
      convertor.ymin = 180;
      convertor.ymax = 0;

      shapes.forEach(function(shape, idx, arr){
        if(shape.type == 'Feature'){
          pushApath(shape.geometry, shape);
        }else if(shape.type = 'GeometryCollection'){
          geometries = shape.geometries;
          geometries.forEach(function(val){
            pushApath(val, val);
          });
        }
      });
      function pushApath(gm, shape){
        shapeType = gm.type;
        shapeCoordinates = gm.coordinates;
        str = convertor[shapeType](shapeCoordinates);
        pathArray.push({
          type: shapeType,
          path: str,
          properties: shape.properties
        });
      }
      return pathArray;
    }
  };

  window.GeoMap = GeoMap;
})(jQuery);<commit_msg>增加crossline<commit_after>/*
 * GeoMap v0.2
 * https://github.com/x6doooo/GeoMap
 *
 * Copyright 2013 Dx. Yang
 * Released under the MIT license
 */

(function($){
  var convertor = {
    "xmin": 360,
    "xmax": 0,
    "ymin": 180,
    "ymax": 0,
    "makePoint": function(p){
      var self = this,
          x = (p[0] < -168.5 ? p[0] + 360 : p[0]) + 170,
          y = (90 - p[1]);
      if(self.xmin > x) self.xmin = x;
      if(self.xmax < x) self.xmax = x;
      if(self.ymin > y) self.ymin = y;
      if(self.ymax < y) self.ymax = y;
      return [x, y];
    },
    "Point": function(coordinates){
      coordinates = this.makePoint(coordinates);
      return coordinates.join(',');
    },
    "LineString": function(coordinates){
      var str = '',
          self = this;
      coordinates.forEach(function(point, idx){
        point = self.makePoint(point);
        if(idx == 0){
          str = 'M' + point.join(',');
        }else{
          str = str + 'L' + point.join(',');
        }
      });
      return str;
    },
    "Polygon": function(coordinates){
      var str = '';
      coordinates.forEach(function(line, idx){
        str = str + convertor.LineString(line) + 'z';
      });
      return str;
    },
    "MultiPoint": function(coordinates){
      var arr = [];
      coordinates.forEach(function(p){
        arr.push(convertor.Point(p));
      });
      return arr;
    },
    "MultiLineString": function(coordinates){
      var str = '';
      coordinates.forEach(function(line){
        str += convertor.LineString(line);
      });
      return str;
    },
    "MultiPolygon": function(coordinates){
      var str = '';
      coordinates.forEach(function(line){
        str += convertor.Polygon(line);
      });
      return str;
    }
  },
  GeoMap = function(cfg){
    var self = this,
        defaultCfg = {
          container: 'body',
          offset: null,
          scale: null,
          mapStyle: {
            'fill': '#fff',
            'stroke': '#999',
            'stroke-width': 0.7
          },
          crossline:{
            enable: true,
            color: '#ccc'
          }
        };

    $.extend(true, defaultCfg, cfg);

    self.container = $(defaultCfg.container);
    self.width = defaultCfg.width || self.container.width();
    self.height = defaultCfg.height || self.container.height();
    self.left = self.container.offset().left;
    self.top = self.container.offset().top;
    self.canvas = new Raphael(self.container.get(0), self.width, self.height);
    self.mapStyle = defaultCfg.mapStyle;
    self.scale = defaultCfg.scale;
    self.offset = defaultCfg.offset;
    self.shapes = self.canvas.set();
    self.json = null;
    self.paths = null;
    self.back = null;
    self.crosslineX = null;
    self.crosslineY = null;
    self.crossline = defaultCfg.crossline;
  };

  GeoMap.prototype = {
    load: function(json){
      this.paths = this.json2path(json);
    },
    render: function(){
      var self = this,
        shapes = self.shapes,
        paths = self.paths,
        canvas = self.canvas,
        style = self.mapStyle,
        aPath = null,
        offset = self.offset,
        scale = self.scale,
        width = self.width,
        height = self.height,
        left= self.left + 5,
        top = self.top + 7,
        crossline = self.crossline;

      if(!scale){
        scale = {
          x: 1, y: 1
        };
      }

      if(!offset){
        offset = {
          x: convertor.xmin,
          y: convertor.ymin
        };
      }
      mapleft = convertor.xmin;
      maptop = convertor.ymin;
      mapwidth = convertor.xmax - convertor.xmin;
      mapheight = convertor.ymax - convertor.ymin;

      self.back = canvas.rect(mapleft, maptop, mapwidth, mapheight).scale(scale.x, scale.y, 0, 0).attr({
        'fill': '#eee', 'stroke-width': 0
      });

      linehead = 'M' + (mapleft) + ',' + (maptop);
      linex = linehead + 'H' + convertor.xmax * scale.x;
      liney = linehead + 'V' + convertor.ymax * scale.y;

      self.crosslineX = canvas.path(linex).attr({'stroke': crossline.color, 'stroke-width': '1px'}).hide();
      self.crosslineY = canvas.path(liney).attr({'stroke': crossline.color, 'stroke-width': '1px'}).hide();

      paths.forEach(function(path){
        if(path.type == 'point' || path.type == 'MultiPoint'){
        }else{
          aPath = canvas.path(path.path).data('properties', path.properties);
        }
        shapes.push(aPath);
      });
      canvas.setViewBox(offset.x, offset.y, width, height, false);
      shapes.attr(style).scale(scale.x, scale.y, mapleft, maptop);

      if(crossline.enable === true){
        shapes.mouseover(function(){
          showCrossLine();
        }).mousemove(function(e){
            moveCrossLine(e);
          }).mouseout(function(){
            hideCrossLine();
          });
        self.back.mouseover(function(){
          showCrossLine();
        }).mousemove(function(e){
          moveCrossLine(e);
        }).mouseout(function(){
          hideCrossLine();
        });
      }
      function showCrossLine(){
        self.crosslineX.toFront().show();
        self.crosslineY.toFront().show();
      }
      function moveCrossLine(e){
        var pos = getEventPos(e);
        self.crosslineX.transform('T0,'+pos.y);
        self.crosslineY.transform('T'+ pos.x + ',0');
      }
      function hideCrossLine(){
        self.crosslineX.hide();
        self.crosslineY.hide();
      }
      function getEventPos(e){
        return {
          x: parseInt(e.pageX - left) + 0.4,
          y: parseInt(e.pageY - top) + 0.4
        };
      }
    },
    json2path: function(json){
      var self = this,
        shapes = json.features,
        shapeType,
        shapeCoordinates,
        str,
        geometries,
        pathArray = [];

      convertor.xmin= 360;
      convertor.xmax = 0;
      convertor.ymin = 180;
      convertor.ymax = 0;

      shapes.forEach(function(shape, idx, arr){
        if(shape.type == 'Feature'){
          pushApath(shape.geometry, shape);
        }else if(shape.type = 'GeometryCollection'){
          geometries = shape.geometries;
          geometries.forEach(function(val){
            pushApath(val, val);
          });
        }
      });
      function pushApath(gm, shape){
        shapeType = gm.type;
        shapeCoordinates = gm.coordinates;
        str = convertor[shapeType](shapeCoordinates);
        pathArray.push({
          type: shapeType,
          path: str,
          properties: shape.properties
        });
      }
      return pathArray;
    }
  };

  window.GeoMap = GeoMap;
})(jQuery);<|endoftext|>


<commit_before>var Transform = require('stream').Transform

  , BASE = 65536

  , adler32 = function(buffer) {
      var a = 1
        , b = 0
        , i = 0
        , length = buffer.length

      for(; i < length; ++i) {
        a = (a + buffer[i]) % 65221
        b = (b + (length - i) * buffer[i] + 1) % 65221
      }
      return b * BASE + a
    }

  , rolling = function(length) {
      var stream = new Transform({objectMode: true})
        , data = []
        , a = 1
        , b = 0
        , collecting = true

      stream._transform = function(chunk, encoding, callback) {
        var i
          , tmp1, tmp2
        if (!Buffer.isBuffer(chunk))
          chunk = new Buffer(chunk, encoding)

        for(i = 0; i < chunk.length; ++i) {
          data.push(chunk[i])
        }

        if (collecting && data.length >= length) {
          for(i = 0; i < length; ++i) {
            a = (a + data[i]) % 65221
            b = (b + (length - i) * data[i] + 1) % 65221
          }
          this.push(b * BASE + a)

          collecting = false
        }

        while (data.length > length) {
          tmp2 = data[length]
          tmp1 = data.shift()
          a = (a - tmp1 + tmp2 + BASE) % BASE
          b = (b - length * tmp1 + a - 1)
          this.push(b * BASE + a)
        }

        callback(null)
      }

      return stream
    }

module.exports = rolling
<commit_msg>[cleanu] Remove unused method<commit_after>var Transform = require('stream').Transform

  , BASE = 65536

  , rolling = function(length) {
      var stream = new Transform({objectMode: true})
        , data = []
        , a = 1
        , b = 0
        , collecting = true

      stream._transform = function(chunk, encoding, callback) {
        var i
          , tmp1, tmp2
        if (!Buffer.isBuffer(chunk))
          chunk = new Buffer(chunk, encoding)

        for(i = 0; i < chunk.length; ++i) {
          data.push(chunk[i])
        }

        if (collecting && data.length >= length) {
          for(i = 0; i < length; ++i) {
            a = (a + data[i]) % 65221
            b = (b + (length - i) * data[i] + 1) % 65221
          }
          this.push(b * BASE + a)

          collecting = false
        }

        while (data.length > length) {
          tmp2 = data[length]
          tmp1 = data.shift()
          a = (a - tmp1 + tmp2 + BASE) % BASE
          b = (b - length * tmp1 + a - 1)
          this.push(b * BASE + a)
        }

        callback(null)
      }

      return stream
    }

module.exports = rolling
<|endoftext|>


<commit_before>$(function () {
	var data = [];
	for (var i = 0; i < 10; ++i) {
		data.push({
			"id": "#" + (i + 1),
			"created_at": new Date().toDateString(),
			"status": "In progress",
			"title": "Test " + i + Math.round(Math.random() * 1000),
			"count": Math.round(Math.random() * 100)
		});
	}

	var columns = [
		{name: "id", type: "string"},
		{name: "created_at", type: "string"},
		{name: "status", type: "string", editor: "CustomEditor"},
		{name: "title", type: "string"},
		{name: "count", type: "string"}
	];

	var grid = $(".sensei-grid").grid(data, columns);
	grid.registerEditor(BasicEditor);
	grid.registerEditor(CustomEditor);
    grid.events.on("editor:save", function (data, $cell) {
        console.info("save cell:", data, $cell);
    });
    grid.events.on("editor:load", function (data, $cell) {
        console.info("set value in editor:", data, $cell);
    });
    grid.events.on("cell:select", function ($cell) {
        console.info("active cell:", $cell);
    });
	grid.render();

    // api examples
    var $row = grid.getRowByIndex(5);
    console.group("data api examples");
    console.log("grid.getRowDataByIndex(0):", grid.getRowDataByIndex(0));
    console.log("grid.getRowData($row):", grid.getRowData($row));
    console.log("grid.getCellDataByIndex(0, 1):", grid.getCellDataByIndex(0, 1));
    console.log("grid.getCellDataByKey(2, created_at):", grid.getCellDataByKey(2, "created_at"));
    console.log("grid.getGridData():", grid.getGridData());
    console.groupEnd("api examples");

    window.grid = grid;
}); <commit_msg>Fix console.groupEnd for data api examples.<commit_after>$(function () {
	var data = [];
	for (var i = 0; i < 10; ++i) {
		data.push({
			"id": "#" + (i + 1),
			"created_at": new Date().toDateString(),
			"status": "In progress",
			"title": "Test " + i + Math.round(Math.random() * 1000),
			"count": Math.round(Math.random() * 100)
		});
	}

	var columns = [
		{name: "id", type: "string"},
		{name: "created_at", type: "string"},
		{name: "status", type: "string", editor: "CustomEditor"},
		{name: "title", type: "string"},
		{name: "count", type: "string"}
	];

	var grid = $(".sensei-grid").grid(data, columns);
	grid.registerEditor(BasicEditor);
	grid.registerEditor(CustomEditor);
    grid.events.on("editor:save", function (data, $cell) {
        console.info("save cell:", data, $cell);
    });
    grid.events.on("editor:load", function (data, $cell) {
        console.info("set value in editor:", data, $cell);
    });
    grid.events.on("cell:select", function ($cell) {
        console.info("active cell:", $cell);
    });
	grid.render();

    // api examples
    var $row = grid.getRowByIndex(5);
    console.group("data api examples");
    console.log("grid.getRowDataByIndex(0):", grid.getRowDataByIndex(0));
    console.log("grid.getRowData($row):", grid.getRowData($row));
    console.log("grid.getCellDataByIndex(0, 1):", grid.getCellDataByIndex(0, 1));
    console.log("grid.getCellDataByKey(2, created_at):", grid.getCellDataByKey(2, "created_at"));
    console.log("grid.getGridData():", grid.getGridData());
    console.groupEnd();

    window.grid = grid;
}); <|endoftext|>