<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.
*/

var azure = require('azure');
var http = require('http');
var BlobConstants = azure.Constants.BlobConstants;
var connectionStringParser = azure.ConnectionStringParser;
var flows = require('streamline/lib/util/flows');
var os = require('os');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var StorageServiceSettings = azure.StorageServiceSettings;
var util = require('util');
var utils = require('../util/utils.js');
var ExponentialRetryPolicyFilter = azure.ExponentialRetryPolicyFilter;

/**
* Module variables
*/
var cli = null;
var logger = null;
var progress = null;

/**
* Limit the concurrent REST calls
*/
var restFunnel = null;

/**
* Storage rest operation time out
*/
var operationTimeout = null;

/**
* Storage Utilities for storage blob/queue/table command
*/
var StorageUtil = {};

/**
* Storge connection string environment variable name and it's also used azure storage powershell.
*/
StorageUtil.ENV_CONNECTIONSTRING_NAME = 'AZURE_STORAGE_CONNECTION_STRING';
StorageUtil.ENV_SDK_ACCOUNT_NAME = 'AZURE_STORAGE_ACCOUNT';
StorageUtil.ENV_SDK_ACCOUNT_KEY = 'AZURE_STORAGE_ACCESS_KEY';
StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME = 'azure_storage_concurrency';
StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME = 'azure_storage_timeout'; //Milliseconds

/**
* Storage Operation Type
*/
StorageUtil.OperationType = {
  Blob  : 'blob',
  Queue : 'queue',
  Table : 'table'
};

/**
* Init cli module
*/
StorageUtil.init = function(azureCli) {
  cli = azureCli;
  logger = cli.output;
  var cfg = utils.readConfig();
  var restConcurrency = getRestConcurrency (cfg);
  http.globalAgent.maxSockets = restConcurrency;
  restFunnel = flows.funnel(restConcurrency);
  operationTimeout = getRestOperationTimeout(cfg);
};

/**
* Create an Storage operation
* @constructor
* @param {OperationType} [type] Storage operation type
* @param {string} [operation] Operation name
*/
StorageUtil.StorageOperation = function(type, operation){
  this.type = type;
  this.operation = operation;
};

/**
* Get blob service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {BlobService} BlobService object from node sdk
*/
StorageUtil.getBlobService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if (serviceSettings === null) {
    //Use the default blob service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createBlobService();
  } else {
    service = azure.createBlobService(serviceSettings._name, serviceSettings._key, serviceSettings._blobEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Get table service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {TableService} TableService object from node sdk
*/
StorageUtil.getTableService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if (serviceSettings === null) {
    //Use the default table service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createTableService();
  } else {
    service = azure.createTableService(serviceSettings._name, serviceSettings._key, serviceSettings._tableEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Get queue service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {QueueService} QueueService object from node sdk
*/
StorageUtil.getQueueService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if(serviceSettings === null) {
    //Use the default queue service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createQueueService();
  } else {
    service = azure.createQueueService(serviceSettings._name, serviceSettings._key, serviceSettings._queueEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Perform Storage REST operation, this function accepts dynamic parameters
* All parameters except the first one will be treated as the parameters of the specified operation
* @param {StorageOperation} storageOperation Storage operation
* @param {Callback} _ call back function
*/
StorageUtil.performStorageOperation = function (storageOperation, _) {
  if(storageOperation === null) return;
  var service = storageOperation.service;
  if (!service) {
    throw new Error('Service client can\'t be null');
  }
  var operation = storageOperation.operation || '';

  if (!service[operation] || !isFunction(service[operation])) {
    throw 'Invalid operation ' + operation;
  }

  //The number of the explicitly defined parameters for this method
  var definedParameterCount = 2;
  var operationArgs = Array.prototype.slice.call(arguments).slice(definedParameterCount, arguments.length);

  var result = null;
  try {
    restFunnel(_, function(_) {
      /*jshint camelcase:false*/
      try{
      result = service[operation].apply_(_, service, operationArgs);
      } catch(e) {
        throw e;
      }
      /*jshint camelcase:true*/
    });
  } catch(e) {
    StorageUtil.endProgress();
    throw e;
  }
  return result;
};

/**
* Start cli operation progress
*/
StorageUtil.startProgress = function(tips) {
  if (progress !== null) {
    StorageUtil.endProgress();
  }
  progress = cli.progress(tips);
};

/**
* End cli operation progress
*/
StorageUtil.endProgress = function() {
  if (progress !== null) {
    progress.end();
  }
  progress = null;
};

/**
* Set REST operation time out
*/
StorageUtil.setOperationTimeout = function(options) {
  if(options.timeoutintervalInMs === undefined &&
    operationTimeout !== null && !isNaN(operationTimeout) && operationTimeout > 0) {
    options.timeoutIntervalInMs = operationTimeout;
  }
};

/**
* Convert string to container access level
*/
StorageUtil.stringToContainerAccessLevel = function(str) {
  var accessType = BlobConstants.BlobContainerPublicAccessType;
  var accessLevel = accessType.OFF;
  if(str) {
    str = str.toLowerCase();
    switch(str) {
    case 'blob':
      accessLevel = accessType.BLOB;
      break;
    case 'container':
      accessLevel = accessType.CONTAINER;
      break;
    case 'off':
      accessLevel = accessType.OFF;
      break;
    default:
      if(str) {
        throw new Error(util.format('Invalid container public access level %s', str));
      }
      break;
    }
  }
  return accessLevel;
};

/**
* Convert file to blob name
*/
StorageUtil.convertFileNameToBlobName = function(name) {
  return name.replace(/\\/img, '/');
};

/**
* Convert container access level to string
*/
StorageUtil.containerAccessLevelToString = function(accessType) {
  var publicAccessType = BlobConstants.BlobContainerPublicAccessType;
  var str = 'Off';
  switch(accessType) {
  case publicAccessType.BLOB:
    str = 'Blob';
    break;
  case publicAccessType.CONTAINER:
    str = 'Container';
    break;
  case publicAccessType.OFF:
    str = 'Off';
    break;
  default:
    if(accessType) {
      throw new Error(util.format('Invalid Container public access type %s', accessType));
    }
    break;
  }
  return str;
};

/**
* Parse json parameter to object
*/
StorageUtil.parseKvParameter = function(str) {
  if (str) {
    return connectionStringParser.parse(str);
  }
};

/**
* Is not found exception
*/
StorageUtil.isNotFoundException = function(e) {
  return e.code == 'NotFound';
};

/*
* Escape blob name
*/
StorageUtil.escapeFileName = function(name) {
  name = encodeURIComponent(name);
  return name.replace(/%20/img, ' '); //Space is valid for file system
};

/**
* Recursive mkdir
*/
StorageUtil.recursiveMkdir = function(dirPath) {
  var dirs = dirPath.split(path.sep);
  var dirPath = '';
  for(var i = 0; i < dirs.length; i++) {
    dirPath = path.join(dirPath, dirs[i]);
    if(!StorageUtil.doesPathExist(dirPath)) {
      fs.mkdirSync(dirPath);
    }
  }
  return dirPath;
};

StorageUtil.doesPathExist = function(dirPath) {
  var existFunc = fs.existsSync || path.existsSync; //For node 0.10 and 0.6
  if(path) {
    return existFunc(dirPath);
  }
  return true;
};

/**
* Get file system structure from blob name
*/
StorageUtil.getStructureFromBlobName = function(blobName) {
  var structure = {fileName : undefined, dirName : undefined};
  if(blobName[blobName.length - 1]  === '/') {
    var lastIndex = blobName.lastIndexOf('/', blobName.length - 2);
    structure.fileName = blobName.substr(lastIndex + 1);
    structure.dirName = blobName.substr(0, lastIndex);
  } else {
    structure.fileName = path.basename(blobName);
    structure.dirName = path.dirname(blobName);
  }
  return structure;
}

/**
* Calculate the md5hash for the specified file
*/
StorageUtil.calculateFileMd5 = function(path, cb) {
  var stream = fs.createReadStream(path);
  var digest = crypto.createHash('md5');
  stream.on('data', function(d) { digest.update(d);});
  stream.on('end', function() {
    var md5 = digest.digest('base64');
    cb(null, md5);
  });
};

/**
* Format blob properties
*/
StorageUtil.formatBlobProperties = function(properties, target) {
  if (!properties) return;
  var propertyNames = ['contentType', 'contentEncoding', 'contentLanguage', 'cacheControl'];
  var postfix = 'Header';
  var getPropertyIndex = function(key) {
    for(var i = 0; i < propertyNames.length; i++) {
      if (propertyNames[i].toLowerCase() == key.toLowerCase()) {
        return i;
      }
    }
    return -1;
  };

  var index = -1;
  for(var item in properties) {
    index = getPropertyIndex(item);
    if (index == -1) {
      throw new Error(util.format('Invalid value: %s. Options are: %s.', item, propertyNames));
    }
    target[propertyNames[index] + postfix] = properties[item];
    if (item.toLowerCase() === 'contenttype') {
      target['contentType'] = properties[item];
    }
  }
};

/**
* Normalize parameters and throw an exception when parsing fail
*/
StorageUtil.normalizeParameters = function() {
  var params = utils.normalizeParameters.apply(utils, arguments);
  if (params.err) {
    throw params.err;
  } else {
    return params;
  }
};

/**
* Check whether the specified parameter is a function
* @param {object} func An arbitrary javascript object
* @return {bool} true if the specified object is function, otherwise false
*/
function isFunction(func) {
  return typeof func === 'function';
}

/**
* Get storage service settings with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {StorageServiceSettings} return the storage service settings if the connection string is applied, otherwise return null.
*/
function getStorageServiceSettings(connectionString) {
  if (!connectionString) {
    connectionString = process.env[StorageUtil.ENV_CONNECTIONSTRING_NAME];
  }
  if (!connectionString) {
    if (!process.env[StorageUtil.ENV_SDK_ACCOUNT_NAME] || !process.env[StorageUtil.ENV_SDK_ACCOUNT_KEY]) {
      throw new Error('Please set the storage account parameters or one of the following two environment variables to use storage command. 1.AZURE_STORAGE_CONNECTION_STRING, 2. AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY');
    }
    return null;
  } else {
    return StorageServiceSettings.createFromConnectionString(connectionString);
  }
}

/**
* Get REST operation time out
*/
function getRestOperationTimeout(cfg) {
  var radix = 10;
  var definedTimeout = parseInt(cfg[StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME], radix);
  if (isNaN(definedTimeout) || definedTimeout <= 0) {
    return null;
  } else {
    return definedTimeout;
  }
}

/**
* Get the REST conccurency
*/
function getRestConcurrency(cfg) {
  var radix = 10;
  var definedConcurrency = parseInt(cfg[StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME], radix);
  if (isNaN(definedConcurrency) || definedConcurrency === 0) {
    return getDefaultRestConcurrency();
  } else {
    return definedConcurrency;
  }
}

/**
* Get the default REST concurrency
*/
function getDefaultRestConcurrency() {
  var cpuCount = os.cpus().length;
  //Hard code number for default task amount per core
  var  asyncTasksPerCoreMultiplier = 1;
  return cpuCount * asyncTasksPerCoreMultiplier;
}

module.exports = StorageUtil;
<commit_msg>apply jslink checking rules<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.
*/

var azure = require('azure');
var http = require('http');
var BlobConstants = azure.Constants.BlobConstants;
var connectionStringParser = azure.ConnectionStringParser;
var flows = require('streamline/lib/util/flows');
var os = require('os');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var StorageServiceSettings = azure.StorageServiceSettings;
var util = require('util');
var utils = require('../util/utils.js');
var ExponentialRetryPolicyFilter = azure.ExponentialRetryPolicyFilter;

/**
* Module variables
*/
var cli = null;
var logger = null;
var progress = null;

/**
* Limit the concurrent REST calls
*/
var restFunnel = null;

/**
* Storage rest operation time out
*/
var operationTimeout = null;

/**
* Storage Utilities for storage blob/queue/table command
*/
var StorageUtil = {};

/**
* Storge connection string environment variable name and it's also used azure storage powershell.
*/
StorageUtil.ENV_CONNECTIONSTRING_NAME = 'AZURE_STORAGE_CONNECTION_STRING';
StorageUtil.ENV_SDK_ACCOUNT_NAME = 'AZURE_STORAGE_ACCOUNT';
StorageUtil.ENV_SDK_ACCOUNT_KEY = 'AZURE_STORAGE_ACCESS_KEY';
StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME = 'azure_storage_concurrency';
StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME = 'azure_storage_timeout'; //Milliseconds

/**
* Storage Operation Type
*/
StorageUtil.OperationType = {
  Blob  : 'blob',
  Queue : 'queue',
  Table : 'table'
};

/**
* Init cli module
*/
StorageUtil.init = function(azureCli) {
  cli = azureCli;
  logger = cli.output;
  var cfg = utils.readConfig();
  var restConcurrency = getRestConcurrency (cfg);
  http.globalAgent.maxSockets = restConcurrency;
  restFunnel = flows.funnel(restConcurrency);
  operationTimeout = getRestOperationTimeout(cfg);
};

/**
* Create an Storage operation
* @constructor
* @param {OperationType} [type] Storage operation type
* @param {string} [operation] Operation name
*/
StorageUtil.StorageOperation = function(type, operation){
  this.type = type;
  this.operation = operation;
};

/**
* Get blob service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {BlobService} BlobService object from node sdk
*/
StorageUtil.getBlobService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if (serviceSettings === null) {
    //Use the default blob service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createBlobService();
  } else {
    service = azure.createBlobService(serviceSettings._name, serviceSettings._key, serviceSettings._blobEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Get table service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {TableService} TableService object from node sdk
*/
StorageUtil.getTableService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if (serviceSettings === null) {
    //Use the default table service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createTableService();
  } else {
    service = azure.createTableService(serviceSettings._name, serviceSettings._key, serviceSettings._tableEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Get queue service with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {QueueService} QueueService object from node sdk
*/
StorageUtil.getQueueService = function(connectionString) {
  var serviceSettings = getStorageServiceSettings(connectionString);
  var service = null;
  if(serviceSettings === null) {
    //Use the default queue service, nodesdk will use the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables
    service = azure.createQueueService();
  } else {
    service = azure.createQueueService(serviceSettings._name, serviceSettings._key, serviceSettings._queueEndpointUri);
  }
  return service.withFilter(new ExponentialRetryPolicyFilter());
};

/**
* Perform Storage REST operation, this function accepts dynamic parameters
* All parameters except the first one will be treated as the parameters of the specified operation
* @param {StorageOperation} storageOperation Storage operation
* @param {Callback} _ call back function
*/
StorageUtil.performStorageOperation = function (storageOperation, _) {
  if(storageOperation === null) return;
  var service = storageOperation.service;
  if (!service) {
    throw new Error('Service client can\'t be null');
  }
  var operation = storageOperation.operation || '';

  if (!service[operation] || !isFunction(service[operation])) {
    throw 'Invalid operation ' + operation;
  }

  //The number of the explicitly defined parameters for this method
  var definedParameterCount = 2;
  var operationArgs = Array.prototype.slice.call(arguments).slice(definedParameterCount, arguments.length);

  var result = null;
  try {
    restFunnel(_, function(_) {
      /*jshint camelcase:false*/
      result = service[operation].apply_(_, service, operationArgs);
      /*jshint camelcase:true*/
    });
  } catch(e) {
    StorageUtil.endProgress();
    throw e;
  }
  return result;
};

/**
* Start cli operation progress
*/
StorageUtil.startProgress = function(tips) {
  if (progress !== null) {
    StorageUtil.endProgress();
  }
  progress = cli.progress(tips);
};

/**
* End cli operation progress
*/
StorageUtil.endProgress = function() {
  if (progress !== null) {
    progress.end();
  }
  progress = null;
};

/**
* Set REST operation time out
*/
StorageUtil.setOperationTimeout = function(options) {
  if(options.timeoutintervalInMs === undefined &&
    operationTimeout !== null && !isNaN(operationTimeout) && operationTimeout > 0) {
    options.timeoutIntervalInMs = operationTimeout;
  }
};

/**
* Convert string to container access level
*/
StorageUtil.stringToContainerAccessLevel = function(str) {
  var accessType = BlobConstants.BlobContainerPublicAccessType;
  var accessLevel = accessType.OFF;
  if(str) {
    str = str.toLowerCase();
    switch(str) {
    case 'blob':
      accessLevel = accessType.BLOB;
      break;
    case 'container':
      accessLevel = accessType.CONTAINER;
      break;
    case 'off':
      accessLevel = accessType.OFF;
      break;
    default:
      if(str) {
        throw new Error(util.format('Invalid container public access level %s', str));
      }
      break;
    }
  }
  return accessLevel;
};

/**
* Convert file to blob name
*/
StorageUtil.convertFileNameToBlobName = function(name) {
  return name.replace(/\\/img, '/');
};

/**
* Convert container access level to string
*/
StorageUtil.containerAccessLevelToString = function(accessType) {
  var publicAccessType = BlobConstants.BlobContainerPublicAccessType;
  var str = 'Off';
  switch(accessType) {
  case publicAccessType.BLOB:
    str = 'Blob';
    break;
  case publicAccessType.CONTAINER:
    str = 'Container';
    break;
  case publicAccessType.OFF:
    str = 'Off';
    break;
  default:
    if(accessType) {
      throw new Error(util.format('Invalid Container public access type %s', accessType));
    }
    break;
  }
  return str;
};

/**
* Parse json parameter to object
*/
StorageUtil.parseKvParameter = function(str) {
  if (str) {
    return connectionStringParser.parse(str);
  }
};

/**
* Is not found exception
*/
StorageUtil.isNotFoundException = function(e) {
  return e.code == 'NotFound';
};

/*
* Escape blob name
*/
StorageUtil.escapeFileName = function(name) {
  name = encodeURIComponent(name);
  return name.replace(/%20/img, ' '); //Space is valid for file system
};

/**
* Recursive mkdir
*/
StorageUtil.recursiveMkdir = function(specifiedPath) {
  var dirs = specifiedPath.split(path.sep);
  var dirPath = '';
  for(var i = 0; i < dirs.length; i++) {
    dirPath = path.join(dirPath, dirs[i]);
    if(!StorageUtil.doesPathExist(dirPath)) {
      fs.mkdirSync(dirPath);
    }
  }
  return dirPath;
};

StorageUtil.doesPathExist = function(dirPath) {
  var existFunc = fs.existsSync || path.existsSync; //For node 0.10 and 0.6
  if(path) {
    return existFunc(dirPath);
  }
  return true;
};

/**
* Get file system structure from blob name
*/
StorageUtil.getStructureFromBlobName = function(blobName) {
  var structure = {fileName : undefined, dirName : undefined};
  if(blobName[blobName.length - 1]  === '/') {
    var lastIndex = blobName.lastIndexOf('/', blobName.length - 2);
    structure.fileName = blobName.substr(lastIndex + 1);
    structure.dirName = blobName.substr(0, lastIndex);
  } else {
    structure.fileName = path.basename(blobName);
    structure.dirName = path.dirname(blobName);
  }
  return structure;
};

/**
* Calculate the md5hash for the specified file
*/
StorageUtil.calculateFileMd5 = function(path, cb) {
  var stream = fs.createReadStream(path);
  var digest = crypto.createHash('md5');
  stream.on('data', function(d) { digest.update(d);});
  stream.on('end', function() {
    var md5 = digest.digest('base64');
    cb(null, md5);
  });
};

/**
* Format blob properties
*/
StorageUtil.formatBlobProperties = function(properties, target) {
  if (!properties) return;
  var propertyNames = ['contentType', 'contentEncoding', 'contentLanguage', 'cacheControl'];
  var postfix = 'Header';
  var getPropertyIndex = function(key) {
    for(var i = 0; i < propertyNames.length; i++) {
      if (propertyNames[i].toLowerCase() == key.toLowerCase()) {
        return i;
      }
    }
    return -1;
  };

  var index = -1;
  for(var item in properties) {
    index = getPropertyIndex(item);
    if (index == -1) {
      throw new Error(util.format('Invalid value: %s. Options are: %s.', item, propertyNames));
    }
    target[propertyNames[index] + postfix] = properties[item];
    if (item.toLowerCase() === 'contenttype') {
      target['contentType'] = properties[item];
    }
  }
};

/**
* Normalize parameters and throw an exception when parsing fail
*/
StorageUtil.normalizeParameters = function() {
  var params = utils.normalizeParameters.apply(utils, arguments);
  if (params.err) {
    throw params.err;
  } else {
    return params;
  }
};

/**
* Check whether the specified parameter is a function
* @param {object} func An arbitrary javascript object
* @return {bool} true if the specified object is function, otherwise false
*/
function isFunction(func) {
  return typeof func === 'function';
}

/**
* Get storage service settings with the specified or default connection string
* @param {string} [connectionString] Storage connection string
* @return {StorageServiceSettings} return the storage service settings if the connection string is applied, otherwise return null.
*/
function getStorageServiceSettings(connectionString) {
  if (!connectionString) {
    connectionString = process.env[StorageUtil.ENV_CONNECTIONSTRING_NAME];
  }
  if (!connectionString) {
    if (!process.env[StorageUtil.ENV_SDK_ACCOUNT_NAME] || !process.env[StorageUtil.ENV_SDK_ACCOUNT_KEY]) {
      throw new Error('Please set the storage account parameters or one of the following two environment variables to use storage command. 1.AZURE_STORAGE_CONNECTION_STRING, 2. AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY');
    }
    return null;
  } else {
    return StorageServiceSettings.createFromConnectionString(connectionString);
  }
}

/**
* Get REST operation time out
*/
function getRestOperationTimeout(cfg) {
  var radix = 10;
  var definedTimeout = parseInt(cfg[StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME], radix);
  if (isNaN(definedTimeout) || definedTimeout <= 0) {
    return null;
  } else {
    return definedTimeout;
  }
}

/**
* Get the REST conccurency
*/
function getRestConcurrency(cfg) {
  var radix = 10;
  var definedConcurrency = parseInt(cfg[StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME], radix);
  if (isNaN(definedConcurrency) || definedConcurrency === 0) {
    return getDefaultRestConcurrency();
  } else {
    return definedConcurrency;
  }
}

/**
* Get the default REST concurrency
*/
function getDefaultRestConcurrency() {
  var cpuCount = os.cpus().length;
  //Hard code number for default task amount per core
  var  asyncTasksPerCoreMultiplier = 1;
  return cpuCount * asyncTasksPerCoreMultiplier;
}

module.exports = StorageUtil;
<|endoftext|>


<commit_before>/*global Class*/
/*global console*/
/*global localStorage*/
var checkKey = function(key){
	if(localStorage && (localStorage.getItem(key) != undefined && localStorage.getItem(key) != null) ){
      	return true;
     }
     else
     {
     	return false;
     }
};
var TableConfiguration = Class.extend({
  check: function(){
  	if(checkKey("cfg")){
      	return true;
      }
      else
      {
      	return false;
      }
  },
  findAll: function(){
      if(this.check()){
      	return JSON.parse(localStorage.getItem("cfg"));
      }
      else
      {
      	return false;
      }
    },
    findValueByKey: function(key){
    	if(this.check()){
	      	if(localStorage.getItem("cfg")[key] != null && localStorage.getItem("cfg")[key] != undefined){
	      		all = this.findAll();
	      		if(all[key] != undefined && all[key] != null){
	      			return all[key];
	      		}
	      		else
	      		{
	      			return false;
	      		}
	      	}
	      	else
	      	{
	      		return false;
	      	}
      	}
      	else
      	{
      		return false;
      	}
    },
    insert: function(key, value){
    	if(this.check()){
    		all = this.findAll();
    		all[key] = value;
    		localStorage.setItem("cfg", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    },
    remove: function(key){
    	if(this.check()){
    		all = this.findAll();
    		delete all[key];
    		localStorage.setItem("cfg", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    },
    updateValue: function(key, value){
    	if(this.check()){
    		all = this.findAll();
    		all[key] = value;
    		localStorage.setItem("cfg", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    }

});

var TableProducts = Class.extend({
  check: function(){
  	if(checkKey("productsList")){
      	return true;
      }
      else
      {
      	return false;
      }
  },
  findAll: function(){
      if(this.check()){
      	return JSON.parse(localStorage.getItem("productsList"));
      }
      else
      {
      	return false;
      }
   },
   insertAll: function(listObject){
    	if(this.check()){
    		all = listObject;
    		localStorage.setItem("productsList", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    },
    deleteAll: function(){
    	all = {};
    	localStorage.setItem("productsList", JSON.stringify(all));
    }
});<commit_msg>Corrections sql<commit_after>/*global Class*/
/*global console*/
/*global localStorage*/
var checkKey = function(key){
	if(localStorage && (localStorage.getItem(key) != undefined && localStorage.getItem(key) != null) ){
      	return true;
     }
     else
     {
     	return false;
     }
};
var TableConfiguration = Class.extend({
  check: function(){
  	if(checkKey("cfg")){
      	return true;
      }
      else
      {
      	return false;
      }
  },
  findAll: function(){
      if(this.check()){
      	return JSON.parse(localStorage.getItem("cfg"));
      }
      else
      {
      	return false;
      }
    },
    findValueByKey: function(key){
    	if(this.check()){
	      	if(localStorage.getItem("cfg")[key] != null && localStorage.getItem("cfg")[key] != undefined){
	      		all = this.findAll();
	      		if(all[key] != undefined && all[key] != null){
	      			return all[key];
	      		}
	      		else
	      		{
	      			return false;
	      		}
	      	}
	      	else
	      	{
	      		return false;
	      	}
      	}
      	else
      	{
      		return false;
      	}
    },
    insert: function(key, value){
    	if(this.check()){
    		all = this.findAll();
    		all[key] = value;
    		localStorage.setItem("cfg", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    },
    remove: function(key){
    	if(this.check()){
    		all = this.findAll();
    		delete all[key];
    		localStorage.setItem("cfg", JSON.stringify(all));
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    },
    updateValue: function(key, value){
    	if(this.check()){
    		all = this.findAll();
    		all[key] = value;
    		localStorage.setItem("cfg", JSON.stringify(all));
    	}
    	else
    	{
    		return false;
    	}
    }

});

var TableProducts = Class.extend({
  check: function(){
  	if(checkKey("productsList")){
      	return true;
      }
      else
      {
      	return false;
      }
  },
  findAll: function(){
      if(this.check()){
      	if(localStorage.getItem("productsList") != undefined && localStorage.getItem("productsList") != null){
      		return JSON.parse(localStorage.getItem("productsList"));
      	}
      	else
      	{
      		return false;
      	}
      }
      else
      {
      	return false;
      }
   },
   insertAll: function(listObject){
    	if(this.check()){
    		all = listObject;
    		localStorage.setItem("productsList", JSON.stringify(all));
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    },
    deleteAll: function(){
    	all = {};
    	localStorage.setItem("productsList", JSON.stringify(all));
    	return true;
    }
});<|endoftext|>


<commit_before>var GRAVITY = .3;
var GROUND, BG, PLAYER, ENEMY, FIRE;
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg;

function preload() {

    GroundImg = loadImage('http://i.imgur.com/vO9az9I.png');

}

function setup() {
  createCanvas(1400,600);

  GROUND = createSprite(width/2, 550);
  GROUND.addImage(GroundImg);

  PLAYER = createSprite(700, 475, 50, 50);

}

function draw() {
  // background(100, 150, 200);

  //Basic left and right movement for PLAYER aka KANYE aka YEEZUS
  if(keyDown("a")) {
    PLAYER.position.x -= 4;
  } else if(keyDown("d")) {
    PLAYER.position.x += 4;
  }

  // Says that CAMERA will always follow PLAYER
  camera.position.x = PLAYER.position.x;

  //My poor attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x - GROUND.width) {
    GROUND.position.x += GROUND.width;
   }

  //Check values here
  console.log("camera: " + camera.position.x);
  console.log("ground: " + GROUND.position.x);

  drawSprites();
}
<commit_msg>Kanye Beta .1<commit_after>var GRAVITY = .5;
var JUMP = -10;
var GROUND, BG, PLAYER, ENEMY, FIRE;
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg;

function preload() {

    GroundImg = loadImage('http://i.imgur.com/vO9az9I.png');
    FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);

  GROUND = createSprite(width/2, 550);
  GROUND.addImage(GroundImg);

  PLAYER = createSprite(width/2, 475, 50, 50);
  PLAYER.addImage(PlayerImg);

  PLAYER.setCollider("circle", 0,0,50);

  FIRE = new Group();

}

function draw() {
  background(100, 150, 200);

  textAlign(CENTER);
  text("Controls: AWSD + X", width/2, 20);

  PLAYER.velocity.y += GRAVITY;

  //Says that CAMERA will always follow PLAYER
  camera.position.x = PLAYER.position.x;

  //My poor attempt to get the ground to wrap with movement
  if(camera.position.x > width / 4 + GROUND.position.x) {
    GROUND.position.x += (camera.position.x) - (width / 4 + GROUND.position.x);
  } else if(camera.position.x < GROUND.position.x + width / 4) {
    GROUND.position.x -= GROUND.width;
  }

  //Basic left and right movement for PLAYER aka KANYE aka YEEZUS
  if(keyDown("a")) {
    PLAYER.position.x -= 4;
  } else if(keyDown("d")) {
    PLAYER.position.x += 4;
  }

  if(keyDown("w")) {
    PLAYER.velocity.y = JUMP;
  }

  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  //Check values here
  console.log("camera: " + camera.position.x);
  console.log("ground: " + GROUND.position.x);

  if(keyWentDown("x")) {
    var fire = createSprite(PLAYER.position.x + 20, PLAYER.position.y);
    fire.addImage(FireImg);
    fire.setSpeed(7, 0);
    fire.life = 40;
    FIRE.add(fire);
  }

  GROUND.debug = mouseIsPressed;
  PLAYER.debug = mouseIsPressed;

  drawSprites();
}
<|endoftext|>


<commit_before>/**
 * Module for global and app configs.
 * @module kbox.core.config
 */

'use strict';

var path = require('path');
var os = require('os');
var fs = require('fs');
var env = require('./env.js');
var deps = require('./deps.js');
var log = require('./log.js');
var _ = require('lodash');

// Constants
var CONFIG_FILENAME = 'kalabox.json';
exports.CONFIG_FILENAME = CONFIG_FILENAME;

var DEFAULT_GLOBAL_CONFIG = {
  domain: 'kbox',
  engine: 'kalabox-engine-docker@https://github.com/kalabox/' +
    'kalabox-engine-docker/tarball/elton-rocketman',
  engineRepo: 'kalabox',
  codeDir: 'code',
  services: 'kalabox-services-docker@https://github.com/kalabox/' +
    'kalabox-services-docker/tarball/elton-rocketman',
  apps: [
    'kalabox-app-backdrop@https://github.com/kalabox/' +
      'kalabox-app-backdrop/tarball/elton-rocketman',
    'kalabox-app-drupal@https://github.com/kalabox/' +
      'kalabox-app-drupal/tarball/elton-rocketman',
    'kalabox-app-pantheon@https://github.com/kalabox/' +
      'kalabox-app-pantheon/tarball/master',
  ],
  profile: 'standard',
  sharing: true,
  stats: {
    report: true,
    url: 'http://stats.kalabox.biz'
  },
  kboxRoot: ':home:/kalabox',
  kalaboxRoot: ':kboxRoot:',
  logLevel: 'debug',
  logLevelConsole: 'info',
  logRoot: ':sysConfRoot:/logs',
  downloadsRoot: ':sysConfRoot:/downloads',
  appsRoot: ':kboxRoot:/apps',
  appRegistry: ':sysConfRoot:/appRegistry.json',
  globalPluginRoot: ':kboxRoot:/plugins',
  globalPlugins: [
    'kalabox-core',
    'kalabox-syncthing',
    'kalabox-app-drupal',
    'kalabox-app-backdrop'
  ],
  configSources: [
    'DEFAULT_GLOBAL_CONFIG'
  ],
  shareIgnores: [
    '*.7z',
    '*.bz2',
    '*.dmg',
    '*.gz',
    '*.iso',
    '*.jar',
    '*.rar',
    '*.tar',
    '*.tgz',
    '*.un~',
    '*.zip',
    '.*.swp',
    '.*DS_Store',
    '.DS_Store*',
    '._*',
    '.git',
    '.sass-cache',
    'Icon',
    'Thumbs.db',
    'ehthumbs.db',
    'sites/default/files/*'
  ]
};

var logDebug = log.debug;
var logInfo = log.info;

/*
 * Pretty print an object.
 */
var pp = function(obj) {
  return JSON.stringify(obj, null, '  ');
};

/*
 * Looks up a key of the config object and returns it.
 */
var lookupKey = function(config, keyToFind) {

  // Recursive function.
  var rec = function(o, prefix) {

    // Loop through each of the objects properties to find value.
    return _.find(o, function(val, key) {

      // Build namespaced name.
      var name = _.filter([prefix, key]).join('.');

      if (typeof val === 'string') {

        // If name of string value matches, return it.
        return (':' + name + ':') === keyToFind;

      } else if (typeof val === 'object') {

        // Recursively check object.
        return rec(val, name);

      } else {

        // Not a string or an object so just return false.
        return false;

      }

    });

  };

  // Init recursive function and return.
  return rec(config);

};

/*
 * Translate a value.
 */
var normalizeValue = exports.normalizeValue = function(config, v) {

  // Search value for regex matches.
  //var params = v.match(/:[a-zA-Z0-9-_]*:/g);
  var params;
  try {
    params = v.match(/:[a-zA-Z0-9-_]*:/g);
  }
  catch (err) {
    throw new Error(typeof v);
  }

  if (!params) {

    // No params were found, so just return original value.
    return v;

  } else {

    // Reduce list of params to final value.
    return _.reduce(params, function(acc, param) {

      // Get replacement value from config object based on param name.
      var replacementValue = lookupKey(config, param);

      if (!replacementValue) {

        // Replacement value was not found so just return value.
        return acc;

      } else {

        // Replace and return.
        return acc.replace(param, replacementValue);

      }

    }, v);

  }

};

/*
 * Walk the properties of the top level object, replacing strings
 * with other properties values.
 */
var normalize = exports.normalize = function(config) {

  // Recursive funciton.
  var rec = function(o) {

    // Loop through each property of the object.
    _.each(o, function(val, key) {

      if (typeof val === 'string') {

        // For string values normalize.
        o[key] = normalizeValue(config, val);

      } else if (typeof val === 'object') {

        // For object values recursively normalize.
        rec(val);

      }

    });

  };

  // Init recursive function with config.
  rec(config);

  // Return config.
  return config;

};

function sort(config) {
  var keys = Object.keys(config).sort();
  var retVal = {};
  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    retVal[key] = config[key];
  }
  return retVal;
}

// @todo: implement
var KEYS_TO_CONCAT = [
  'configSources',
  'shareIgnores'
];

function mixIn(a, b) {
  for (var key in b) {
    var shouldConcat = _.contains(KEYS_TO_CONCAT, key);
    if (shouldConcat) {
      // Concat.
      if (_.isArray(a[key]) && _.isArray(b[key])) {
        a[key] = _.uniq(a[key].concat(b[key]));
        a[key].sort();
      } else {
        a[key] = b[key];
      }
    } else {
      // Override.
      a[key] = b[key];
    }
  }
  return sort(normalize(a));
}
exports.mixIn = mixIn;

var getPackageJson = function() {
  return require(path.join(env.getSourceRoot(), 'package.json'));
};

/**
 * Gets the kalabox environment config.
 * @returns {object} config - The kalabox enviroment config.
 * @example
 * var envConfig = kbox.core.config.getEnvConfig();
 * // Print home directory to stdout.
 * console.log(envConfig.home);
 */
exports.getEnvConfig = function() {
  var packageJson = getPackageJson();
  var provisioned = false;
  if (fs.existsSync(path.join(env.getSysConfRoot(), 'provisioned'))) {
    provisioned = true;
  }
  return {
    provisioned: provisioned,
    home: env.getHomeDir(),
    os: {
      type: os.type(),
      platform: os.platform(),
      release: os.release(),
      arch: os.arch()
    },
    sysConfRoot: env.getSysConfRoot(),
    sysProviderRoot: env.getSysProviderRoot(),
    srcRoot: env.getSourceRoot(),
    version: packageJson.version,
    configSources: [
      'ENV_CONFIG'
    ]
  };
};

/**
 * Gets the default config. The default config is a combination of the
 *   environment config and a set of default config values.
 * @returns {object} config - The kalabox default config.
 * @example
 * var defaultConfig = kbox.core.config.getDefaultConfig();
 * // Print global plugins
 * defaultConfig.globalPlugins.forEach(function(plugin) {
 *   console.log(plugin)  ;
 * });
 */
exports.getDefaultConfig = function() {
  return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG);
};

var getReleaseConfigFilepath = exports.getReleaseConfigFilepath = function() {
  return path.join(env.getSourceRoot(), CONFIG_FILENAME);
};

var getGlobalConfigFilepath = function() {
  return path.join(env.getSysConfRoot(), CONFIG_FILENAME);
};

var loadConfigFile = function(configFilepath) {
  var loadedConfigFile = require(configFilepath);
  loadedConfigFile.configSources = [configFilepath];
  return loadedConfigFile;
};

/**
 * Gets the global config. The global config is a combination of the
 *   environment config, the default config, and any values overriden
 *   in the $HOME/.kalabox/kalabox.json config file.
 * @returns {object} config - The kalabox global config.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * // Print the entire global config.
 * console.log(JSON.stringify(globalConfig, null, '\t'));
 */
exports.getGlobalConfig = function() {
  var defaultConfig = this.getDefaultConfig();
  var filesToLoad = [
    getReleaseConfigFilepath(),
    getGlobalConfigFilepath()
  ];
  var globalConfig = _.reduce(filesToLoad, function(config, fileToLoad) {
    if (fs.existsSync(fileToLoad)) {
      var loadedConfigFile = loadConfigFile(fileToLoad);
      config = mixIn(config, loadedConfigFile);
    }
    return config;
  }, defaultConfig);
  return globalConfig;
};

exports.getAppConfigFilepath = function(app, config) {
  return path.join(config.appsRoot, app.name, CONFIG_FILENAME);
};

/**
 * Gets the app config for an app. The app config is a combination of the
 *   environment config, the default config, any values overriden in the
 *   $HOME/.kalabox/kalabox.json config file, and the kalabox.json config
 *   file in the app's root directory.
 * @arg {string} app - The name of the app you'd like to get the config for.
 * @arg {string} appRoot [optional] - Directory to load the
 * app's config file from.
 * @returns {object} config - The app's kalabox app config.
 * @example
 * var appConfig = kbox.core.config.getAppConfig('myapp');
 * // Print the entire app config.
 * console.log(JSON.stringify(appConfig, null, '\t'));
 */
exports.getAppConfig = function(app, appRoot) {
  // @todo: this is jank
  if (typeof app === 'string') {
    var appName = app;
    app = {name: appName};
  }

  var globalConfig = this.getGlobalConfig();

  if (!appRoot) {
    appRoot = path.join(globalConfig.appsRoot, app.name);
  }

  var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME);
  var appConfigFile = require(appConfigFilepath);
  appConfigFile.appRoot = appRoot;
  appConfigFile.appCidsRoot = ':appRoot:/.cids';
  var retVal = mixIn(globalConfig, appConfigFile);
  logDebug('CONFIG => App config loaded.', retVal);
  return retVal;
};
<commit_msg>Dont use pantheon app for now<commit_after>/**
 * Module for global and app configs.
 * @module kbox.core.config
 */

'use strict';

var path = require('path');
var os = require('os');
var fs = require('fs');
var env = require('./env.js');
var deps = require('./deps.js');
var log = require('./log.js');
var _ = require('lodash');

// Constants
var CONFIG_FILENAME = 'kalabox.json';
exports.CONFIG_FILENAME = CONFIG_FILENAME;

var DEFAULT_GLOBAL_CONFIG = {
  domain: 'kbox',
  engine: 'kalabox-engine-docker@https://github.com/kalabox/' +
    'kalabox-engine-docker/tarball/elton-rocketman',
  engineRepo: 'kalabox',
  codeDir: 'code',
  services: 'kalabox-services-kalabox@https://github.com/kalabox/' +
    'kalabox-services-kalabox/tarball/elton-rocketman',
  apps: [
    'kalabox-app-backdrop@https://github.com/kalabox/' +
      'kalabox-app-backdrop/tarball/elton-rocketman',
    'kalabox-app-drupal@https://github.com/kalabox/' +
      'kalabox-app-drupal/tarball/elton-rocketman'
  ],
  profile: 'standard',
  sharing: true,
  stats: {
    report: true,
    url: 'http://stats.kalabox.biz'
  },
  kboxRoot: ':home:/kalabox',
  kalaboxRoot: ':kboxRoot:',
  logLevel: 'debug',
  logLevelConsole: 'info',
  logRoot: ':sysConfRoot:/logs',
  downloadsRoot: ':sysConfRoot:/downloads',
  appsRoot: ':kboxRoot:/apps',
  appRegistry: ':sysConfRoot:/appRegistry.json',
  globalPluginRoot: ':kboxRoot:/plugins',
  globalPlugins: [
    'kalabox-core',
    'kalabox-syncthing',
    'kalabox-app-drupal',
    'kalabox-app-backdrop'
  ],
  configSources: [
    'DEFAULT_GLOBAL_CONFIG'
  ],
  shareIgnores: [
    '*.7z',
    '*.bz2',
    '*.dmg',
    '*.gz',
    '*.iso',
    '*.jar',
    '*.rar',
    '*.tar',
    '*.tgz',
    '*.un~',
    '*.zip',
    '.*.swp',
    '.*DS_Store',
    '.DS_Store*',
    '._*',
    '.git',
    '.sass-cache',
    'Icon',
    'Thumbs.db',
    'ehthumbs.db',
    'sites/default/files/*'
  ]
};

var logDebug = log.debug;
var logInfo = log.info;

/*
 * Pretty print an object.
 */
var pp = function(obj) {
  return JSON.stringify(obj, null, '  ');
};

/*
 * Looks up a key of the config object and returns it.
 */
var lookupKey = function(config, keyToFind) {

  // Recursive function.
  var rec = function(o, prefix) {

    // Loop through each of the objects properties to find value.
    return _.find(o, function(val, key) {

      // Build namespaced name.
      var name = _.filter([prefix, key]).join('.');

      if (typeof val === 'string') {

        // If name of string value matches, return it.
        return (':' + name + ':') === keyToFind;

      } else if (typeof val === 'object') {

        // Recursively check object.
        return rec(val, name);

      } else {

        // Not a string or an object so just return false.
        return false;

      }

    });

  };

  // Init recursive function and return.
  return rec(config);

};

/*
 * Translate a value.
 */
var normalizeValue = exports.normalizeValue = function(config, v) {

  // Search value for regex matches.
  //var params = v.match(/:[a-zA-Z0-9-_]*:/g);
  var params;
  try {
    params = v.match(/:[a-zA-Z0-9-_]*:/g);
  }
  catch (err) {
    throw new Error(typeof v);
  }

  if (!params) {

    // No params were found, so just return original value.
    return v;

  } else {

    // Reduce list of params to final value.
    return _.reduce(params, function(acc, param) {

      // Get replacement value from config object based on param name.
      var replacementValue = lookupKey(config, param);

      if (!replacementValue) {

        // Replacement value was not found so just return value.
        return acc;

      } else {

        // Replace and return.
        return acc.replace(param, replacementValue);

      }

    }, v);

  }

};

/*
 * Walk the properties of the top level object, replacing strings
 * with other properties values.
 */
var normalize = exports.normalize = function(config) {

  // Recursive funciton.
  var rec = function(o) {

    // Loop through each property of the object.
    _.each(o, function(val, key) {

      if (typeof val === 'string') {

        // For string values normalize.
        o[key] = normalizeValue(config, val);

      } else if (typeof val === 'object') {

        // For object values recursively normalize.
        rec(val);

      }

    });

  };

  // Init recursive function with config.
  rec(config);

  // Return config.
  return config;

};

function sort(config) {
  var keys = Object.keys(config).sort();
  var retVal = {};
  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    retVal[key] = config[key];
  }
  return retVal;
}

// @todo: implement
var KEYS_TO_CONCAT = [
  'configSources',
  'shareIgnores'
];

function mixIn(a, b) {
  for (var key in b) {
    var shouldConcat = _.contains(KEYS_TO_CONCAT, key);
    if (shouldConcat) {
      // Concat.
      if (_.isArray(a[key]) && _.isArray(b[key])) {
        a[key] = _.uniq(a[key].concat(b[key]));
        a[key].sort();
      } else {
        a[key] = b[key];
      }
    } else {
      // Override.
      a[key] = b[key];
    }
  }
  return sort(normalize(a));
}
exports.mixIn = mixIn;

var getPackageJson = function() {
  return require(path.join(env.getSourceRoot(), 'package.json'));
};

/**
 * Gets the kalabox environment config.
 * @returns {object} config - The kalabox enviroment config.
 * @example
 * var envConfig = kbox.core.config.getEnvConfig();
 * // Print home directory to stdout.
 * console.log(envConfig.home);
 */
exports.getEnvConfig = function() {
  var packageJson = getPackageJson();
  var provisioned = false;
  if (fs.existsSync(path.join(env.getSysConfRoot(), 'provisioned'))) {
    provisioned = true;
  }
  return {
    provisioned: provisioned,
    home: env.getHomeDir(),
    os: {
      type: os.type(),
      platform: os.platform(),
      release: os.release(),
      arch: os.arch()
    },
    sysConfRoot: env.getSysConfRoot(),
    sysProviderRoot: env.getSysProviderRoot(),
    srcRoot: env.getSourceRoot(),
    version: packageJson.version,
    configSources: [
      'ENV_CONFIG'
    ]
  };
};

/**
 * Gets the default config. The default config is a combination of the
 *   environment config and a set of default config values.
 * @returns {object} config - The kalabox default config.
 * @example
 * var defaultConfig = kbox.core.config.getDefaultConfig();
 * // Print global plugins
 * defaultConfig.globalPlugins.forEach(function(plugin) {
 *   console.log(plugin)  ;
 * });
 */
exports.getDefaultConfig = function() {
  return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG);
};

var getReleaseConfigFilepath = exports.getReleaseConfigFilepath = function() {
  return path.join(env.getSourceRoot(), CONFIG_FILENAME);
};

var getGlobalConfigFilepath = function() {
  return path.join(env.getSysConfRoot(), CONFIG_FILENAME);
};

var loadConfigFile = function(configFilepath) {
  var loadedConfigFile = require(configFilepath);
  loadedConfigFile.configSources = [configFilepath];
  return loadedConfigFile;
};

/**
 * Gets the global config. The global config is a combination of the
 *   environment config, the default config, and any values overriden
 *   in the $HOME/.kalabox/kalabox.json config file.
 * @returns {object} config - The kalabox global config.
 * @example
 * var globalConfig = kbox.core.config.getGlobalConfig();
 * // Print the entire global config.
 * console.log(JSON.stringify(globalConfig, null, '\t'));
 */
exports.getGlobalConfig = function() {
  var defaultConfig = this.getDefaultConfig();
  var filesToLoad = [
    getReleaseConfigFilepath(),
    getGlobalConfigFilepath()
  ];
  var globalConfig = _.reduce(filesToLoad, function(config, fileToLoad) {
    if (fs.existsSync(fileToLoad)) {
      var loadedConfigFile = loadConfigFile(fileToLoad);
      config = mixIn(config, loadedConfigFile);
    }
    return config;
  }, defaultConfig);
  return globalConfig;
};

exports.getAppConfigFilepath = function(app, config) {
  return path.join(config.appsRoot, app.name, CONFIG_FILENAME);
};

/**
 * Gets the app config for an app. The app config is a combination of the
 *   environment config, the default config, any values overriden in the
 *   $HOME/.kalabox/kalabox.json config file, and the kalabox.json config
 *   file in the app's root directory.
 * @arg {string} app - The name of the app you'd like to get the config for.
 * @arg {string} appRoot [optional] - Directory to load the
 * app's config file from.
 * @returns {object} config - The app's kalabox app config.
 * @example
 * var appConfig = kbox.core.config.getAppConfig('myapp');
 * // Print the entire app config.
 * console.log(JSON.stringify(appConfig, null, '\t'));
 */
exports.getAppConfig = function(app, appRoot) {
  // @todo: this is jank
  if (typeof app === 'string') {
    var appName = app;
    app = {name: appName};
  }

  var globalConfig = this.getGlobalConfig();

  if (!appRoot) {
    appRoot = path.join(globalConfig.appsRoot, app.name);
  }

  var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME);
  var appConfigFile = require(appConfigFilepath);
  appConfigFile.appRoot = appRoot;
  appConfigFile.appCidsRoot = ':appRoot:/.cids';
  var retVal = mixIn(globalConfig, appConfigFile);
  logDebug('CONFIG => App config loaded.', retVal);
  return retVal;
};
<|endoftext|>


<commit_before>(function() {
	var getJSQueryString = function(script) {
		var
		  scripts = document.getElementsByTagName('script'),
		  i,
		  curScript;

		for (i = 0; i < scripts.length; ++i) {
			curScript = scripts[i];

			if (curScript.src.match(script)) {
				return  (curScript.src.match(/\?(.*)/) || [undefined])[1];
			}
		}
	}

	var getJSParams = function(script) {
		var
		  qs = getJSQueryString(script),
		  search = /([^&=]+)=?([^&]*)/g,
		  urlParams = {};

		while (match = search.exec(qs))
      urlParams[match[1]] = match[2];

		return urlParams;
	}

	var getJSParamNamed = function (script, name) {
		return  getJSParams(script)[name];
	}

	var bwid = getJSParamNamed('babeltheque.js', 'bwid');

	window.loadBabelthequeScript = function() {
		insertBabelthequeISBNTag();
		$.getScript('http://www.babeltheque.com/bw_' + bwid +'.js');
	}
})();

$.fn.babelthequeTag=function(info) {
	return this.each(function() {
		$(this).append('

');
	});
}

var insertBabelthequeISBNTag = function() {
	if (!$('input#BW_id_isbn'))
		$('body').append('<input type="hidden" id="BW_id_isbn" value="'+isbn+'"\>');
}

var blocNoticeAfterLoad = function (info, isbn, target) {
	if ("" == isbn)
		return;

	var callback = $(window).attr(info + 'NoticeAfterLoad');
	if (undefined == callback)
		return;

	callback(target);
	loadBabelthequeScript();
}

var tagsNoticeAfterLoad = function(target) {
	target.prepend('

');
}

var avisNoticeAfterLoad = function(target) {
	$('

Babelthèque ( évaluations)

')
	.insertAfter(target.find('table tr:nth-child(2)'));
}

var videosNoticeAfterLoad = function(target) {
	target.babelthequeTag('videos');
}

var resumeNoticeAfterLoad = function(target) {
	target.babelthequeTag('citations');
}

var babelthequeNoticeAfterLoad = function(target) {
//	target.empty().babelthequeTag('suggestions');
}
<commit_msg>Amélioration intégration Babélio / Babelthèque<commit_after>(function() {
	var getJSQueryString = function(script) {
		var
		  scripts = document.getElementsByTagName('script'),
		  i,
		  curScript;

		for (i = 0; i < scripts.length; ++i) {
			curScript = scripts[i];

			if (curScript.src.match(script)) {
				return  (curScript.src.match(/\?(.*)/) || [undefined])[1];
			}
		}
	}

	var getJSParams = function(script) {
		var
		  qs = getJSQueryString(script),
		  search = /([^&=]+)=?([^&]*)/g,
		  urlParams = {};

		while (match = search.exec(qs))
      urlParams[match[1]] = match[2];

		return urlParams;
	}

	var getJSParamNamed = function (script, name) {
		return  getJSParams(script)[name];
	}

	var bwid = getJSParamNamed('babeltheque.js', 'bwid');

	window.loadBabelthequeScript = function() {
		insertBabelthequeISBNTag();
		$.getScript('http://www.babeltheque.com/bw_' + bwid +'.js');
	}
})();

$.fn.babelthequeTag=function(info) {
	return this.each(function() {
		$(this).append('

');
	});
}

var insertBabelthequeISBNTag = function() {
	if (!$('input#BW_id_isbn'))
		$('body').append('<input type="hidden" id="BW_id_isbn" value="'+isbn+'"\>');
}

var blocNoticeAfterLoad = function (info, isbn, target) {
	if ("" == isbn)
		return;

	var callback = $(window).attr(info + 'NoticeAfterLoad');
	if (undefined == callback)
		return;

	callback(target);
	loadBabelthequeScript();
}

var tagsNoticeAfterLoad = function(target) {
	target.prepend('

');
}

var avisNoticeAfterLoad = function(target) {
	$('

Babelthèque ( évaluations)

')
	.insertAfter(target.find('table tr:nth-child(2)'));
}

var videosNoticeAfterLoad = function(target) {
	target.babelthequeTag('videos');
}

var resumeNoticeAfterLoad = function(target) {
	target.babelthequeTag('citations');
}

var babelthequeNoticeAfterLoad = function(target) {
	target.empty().babelthequeTag('suggestions');
}
<|endoftext|>


<commit_before>const WIDTH = 600;
const HEIGHT = 600;

const SPACING = 15;

const SQUARE_SIZE = 5;
const GRID_SIZE = 40;

const CIRCLE_CENTER_X = 20;
const CIRCLE_CENTER_Y = 20;
const CIRCLE_RADIUS = 20;

var setup = function() {
  createCanvas(WIDTH, HEIGHT);
  background('#FFFFFF');

  angleMode(DEGREES);

  stroke('#000000');
  fill('#000000');

  strokeWeight(1);
  strokeCap(SQUARE);

  noLoop();
}

var toDegrees = (radians) => {
  return radians * 180 / Math.PI;
}

var distanceBetweenTwoPoints = (ax, ay, bx, by) => {
  return Math.sqrt((bx - ax) ** 2 + (by - ay) ** 2);
}

var setColor = (posX, posY) => {
  var g = Math.round(posX / GRID_SIZE * 99).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});
  var b = Math.round(posY / GRID_SIZE * 99).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});

  var color = '#FF' + g + b;

  console.log(color);
  stroke(color);
  fill(color);
}

var drawSquare = (posX, posY, angle) => {
  const size = 5 + SQUARE_SIZE * Math.random();

  push();

  translate(posX * SPACING, posY * SPACING);
  rotate(angle);
  setColor(posX, posY);
  rect(-(size/2), -(size/2), size, size);

  pop();
}

var isInCircle = (x, y) => {
  return Math.sqrt((x - CIRCLE_CENTER_X) ** 2 + (y - CIRCLE_CENTER_Y) ** 2) < CIRCLE_RADIUS
}

var draw = function() {
  for (let x = 1; x <= GRID_SIZE; x++) {
    for (let y = 1; y <= GRID_SIZE; y++) {
      if (isInCircle(x, y)) {
        drawSquare(x, y, Math.random() * 360);
      }
    }
  }
}
<commit_msg>colored sphere<commit_after>const WIDTH = 600;
const HEIGHT = 600;

const SPACING = 15;

const SQUARE_SIZE = 5;
const GRID_SIZE = 40;

const CIRCLE_CENTER_X = 20;
const CIRCLE_CENTER_Y = 20;
const CIRCLE_RADIUS = 20;

var setup = function() {
  createCanvas(WIDTH, HEIGHT);
  background('#FFFFFF');

  angleMode(DEGREES);

  stroke('#000000');
  fill('#000000');

  strokeWeight(1);
  strokeCap(SQUARE);

  noLoop();
}

var toDegrees = (radians) => {
  return radians * 180 / Math.PI;
}

var distanceBetweenTwoPoints = (ax, ay, bx, by) => {
  return Math.sqrt((bx - ax) ** 2 + (by - ay) ** 2);
}

var setColor = (posX, posY) => {
  var g = Math.round(posX / GRID_SIZE * 255);
  var b = Math.round(posY / GRID_SIZE * 255);

  // Convert to hex
  g = Number(g).toString(16);
  g = g.length === 1 ? '0' + g : g;
  b = Number(b).toString(16);
  b = b.length === 1 ? '0' + b : b;

  var color = '#FF' + g + b;

  stroke(color);
  fill(color);
}

var drawSquare = (posX, posY, angle) => {
  const size = 5 + SQUARE_SIZE * Math.random();

  push();

  translate(posX * SPACING, posY * SPACING);
  rotate(angle);
  setColor(posX, posY);
  rect(-(size/2), -(size/2), size, size);

  pop();
}

var isInCircle = (x, y) => {
  return Math.sqrt((x - CIRCLE_CENTER_X) ** 2 + (y - CIRCLE_CENTER_Y) ** 2) < CIRCLE_RADIUS
}

var draw = function() {
  for (let x = 1; x <= GRID_SIZE; x++) {
    for (let y = 1; y <= GRID_SIZE; y++) {
      if (isInCircle(x, y)) {
        drawSquare(x, y, Math.random() * 360);
      }
    }
  }
}
<|endoftext|>


<commit_before>// Bower Config

// UZI
// added searchpath array
module.exports = function() {

  var c = require('rc') ('bower', {
    //Bower Defaults
    directory: 'components',
    json:      'component.json',
    endpoint:  'https://bower.herokuapp.com',
    searchpath: []
  });

  // temp for now
  // rc doesn't read .bowerrc from local so we do it manually
  var fs = require('fs');
  if (fs.existsSync('.bowerrc')) {
	c = JSON.parse(fs.readFileSync('.bowerrc').toString());
  }

  return c;

}();
// END UZI
<commit_msg>Code cleanup<commit_after>// Bower Config

module.exports = function() {

  var c = require('rc') ('bower', {
    //Bower Defaults
    directory: 'components',
    json:      'component.json',
    endpoint:  'https://bower.herokuapp.com',
    searchpath: []
  });

  // temp for now
  // rc doesn't read .bowerrc from local so we do it manually
  var fs = require('fs');
  if (fs.existsSync('.bowerrc')) {
	c = JSON.parse(fs.readFileSync('.bowerrc').toString());
  }

  return c;

}();
<|endoftext|>


<commit_before>import {
  define,
  render,
  Component,
  cloneElement,
  WeElement
} from '../../src/omi'

describe('install()', () => {
  let scratch
  //const Empty = () => null

  before(() => {
    scratch = document.createElement('div')
    ;(document.body || document.documentElement).appendChild(scratch)
  })

  beforeEach(() => {
    //let c = scratch.firstElementChild;
    //if (c) render(<Empty />, scratch, { merge: c })
    scratch.innerHTML = ''
  })

  after(() => {
    scratch.parentNode.removeChild(scratch)
    scratch = null
  })

  it('should render components', () => {
    class Ele extends Component {
      render() {
        return
Ele

      }
      install() {
        console.log(123)
      }
    }

    define('my-ele', Ele)
    sinon.spy(Ele.prototype, 'render')
    render(<my-ele />, scratch)

    expect(Ele.prototype.render)
      .to.have.been.calledOnce.and.to.have.been.calledWithMatch({}, {})
      .and.to.have.returned(sinon.match({ nodeName: 'div' }))

    expect(scratch.innerHTML).to.equal('
Ele
')
  })

  it('should render components with props', () => {
    const PROPS = { foo: 'bar', onBaz: () => {} }
    let constructorProps

    class C2 extends Component {
      constructor(props) {
        super(props)
        constructorProps = props
      }
      render(props) {
        return

      }
    }
    sinon.spy(C2.prototype, 'render')

    define('c2-ele', C2)
    render(<c2-ele {...PROPS} />, scratch)

    expect(constructorProps).to.deep.equal(PROPS)

    expect(C2.prototype.render)
      .to.have.been.calledOnce.and.to.have.been.calledWithMatch(PROPS, {})
      .and.to.have.returned(
        sinon.match({
          nodeName: 'div',
          attributes: PROPS
        })
      )

    expect(scratch.innerHTML).to.equal('

')
  })

  it('should clone components', () => {
    let instance =
    let clone = cloneElement(instance)
    expect(clone).to.deep.equal(instance)
  })

  it('should render string', () => {
    class StringComponent extends Component {
      render() {
        return 'Hi there'
      }
    }

    define('a-b', StringComponent)

    render(, scratch)
    expect(scratch.innerHTML).to.equal('Hi there')
  })

  it('should render number as string', () => {
    define('c-d', class extends Component {
      render() {
        return 42
      }
    })
    render(<c-d />, scratch)
    expect(scratch.innerHTML).to.equal('42')
  })

  it('should render null as empty string', () => {
    define('c-d', class extends Component {
      render() {
        return null
      }
    })
    render(<c-d />, scratch)
    expect(scratch.innerHTML).to.equal('')
  })

  it('should remove orphaned elements replaced by Components', () => {
    define('c-d', class Comp extends Component {
      render() {
        return span in a component
      }
    })

    let root
    function test(content) {
      root = render(content, scratch, { merge: root })
    }

    test(<c-d />)
    test(
just a div
)
    test(<c-d />)

    expect(scratch.innerHTML).to.equal('span in a component')
  })

  describe('props.children', () => {
    describe('should always be an array', () => {
      it('render props.children[0]', () => {
        define('my-p', class extends WeElement {
          render(props) {
            return props.children[0]
          }
        })

        define('my-app', class extends WeElement {
          render() {
            return (

                <my-p>

Hello World

                </my-p>

            )
          }
        })

        render(<my-app />, scratch)

        expect(scratch.innerHTML).to.equal('

Hello World

')
      })
    })
  })
})
<commit_msg>remove ; in browser/index.js<commit_after>import {
  define,
  render,
  Component,
  cloneElement,
  WeElement
} from '../../src/omi'

describe('install()', () => {
  let scratch
  //const Empty = () => null

  before(() => {
    scratch = document.createElement('div')
    (document.body || document.documentElement).appendChild(scratch)
  })

  beforeEach(() => {
    //let c = scratch.firstElementChild;
    //if (c) render(<Empty />, scratch, { merge: c })
    scratch.innerHTML = ''
  })

  after(() => {
    scratch.parentNode.removeChild(scratch)
    scratch = null
  })

  it('should render components', () => {
    class Ele extends Component {
      render() {
        return
Ele

      }
      install() {
        console.log(123)
      }
    }

    define('my-ele', Ele)
    sinon.spy(Ele.prototype, 'render')
    render(<my-ele />, scratch)

    expect(Ele.prototype.render)
      .to.have.been.calledOnce.and.to.have.been.calledWithMatch({}, {})
      .and.to.have.returned(sinon.match({ nodeName: 'div' }))

    expect(scratch.innerHTML).to.equal('
Ele
')
  })

  it('should render components with props', () => {
    const PROPS = { foo: 'bar', onBaz: () => {} }
    let constructorProps

    class C2 extends Component {
      constructor(props) {
        super(props)
        constructorProps = props
      }
      render(props) {
        return

      }
    }
    sinon.spy(C2.prototype, 'render')

    define('c2-ele', C2)
    render(<c2-ele {...PROPS} />, scratch)

    expect(constructorProps).to.deep.equal(PROPS)

    expect(C2.prototype.render)
      .to.have.been.calledOnce.and.to.have.been.calledWithMatch(PROPS, {})
      .and.to.have.returned(
        sinon.match({
          nodeName: 'div',
          attributes: PROPS
        })
      )

    expect(scratch.innerHTML).to.equal('

')
  })

  it('should clone components', () => {
    let instance =
    let clone = cloneElement(instance)
    expect(clone).to.deep.equal(instance)
  })

  it('should render string', () => {
    class StringComponent extends Component {
      render() {
        return 'Hi there'
      }
    }

    define('a-b', StringComponent)

    render(, scratch)
    expect(scratch.innerHTML).to.equal('Hi there')
  })

  it('should render number as string', () => {
    define('c-d', class extends Component {
      render() {
        return 42
      }
    })
    render(<c-d />, scratch)
    expect(scratch.innerHTML).to.equal('42')
  })

  it('should render null as empty string', () => {
    define('c-d', class extends Component {
      render() {
        return null
      }
    })
    render(<c-d />, scratch)
    expect(scratch.innerHTML).to.equal('')
  })

  it('should remove orphaned elements replaced by Components', () => {
    define('c-d', class Comp extends Component {
      render() {
        return span in a component
      }
    })

    let root
    function test(content) {
      root = render(content, scratch, { merge: root })
    }

    test(<c-d />)
    test(
just a div
)
    test(<c-d />)

    expect(scratch.innerHTML).to.equal('span in a component')
  })

  describe('props.children', () => {
    describe('should always be an array', () => {
      it('render props.children[0]', () => {
        define('my-p', class extends WeElement {
          render(props) {
            return props.children[0]
          }
        })

        define('my-app', class extends WeElement {
          render() {
            return (

                <my-p>

Hello World

                </my-p>

            )
          }
        })

        render(<my-app />, scratch)

        expect(scratch.innerHTML).to.equal('

Hello World

')
      })
    })
  })
})
<|endoftext|>


<commit_before>var amplitude,
    level,
    song,
    speed,
    amplitudeLevel;

function preload(){
  song = loadSound('/assets/FortunateSon.mp3');
}

function setup() {
  createCanvas(100, 100);
  song.play();
  amplitude = new p5.Amplitude();

}

function draw() {
  level = amplitude.getLevel();
  var size = map(level, 0, 1, 1, 2);
  amplitudeLevel = createElement('span', size);
  console.log("size:" + size);
}
<commit_msg>Readjusts canvas height and width to be invisible<commit_after>var amplitude,
    level,
    song,
    speed,
    amplitudeLevel;

function preload(){
  song = loadSound('/assets/FortunateSon.mp3');
}

function setup() {
  createCanvas(0, 0);
  song.play();
  amplitude = new p5.Amplitude();

}

function draw() {
  level = amplitude.getLevel();
  var size = map(level, 0, 1, 1, 2);
  amplitudeLevel = createElement('span', size);
  console.log("size:" + size);
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const Node = require('./node');
var resolveEvaluateResult = require('./remote_object');

var Driver = function(crd) {
    this.crd = crd;
    this.Page = this.crd.Page;
    this.DOM = this.crd.DOM;
    this.Network = this.crd.Network;
    this.Runtime = this.crd.Runtime;

    this.timeouts = {
        script: 30000, // ms
    };
};

Driver.prototype.init = function() {
    return Promise.all([
        this.Page.enable(),
        this.DOM.enable(),
        this.Runtime.enable(),
        this.Network.enable()
    ]);
};

Driver.createDriver = function(crd) {
    const driver = new Driver(crd);
    return driver.init().then(() => { return driver });
};

Driver.prototype.navigate = function(args) {
    const self = this;
    return new Promise((resolve, reject) => {
        self.crd.once('Page.loadEventFired', function() {
            resolve('done');
        });
        self.Page.navigate(args).catch((err) => { reject(err) });
    });
};

Driver.prototype.getDocument = function() {
    return this.DOM.getDocument();
};

Driver.prototype.querySelector = function(args) {
    const self = this;
    return this.DOM.getDocument().then((node) => {
        args['nodeId'] = node.root.nodeId;
        return this.DOM.querySelector(args).then((result) => {
            return new Node(self, result.nodeId);
        });
    });
};

Driver.prototype.querySelectorAll = function(args) {
    const self = this;
    return this.DOM.getDocument().then((node) => {
        args['nodeId'] = node.root.nodeId;
        return this.DOM.querySelectorAll(args).then((result) => {
            const nodeIds = result.nodeIds;
            const data = [];

            for (var nodeId in nodeIds) {
                data.push(new Node(self, nodeId));
            }

            return data
        });
    });
};

Driver.prototype.reload = function() {
    const self = this;
    return new Promise((resolve, reject) => {
        self.crd.once('Page.loadEventFired', function() {
            resolve('done');
        });
        self.Page.reload({ignoreCache: true}).catch((err) => { reject(err) });
    });
};

Driver.prototype.pdf = function(path, options) {
    return this.Page.printToPdf(options).then((result) => {
        const data = Buffer.from(result.data, 'base64')
        return new Promise((resolve, reject) => {
            fs.writeFile(path, data, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(path);
                }
            });
        });
    });
};

Driver.prototype.screenshot = function(path, options) {
    // TODO file ext needs validation
    return this.Page.captureScreenshot(options).then((result) => {
        const data = Buffer.from(result.data, 'base64')
        return new Promise((resolve, reject) => {
            fs.writeFile(path, data, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(path);
                }
            });
        });
    });
};

Driver.prototype.setUserAgent = function(args) {
    return this.Network.setUserAgentOverride(args);
};

Driver.prototype.getCookies = function(args) {
    // handle no args .... should default to current url
    return this.Network.getCookies(args);
};

Driver.prototype.getAllCookies = function() {
    return this.Network.getAllCookies();
};

Driver.prototype.deleteAllCookies = function() {
    const self = this;
    return this.Network.canClearBrowserCookies().then((result) => {
        if ( result.result ) {
            return self.Network.clearBrowserCookies();
        } else {
            return Promise.reject(new Error('unable to clear browser cookies'))
        }
    });
};

Driver.prototype.setCookie = function(args) {
    // need intelligent defaults?
    return this.Network.setCookie(args);
};

Driver.prototype.setContent = function(html) {
    const self = this;
    return this.Page.navigate({url: 'about:blank'}).then((result) => {
        self.Page.setDocumentContent({frameId: result.frameId, html: html});
    });
};

// TODO move this out to a utils module
Driver.prototype.delay = function(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(function() { resolve(true); }, ms);
    });
};

Driver.prototype.spinBrowserEventLoop = function() {
    const self = this;
    return self.evaluateAsync({
        functionDeclaration: 'setTimeout(function() { resolve(true); }, 0);'
    });
};

// private version of evaluate
Driver.prototype._evaluate = function(options) {
    const self = this;
    const objectId = options.objectId;
    const args = options.args || [];
    const script = options.functionDeclaration;

    for (let i = 0; i < args.length; i++) {
        args[i] = {value: args[i]}
    }

    return self.Runtime.callFunctionOn(
        {
            functionDeclaration: script,
            arguments: args,
            objectId: objectId,
            returnByValue: false,
            awaitPromise: true}).then((result) => {
                if ( result.exceptionDetails ) {
                    return Promise.reject(new Error(JSON.stringify(result.exceptionDetails)));
                }
                const multiType = result.result.type + ':' + result.result.subtype;
                return resolveEvaluateResult(multiType, self, result.result);
            });
};

Driver.prototype.evaluate = function(options) {
    const self = this;
    var scriptTimeout = Number.parseInt(options.timeout || self.timeouts.script);
    var str = options.functionDeclaration;
    if (typeof str !== 'function') {
        str = `function() {
            ${str}
        }`
    }
    str = str.toString().trim();

    options.functionDeclaration = `function() { const args = arguments; const self = this; return new Promise((resolve,reject) => {
        try {
            setTimeout(function() { reject(new Error('Chrominator Script Timeout')); }, ${scriptTimeout});
            resolve(function() {
                return ${str}
            }().apply(self, args));
        } catch(err) {
            reject(err);
        }
    }); }`

    return this.DOM.getDocument().then((result) => {
        return self.DOM.resolveNode({nodeId: result.root.nodeId});
    }).then((result) => {
        options.objectId = result.object.objectId;
        return self._evaluate(options);
    });
};

Driver.prototype.evaluateAsync = function(options) {
    const self = this;
    var scriptTimeout = Number.parseInt(options.timeout || self.timeouts.script);
    var str = options.functionDeclaration;
    if (typeof str !== 'function') {
        str = `function() {
            ${str}
        }`
    }
    str = str.toString().trim();

    options.functionDeclaration = `function() { const args = arguments; const self = this; return new Promise((resolve,reject) => {
        try {
            setTimeout(function() { reject(new Error('Chrominator Script Timeout')); }, ${scriptTimeout});
            (function() {
                return ${str}
            }().apply(self, args));

        } catch(err) {
            reject(err);
        }
    }); }`

    return this.DOM.getDocument().then((result) => {
        return self.DOM.resolveNode({nodeId: result.root.nodeId});
    }).then((result) => {
        options.objectId = result.object.objectId;
        return self._evaluate(options);
    });
};

module.exports = Driver;
<commit_msg>add page load strategies<commit_after>'use strict';

const fs = require('fs');
const Node = require('./node');
var resolveEvaluateResult = require('./remote_object');

const readyStates = {
    loading: 0,
    interactive: 1,
    complete: 2,
}

var Driver = function(crd) {
    this.crd = crd;
    this.Page = this.crd.Page;
    this.DOM = this.crd.DOM;
    this.Network = this.crd.Network;
    this.Runtime = this.crd.Runtime;

    this.timeouts = {
        script: 30000, // ms
        pageLoad: 300000, // ms
    };
};

Driver.prototype.init = function() {
    return Promise.all([
        this.Page.enable(),
        this.DOM.enable(),
        this.Runtime.enable(),
        this.Network.enable()
    ]);
};

Driver.createDriver = function(crd) {
    const driver = new Driver(crd);
    return driver.init().then(() => { return driver });
};

Driver.prototype.navigate = function(args) {
    const self = this;
    const pageLoadStrategy = readyStates[args.pageLoadStrategy || 'complete'];

    return new Promise((resolve, reject) => {
        self.crd.once('Page.loadEventFired', function() {
            if (typeof pageLoadStrategy === 'undefined') {
                resolve('done');
                return;
            }
            self.evaluateAsync({
                functionDeclaration: function(readyState) {
                    const readyStates = {
                        loading: 0,
                        interactive: 1,
                        complete: 2,
                    }
                    if (readyStates[document.readyState] >= readyState) { resolve(); }

                    document.onreadystatechange = function() {
                        if (readyStates[document.readyState] >= readyState) { resolve(); }
                    };
                    if (readyStates[document.readyState] >= readyState) { resolve(); }
                },
                args: [pageLoadStrategy],
                timeout: self.timeouts.pageLoad || args.timeout }).then((result) => {

                    resolve('done');
                });
        });
        self.Page.navigate(args).catch((err) => { reject(err) });
    });
};

Driver.prototype.getDocument = function() {
    return this.DOM.getDocument();
};

Driver.prototype.querySelector = function(args) {
    const self = this;
    return this.DOM.getDocument().then((node) => {
        args['nodeId'] = node.root.nodeId;
        return this.DOM.querySelector(args).then((result) => {
            return new Node(self, result.nodeId);
        });
    });
};

Driver.prototype.querySelectorAll = function(args) {
    const self = this;
    return this.DOM.getDocument().then((node) => {
        args['nodeId'] = node.root.nodeId;
        return this.DOM.querySelectorAll(args).then((result) => {
            const nodeIds = result.nodeIds;
            const data = [];

            for (var nodeId in nodeIds) {
                data.push(new Node(self, nodeId));
            }

            return data
        });
    });
};

Driver.prototype.reload = function() {
    const self = this;
    return new Promise((resolve, reject) => {
        self.crd.once('Page.loadEventFired', function() {
            resolve('done');
        });
        self.Page.reload({ignoreCache: true}).catch((err) => { reject(err) });
    });
};

Driver.prototype.pdf = function(path, options) {
    return this.Page.printToPdf(options).then((result) => {
        const data = Buffer.from(result.data, 'base64')
        return new Promise((resolve, reject) => {
            fs.writeFile(path, data, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(path);
                }
            });
        });
    });
};

Driver.prototype.screenshot = function(path, options) {
    // TODO file ext needs validation
    return this.Page.captureScreenshot(options).then((result) => {
        const data = Buffer.from(result.data, 'base64')
        return new Promise((resolve, reject) => {
            fs.writeFile(path, data, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(path);
                }
            });
        });
    });
};

Driver.prototype.setUserAgent = function(args) {
    return this.Network.setUserAgentOverride(args);
};

Driver.prototype.getCookies = function(args) {
    // handle no args .... should default to current url
    return this.Network.getCookies(args);
};

Driver.prototype.getAllCookies = function() {
    return this.Network.getAllCookies();
};

Driver.prototype.deleteAllCookies = function() {
    const self = this;
    return this.Network.canClearBrowserCookies().then((result) => {
        if ( result.result ) {
            return self.Network.clearBrowserCookies();
        } else {
            return Promise.reject(new Error('unable to clear browser cookies'))
        }
    });
};

Driver.prototype.setCookie = function(args) {
    // need intelligent defaults?
    return this.Network.setCookie(args);
};

Driver.prototype.setContent = function(html) {
    const self = this;
    return this.Page.navigate({url: 'about:blank'}).then((result) => {
        self.Page.setDocumentContent({frameId: result.frameId, html: html});
    });
};

// TODO move this out to a utils module
Driver.prototype.delay = function(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(function() { resolve(true); }, ms);
    });
};

Driver.prototype.spinBrowserEventLoop = function() {
    const self = this;
    return self.evaluateAsync({
        functionDeclaration: 'setTimeout(function() { resolve(true); }, 0);'
    });
};

// private version of evaluate
Driver.prototype._evaluate = function(options) {
    const self = this;
    const objectId = options.objectId;
    const args = options.args || [];
    const script = options.functionDeclaration;

    for (let i = 0; i < args.length; i++) {
        args[i] = {value: args[i]}
    }

    return self.Runtime.callFunctionOn(
        {
            functionDeclaration: script,
            arguments: args,
            objectId: objectId,
            returnByValue: false,
            awaitPromise: true}).then((result) => {
                if ( result.exceptionDetails ) {
                    return Promise.reject(new Error(JSON.stringify(result.exceptionDetails)));
                }
                const multiType = result.result.type + ':' + result.result.subtype;
                return resolveEvaluateResult(multiType, self, result.result);
            });
};

Driver.prototype.evaluate = function(options) {
    const self = this;
    var scriptTimeout = Number.parseInt(options.timeout || self.timeouts.script);
    var str = options.functionDeclaration;
    if (typeof str !== 'function') {
        str = `function() {
            ${str}
        }`
    }
    str = str.toString().trim();

    options.functionDeclaration = `function() { const args = arguments; const self = this; return new Promise((resolve,reject) => {
        try {
            setTimeout(function() { reject(new Error('Chrominator Script Timeout')); }, ${scriptTimeout});
            resolve(function() {
                return ${str}
            }().apply(self, args));
        } catch(err) {
            reject(err);
        }
    }); }`

    return this.DOM.getDocument().then((result) => {
        return self.DOM.resolveNode({nodeId: result.root.nodeId});
    }).then((result) => {
        options.objectId = result.object.objectId;
        return self._evaluate(options);
    });
};

Driver.prototype.evaluateAsync = function(options) {
    const self = this;
    var scriptTimeout = Number.parseInt(options.timeout || self.timeouts.script);
    var str = options.functionDeclaration;
    if (typeof str !== 'function') {
        str = `function() {
            ${str}
        }`
    }
    str = str.toString().trim();

    options.functionDeclaration = `function() { const args = arguments; const self = this; return new Promise((resolve,reject) => {
        try {
            setTimeout(function() { reject(new Error('Chrominator Script Timeout')); }, ${scriptTimeout});
            (function() {
                return ${str}
            }().apply(self, args));

        } catch(err) {
            reject(err);
        }
    }); }`

    return this.DOM.getDocument().then((result) => {
        return self.DOM.resolveNode({nodeId: result.root.nodeId});
    }).then((result) => {
        options.objectId = result.object.objectId;
        return self._evaluate(options);
    });
};

module.exports = Driver;
<|endoftext|>


<commit_before>var allowUnsafeNewFunction = require('loophole').allowUnsafeNewFunction
var pkgConfig = require('pkg-config')
var dirname = require('path').dirname
var styleSettings = require('./style-settings')

function noStyle () {
  return { cmd: 'no-style' }
}

function requireWithLocalOverride (moduleName, dir) {
  try {
    return module.constructor._load(moduleName, {
      paths: module.constructor._nodeModulePaths(dir)
    })
  } catch (err) {
    return require(moduleName)
  }
}

var pickStandard = function (style, filePath) {
  var dir = dirname(filePath)
  return allowUnsafeNewFunction(function () {
    return requireWithLocalOverride(style, dir)
  })
}

function getStyleThroughDevDeps (filePath, style) {
  // Get the dependencies from the nearest package.json
  function pkgOpts (root) { return { cwd: filePath, root: root, cache: false } }
  var devDeps = pkgConfig(null, pkgOpts('devDependencies')) || {}
  var prodDeps = pkgConfig(null, pkgOpts('dependencies')) || {}

  var options = styleSettings.styleOptions

  // Include style if not one of known linters
  if (options.indexOf(style) === -1) options.push(style)

  // If one of the known linters is found as a dependency, use it
  var useLinter = options.filter(function (linter) {
    return devDeps[linter] || prodDeps[linter]
  })[0]

  return useLinter ? pickStandard(useLinter, filePath) : noStyle()
}

module.exports = function selectStyle (filePath, options) {
  // See if it should get style from the package.json
  if (options.checkStyleDevDependencies) {
    return getStyleThroughDevDeps(filePath, options.style)
  }

  // Fallback to style value to decide which style we should use
  var shouldStyle = options.style && options.style !== 'no-style'
  return shouldStyle ? pickStandard(options.style, filePath) : noStyle()
}
<commit_msg>fix no-style<commit_after>var allowUnsafeNewFunction = require('loophole').allowUnsafeNewFunction
var pkgConfig = require('pkg-config')
var dirname = require('path').dirname
var styleSettings = require('./style-settings')

function noStyle () {
  return { cmd: 'no-style' }
}

function requireWithLocalOverride (moduleName, dir) {
  try {
    return module.constructor._load(moduleName, {
      paths: module.constructor._nodeModulePaths(dir)
    })
  } catch (err) {
    return require(moduleName)
  }
}

var pickStandard = function (style, filePath) {
  var dir = dirname(filePath)
  return allowUnsafeNewFunction(function () {
    return requireWithLocalOverride(style, dir)
  })
}

function getStyleThroughDevDeps (filePath, style) {
  // Get the dependencies from the nearest package.json
  function pkgOpts (root) { return { cwd: filePath, root: root, cache: false } }
  var devDeps = pkgConfig(null, pkgOpts('devDependencies')) || {}
  var prodDeps = pkgConfig(null, pkgOpts('dependencies')) || {}

  var options = styleSettings.styleOptions

  if (style === 'no-style') {
    return noStyle()
  }

  // Include style if not one of known linters
  if (options.indexOf(style) === -1) options.push(style)

  // If one of the known linters is found as a dependency, use it
  var useLinter = options.filter(function (linter) {
    return devDeps[linter] || prodDeps[linter]
  })[0]

  return useLinter ? pickStandard(useLinter, filePath) : noStyle()
}

module.exports = function selectStyle (filePath, options) {
  // See if it should get style from the package.json
  if (options.checkStyleDevDependencies) {
    return getStyleThroughDevDeps(filePath, options.style)
  }

  // Fallback to style value to decide which style we should use
  var shouldStyle = options.style && options.style !== 'no-style'
  return shouldStyle ? pickStandard(options.style, filePath) : noStyle()
}
<|endoftext|>


<commit_before>function skewer() {
    $.get("/skewer/get", function (str) {
        var request = JSON.parse(str);
        var result = {type: "eval", id: request.id,
                      callback: request.callback, strict: request.strict};
        try {
            var prefix = request.strict ? '"use strict";\n' : "";
            var value = (eval, eval)(prefix + request.eval); // global eval
            result.value = skewer.safeStringify(value, request.verbose);
            result.status = "success";
        } catch (error) {
            result.value = error.toString();
            result.status = "error";
            result.error = {"name": error.name, "stack": error.stack,
                            "type": error.type, "message": error.message,
                            "eval": request.eval};
        }
        $.post("/skewer/post", JSON.stringify(result), skewer);
    }, "text");
}

skewer.safeStringify = function (object, verbose) {
    "use strict";
    var circular = "#<Circular>";
    var seen = [];

    var stringify = function(obj) {
        if (obj === true) {
            return "true";
        } else if (obj === false) {
            return "false";
        } else if (obj === undefined) {
            return "undefined";
        } else if (obj === null) {
            return "null";
        } else if (typeof obj === "number") {
            return obj.toString();
        } else if (obj instanceof Array) {
            if (seen.indexOf(obj) >= 0) {
                return circular;
            } else {
                seen.push(obj);
                return "[" + obj.map(function(e) {
                    return stringify(e);
                }).join(", ") + "]";
            }
        } else if (typeof obj === "string") {
            return JSON.stringify(obj);
        } else if (typeof obj === "function") {
            if (verbose)
                return obj.toString();
            else
                return "Function";
        } else {
            if (verbose) {
                if (seen.indexOf(obj) >= 0)
                    return circular;
                else
                    seen.push(obj);
                var output = "{";
                for (key in obj) {
                    output += JSON.stringify(key) + ":";
                    output += stringify(obj[key]);
                    output += ",";
                }
                return output.slice(0, -1) + "}";
            } else {
                return "Object";
            }
        }
    };

    try {
        return stringify(object);
    } catch (error) {
        return skewer.safeStringify(object, false);
    }
};

skewer.log = function(message) {
    "use strict";
    var log = {type: "log", callback: "skewer-post-log",
               value: skewer.safeStringify(message, true)};
    $.post("/skewer/post", JSON.stringify(log));
};

$("document").ready(skewer);
<commit_msg>Fill in some JsDoc comments.<commit_after>/**
 * @fileOverview Live browser interaction with Emacs
 * @requires jQuery
 * @version 1.0
 */

/**
 * Makes a request to Emacs for something to evaluate. Once done it
 * sends the results back and queues itself for another request.
 * @namespace Holds all of Skewer's functionality.
 */
function skewer() {
    $.get("/skewer/get", function (str) {
        var request = JSON.parse(str);
        var result = {type: "eval", id: request.id,
                      callback: request.callback, strict: request.strict};
        try {
            var prefix = request.strict ? '"use strict";\n' : "";
            var value = (eval, eval)(prefix + request.eval); // global eval
            result.value = skewer.safeStringify(value, request.verbose);
            result.status = "success";
        } catch (error) {
            result.value = error.toString();
            result.status = "error";
            result.error = {"name": error.name, "stack": error.stack,
                            "type": error.type, "message": error.message,
                            "eval": request.eval};
        }
        $.post("/skewer/post", JSON.stringify(result), skewer);
    }, "text");
}

/**
 * Stringify a potentially circular object without throwing an exception.
 * @param object The object to be printed.
 * @param {boolean} verbose Enable more verbose output.
 * @returns {string} The printed object.
 */
skewer.safeStringify = function (object, verbose) {
    "use strict";
    var circular = "#<Circular>";
    var seen = [];

    var stringify = function(obj) {
        if (obj === true) {
            return "true";
        } else if (obj === false) {
            return "false";
        } else if (obj === undefined) {
            return "undefined";
        } else if (obj === null) {
            return "null";
        } else if (typeof obj === "number") {
            return obj.toString();
        } else if (obj instanceof Array) {
            if (seen.indexOf(obj) >= 0) {
                return circular;
            } else {
                seen.push(obj);
                return "[" + obj.map(function(e) {
                    return stringify(e);
                }).join(", ") + "]";
            }
        } else if (typeof obj === "string") {
            return JSON.stringify(obj);
        } else if (typeof obj === "function") {
            if (verbose)
                return obj.toString();
            else
                return "Function";
        } else {
            if (verbose) {
                if (seen.indexOf(obj) >= 0)
                    return circular;
                else
                    seen.push(obj);
                var output = "{";
                for (key in obj) {
                    output += JSON.stringify(key) + ":";
                    output += stringify(obj[key]);
                    output += ",";
                }
                return output.slice(0, -1) + "}";
            } else {
                return "Object";
            }
        }
    };

    try {
        return stringify(object);
    } catch (error) {
        return skewer.safeStringify(object, false);
    }
};

/**
 * Log an object to the Skewer REPL in Emacs (console.log).
 * @param message The object to be logged.
 */
skewer.log = function(message) {
    "use strict";
    var log = {type: "log", callback: "skewer-post-log",
               value: skewer.safeStringify(message, true)};
    $.post("/skewer/post", JSON.stringify(log));
};

$("document").ready(skewer);
<|endoftext|>