<commit_before>/*
 * Axway Appcelerator Titanium Mobile
 * Copyright (c) 2011-2018 by Axway Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
var should = require('./utilities/assertions'),
	utilities = require('./utilities/utilities');

describe('Titanium.Android.NotificationManager', function() {

	it.android('Notifications enabled by default', function() {
		var notificationEnabled = Titanium.Android.NotificationManager.areNotificationsEnabled();
		should(notificationEnabled).be.a.Boolean;
		should(notificationEnabled).eql(true);
	});

});<commit_msg>Lint unit test.<commit_after>/*
 * Axway Appcelerator Titanium Mobile
 * Copyright (c) 2011-2018 by Axway Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
'use strict';
var should = require('./utilities/assertions');

describe('Titanium.Android.NotificationManager', function () {
	it.android('Notifications enabled by default', function () {
		var notificationEnabled = Ti.Android.NotificationManager.areNotificationsEnabled();
		should(notificationEnabled).be.a.Boolean;
		should(notificationEnabled).eql(true);
	});
});
<|endoftext|>


<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 assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('util');
var url = require('url');
var xml2js = require('xml2js');
var azureUtils = require('../../util/util');
var common = require('../common');
var utils = require('../utils');
var constants = require('../constants');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;
var keyFiles = require('../keyFiles');
var cacheUtils = require('../cacheUtils');

exports.init = function (cli) {
  var log = cli.output;
  var azureDirectory = utils.azureDir();
  var pemPath = path.join(azureDirectory, 'managementCertificate.pem');
  var publishSettingsFilePath = path.join(azureDirectory, 'publishSettings.xml');

  var account = cli.category('account')
    .description('Manage your account information and publish settings');

  account.command('download')
    .whiteListPowershell()
    .description('Launch a browser to download your publishsettings file')
    .execute(function (options, callback) {
      try {
        var url = utils.getPublishingProfileUrl();
        common.launchBrowser(url);
        log.help('Save the downloaded file, then execute the command');
        log.help('  account import <file>');
        callback();
      }
      catch (err) {
        callback(err);
      }
    });

  account.command('list')
    .whiteListPowershell()
    .description('Lists the imported subscriptions')
    .execute(function (options, callback) {
      var subscriptions = account.readSubscriptions();
      log.table(subscriptions, function (row, s) {
        row.cell('Name', s.Name);
        row.cell('Id', s.Id);
      });
    });

  account.command('set <subscription>')
    .whiteListPowershell()
    .description('Sets the current subscription')
    .execute(function (subscription, options, callback) {
      var subscriptions = account.readSubscriptions();

      // Try to match based on name first
      var importByName = true;
      var filtered = subscriptions.filter(function (s) { return utils.ignoreCaseEquals(s.Name, subscription) });
      if (!filtered.length) {
        // If nothing was found try matching on Id
        importByName = false;
        filtered = subscriptions.filter(function (s) { return utils.ignoreCaseEquals(s.Id, subscription) });

        if (!filtered.length) {
          // if still nothing found, just throw
          throw new Error('Invalid subscription "' + subscription + '".');
        }
      }

      var subscriptionObject = filtered[0];
      var cfg = account.readConfig();

      var subscriptionTag = importByName ? subscriptionObject.Name : subscriptionObject.Id;
      log.info('Setting subscription to \'' + subscriptionTag + '\'');
      cfg['Subscription'] = subscriptionObject.Id;
      account.writeConfig(cfg);
      log.info('Changes saved.');
    });

  account.command('import <file>')
    .whiteListPowershell()
    .description('Import a publishsettings file or certificate for your account')
    .execute(function (file, options, callback) {
      log.verbose('Importing file ' + file);

      // Is it a .pem file?
      var keyCertValues = keyFiles.readFromFile(file);
      var keyPresent = !!keyCertValues.key;
      var certPresent = !!keyCertValues.cert;
      if (keyPresent + certPresent === 1) {
        // Exactly one of them present.  Tell the user about the error.
        // Do not try this file as xml or pfx
        callback('File ' + file + ' needs to contain both private key and cert, but only ' +
                (keyCertValues.key ? 'key' : 'certificate') + ' was found.');
      } else if (keyCertValues.key && keyCertValues.cert) {
        // Both key and cert are present.
        keyFiles.writeToFile(pemPath, keyCertValues);
        log.verbose('Key and cert have been written to ' + pemPath);
      } else {
        // Try to open as publishsettings or pfx.
        log.silly(file + ' does not appear to be a PEM file. Reading as publish settings file.');
        var parser = new xml2js.Parser();
        var publishSettings = null;
        parser.on('end', function (settings) { publishSettings = settings; });
        var readBuffer = fs.readFileSync(file);
        try {
          parser.parseString(readBuffer);
        } catch (err) {
          if (err.toString().indexOf('Non-whitespace before first tag') === -1) {
            // This looks like an xml parsing error, not PFX.
            callback(err);
          }

          log.silly('Unable to read file as xml publish settings file. Assuming it is pfx');
          publishSettings = null;
        }

        if (publishSettings) {
          processSettings(file, publishSettings);
        } else {
          convertPfx(readBuffer);
        }
      }

      cacheUtils.clear();
      if (publishSettings && publishSettings.PublishProfile.Subscription['@']) {
        return cli.category('site').doSpacesGet({ subscription: publishSettings.PublishProfile.Subscription['@'].Id },
            function(error) {
          if (error) {
            var message = error.Message;
            if (typeof message === 'string' && message.indexOf('The subscription is not authorized for this feature.') >= 0) {
              log.silly('Error getting site locations - ignored: ', error);
              error = undefined;
            }
          }
          callback(error);
        });
      }
      return callback();

      function convertPfx(pfx) {
        var pem = pfx2pem(pfx);
        utils.writeFileSyncMode(pemPath, pem.toString(), 'utf8');
        log.verbose('Converted PFX data to ' + pemPath);
      }

      function processSettings(file, settings) {
        if (!settings.PublishProfile ||
            !settings.PublishProfile['@'] ||
            !settings.PublishProfile['@'].ManagementCertificate) {
          throw new Error('Invalid publishSettings file. Use "azure account download" to download publishing credentials.');
        }

        var attribs = settings.PublishProfile['@'];
        var subs = settings.PublishProfile.Subscription;
        if (typeof subs === 'undefined' || subs === undefined) {
          subs = [];
        } else if (typeof (subs[0]) === 'undefined') {
          subs = [subs];
        }

        if (attribs.Url) {
          var endpointInfo = utils.validateEndpoint(attribs.Url);
          var config = account.readConfig();
          config.endpoint = endpointInfo;
          account.writeConfig(config);
          log.info('Setting service endpoint to:', config.endpoint);
        }

        if (subs.length === 0) {
          log.warning('Importing profile with no subscriptions');
        }
        else {
          for (var index in subs) {
            log.info('Found subscription:', subs[index]['@'].Name);
            log.verbose('  Id:', subs[index]['@'].Id);
          }
        }

        log.verbose('Parsing management certificate');
        var pfx = new Buffer(attribs.ManagementCertificate, 'base64');
        convertPfx(pfx);

        log.verbose('Storing account information at', publishSettingsFilePath);
        utils.writeFileSyncMode(publishSettingsFilePath, readBuffer); // folder already created by convertPfx()
        if (subs.length !== 0) {
          log.info('Setting default subscription to:', subs[0]['@'].Name);
          log.info('Use "azure account set" to change to a different one.')
          var config = account.readConfig();
          config.subscription = subs[0]['@'].Id;
          account.writeConfig(config);
        }
        log.warn('The \'' + file + '\' file contains sensitive information.');
        log.warn('Remember to delete it now that it has been imported.');
        log.info('Account publish settings imported successfully');
      }
    });

  account.command('clear')
    .whiteListPowershell()
    .description('Remove any of the stored account info stored by import or config set')

    .action(function () {
      function deleteIfExists(file, isDir) {
        if (fs.existsSync(file)) {
          log.silly('Removing ' + file);
          (isDir ? fs.rmdirSync : fs.unlinkSync)(file);
          return true;
        } else {
          log.silly(file + ' does not exist');
        }
      }
      var isDeleted = deleteIfExists(pemPath);
      isDeleted = deleteIfExists(publishSettingsFilePath) || isDeleted; // in this order only
      isDeleted = account.clearConfig() || isDeleted;
      isDeleted = cacheUtils.clear() || isDeleted;
      try {
        deleteIfExists(azureDirectory, true);
      } catch (err) {
        log.warn('Couldn\'t remove ' + azureDirectory);
      }
      log.info(isDeleted ? 'Account settings cleared successfully'
          : 'Account settings are already clear');
    });

  var affinityGroup = account.category('affinity-group')
    .description('Commands to manage your Azure affinity groups');

  affinityGroup.command('list')
    .description('List locations available for your account')
    .execute(function (options, callback) {
      listLAG('AffinityGroups', options, callback);
    });

  function listLAG(what, options, callback) {
    var channel = utils.createServiceManagementService(cli.category('account').lookupSubscriptionId(options.subscription),
      cli.category('account'), log);

    var textName = what.replace(/([A-Z])/g, ' $1').toLowerCase();
    var progress = cli.progress('Fetching' + textName);
    utils.doServiceManagementOperation(channel, 'list' + what, function (error, response) {
      progress.end();
      if (!error) {
        if (response.body.length > 0) {
          log.table(response.body, function (row, item) {
            if ('DisplayName' in item) { // for location
              row.cell('Name', item.DisplayName);
            } else {
              row.cell('Name', item.Name);
            }

            if ('Label' in item) {
              row.cell('Label', Buffer(item.Label, 'base64').toString());
            }
            if ('Location' in item) {
              row.cell('Location', item.Location || '');
            }
          });
        } else {
          if (log.format().json) {
            log.json([]);
          } else {
            log.info('No' + textName + ' found');
          }
        }
      }
      callback(error);
    });
  }
  account.listLAG = listLAG;

  var storage = account.category('storage')
    .description('Commands to manage your Azure storage account');

  storage.command('list')
        .description('List storage accounts available for your account')
        .execute(function (options, callback) {
          var channel = utils.createServiceManagementService(cli.category('account').lookupSubscriptionId(options.subscription),
              cli.category('account'), log);

          var progress = cli.progress('Fetching storage accounts');
          utils.doServiceManagementOperation(channel, 'listStorageAccounts', function (error, response) {
            progress.end();
            if (!error) {
              if (response.body.length > 0) {
                log.table(response.body, function (row, item) {
                  row.cell('Name', item.ServiceName);
                  var storageServiceProperties = item.StorageServiceProperties;
                  if ('Label' in storageServiceProperties) {
                    row.cell('Label', Buffer(storageServiceProperties.Label, 'base64').toString());
                  }
                  // This will display affinity group GUID and GeoPrimaryLocation (if present) if Location is not present
                  // Affinity group or location display name is not present in the data
                  row.cell('Location', storageServiceProperties.Location ||
                      (storageServiceProperties.AffinityGroup || '') +
                      (storageServiceProperties.GeoPrimaryRegion ? ' (' + storageServiceProperties.GeoPrimaryRegion + ')' : ''));
                });
              } else {
                if (log.format().json) {
                  log.json([]);
                } else {
                  log.info('No storage accounts found');
                }
              }
            }
            callback(error);
          });
        });

  account.readPublishSettings = function () {
    var publishSettings = {};

    var parser = new xml2js.Parser();
    parser.on('end', function (result) { publishSettings = result; });
    try {
      log.silly('Reading publish settings', publishSettingsFilePath);
      var readBuffer = fs.readFileSync(publishSettingsFilePath);
      parser.parseString(readBuffer);
    } catch (err) {
      // publish settings file is not expected for all scenarios
    }

    return publishSettings;
  };

  account.readSubscriptions = function () {
    if (!fs.existsSync(publishSettingsFilePath)) {
      throw new Error('No publish settings file found. Please use "azure account import" first.');
    }

    var parser = new xml2js.Parser();
    var publishSettings = null;
    parser.on('end', function (settings) { publishSettings = settings; });
    var readBuffer = fs.readFileSync(publishSettingsFilePath);

    try {
      parser.parseString(readBuffer);
    } catch (err) {
      if (err.toString().indexOf('Non-whitespace before first tag') === -1) {
        // This looks like an xml parsing error, not PFX.
        callback(err);
      }

      log.silly('Unable to read file as xml publish settings file.');
      publishSettings = null;
    }

    if (publishSettings) {
      var subs = publishSettings.PublishProfile.Subscription;
      if (typeof subs === 'undefined' || subs === undefined) {
        subs = [];
      } else if (typeof (subs[0]) === 'undefined') {
        subs = [subs];
      }

      if (subs.length === 0) {
        log.warning('No subscriptions.');
      } else {
        var subscriptions = [];
        for (var s in subs) {
          subscriptions[s] = {
            Name: subs[s]['@'].Name,
            Id: subs[s]['@'].Id
          };
        }

        return subscriptions;
      }
    } else {
      throw new Error('Invalid publish settings file.')
    }
  }

  account.defaultSubscriptionId = function () {
    return account.readConfig().subscription;
  };

  account.lookupSubscriptionId = function (subscription) {
    // use default subscription if not passed as an argument
    if (subscription === undefined) {
      subscription = account.readConfig().subscription;
    }

    // load and normalize publish settings
    var publishSettings = account.readPublishSettings();

    if (publishSettings && publishSettings.PublishProfile) {
      var subs = publishSettings.PublishProfile.Subscription;
      if (subs === 'undefined') {
        subs = [];
      } else if (typeof (subs[0]) === 'undefined') {
        subs = [subs];
      }

      // use subscription id when the subscription name matches
      for (var index in subs) {
        if (subs[index]['@'].Name === subscription) {
          return subs[index]['@'].Id;
        }
      }
    }

    return subscription;
  };

  account.managementCertificate = function () {
    var pemFile = path.join(utils.azureDir(), 'managementCertificate.pem');
    log.silly('Reading pem', pemFile);
    return keyFiles.readFromFile(pemFile);
  };

  account.managementEndpointUrl = function () {
    var cfg = account.readConfig();
    return cfg.endpoint;
  };
};

<commit_msg>#287: Fix casing issue.<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 assert = require('assert');
var fs = require('fs');
var path = require('path');
var util = require('util');
var url = require('url');
var xml2js = require('xml2js');
var azureUtils = require('../../util/util');
var common = require('../common');
var utils = require('../utils');
var constants = require('../constants');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;
var keyFiles = require('../keyFiles');
var cacheUtils = require('../cacheUtils');

exports.init = function (cli) {
  var log = cli.output;
  var azureDirectory = utils.azureDir();
  var pemPath = path.join(azureDirectory, 'managementCertificate.pem');
  var publishSettingsFilePath = path.join(azureDirectory, 'publishSettings.xml');

  var account = cli.category('account')
    .description('Manage your account information and publish settings');

  account.command('download')
    .whiteListPowershell()
    .description('Launch a browser to download your publishsettings file')
    .execute(function (options, callback) {
      try {
        var url = utils.getPublishingProfileUrl();
        common.launchBrowser(url);
        log.help('Save the downloaded file, then execute the command');
        log.help('  account import <file>');
        callback();
      }
      catch (err) {
        callback(err);
      }
    });

  account.command('list')
    .whiteListPowershell()
    .description('Lists the imported subscriptions')
    .execute(function (options, callback) {
      var subscriptions = account.readSubscriptions();
      log.table(subscriptions, function (row, s) {
        row.cell('Name', s.Name);
        row.cell('Id', s.Id);
      });
    });

  account.command('set <subscription>')
    .whiteListPowershell()
    .description('Sets the current subscription')
    .execute(function (subscription, options, callback) {
      var subscriptions = account.readSubscriptions();

      // Try to match based on name first
      var importByName = true;
      var filtered = subscriptions.filter(function (s) { return utils.ignoreCaseEquals(s.Name, subscription) });
      if (!filtered.length) {
        // If nothing was found try matching on Id
        importByName = false;
        filtered = subscriptions.filter(function (s) { return utils.ignoreCaseEquals(s.Id, subscription) });

        if (!filtered.length) {
          // if still nothing found, just throw
          throw new Error('Invalid subscription "' + subscription + '".');
        }
      }

      var subscriptionObject = filtered[0];
      var cfg = account.readConfig();

      var subscriptionTag = importByName ? subscriptionObject.Name : subscriptionObject.Id;
      log.info('Setting subscription to \'' + subscriptionTag + '\'');
      cfg.subscription = subscriptionObject.Id;
      account.writeConfig(cfg);
      log.info('Changes saved.');
    });

  account.command('import <file>')
    .whiteListPowershell()
    .description('Import a publishsettings file or certificate for your account')
    .execute(function (file, options, callback) {
      log.verbose('Importing file ' + file);

      // Is it a .pem file?
      var keyCertValues = keyFiles.readFromFile(file);
      var keyPresent = !!keyCertValues.key;
      var certPresent = !!keyCertValues.cert;
      if (keyPresent + certPresent === 1) {
        // Exactly one of them present.  Tell the user about the error.
        // Do not try this file as xml or pfx
        callback('File ' + file + ' needs to contain both private key and cert, but only ' +
                (keyCertValues.key ? 'key' : 'certificate') + ' was found.');
      } else if (keyCertValues.key && keyCertValues.cert) {
        // Both key and cert are present.
        keyFiles.writeToFile(pemPath, keyCertValues);
        log.verbose('Key and cert have been written to ' + pemPath);
      } else {
        // Try to open as publishsettings or pfx.
        log.silly(file + ' does not appear to be a PEM file. Reading as publish settings file.');
        var parser = new xml2js.Parser();
        var publishSettings = null;
        parser.on('end', function (settings) { publishSettings = settings; });
        var readBuffer = fs.readFileSync(file);
        try {
          parser.parseString(readBuffer);
        } catch (err) {
          if (err.toString().indexOf('Non-whitespace before first tag') === -1) {
            // This looks like an xml parsing error, not PFX.
            callback(err);
          }

          log.silly('Unable to read file as xml publish settings file. Assuming it is pfx');
          publishSettings = null;
        }

        if (publishSettings) {
          processSettings(file, publishSettings);
        } else {
          convertPfx(readBuffer);
        }
      }

      cacheUtils.clear();
      if (publishSettings && publishSettings.PublishProfile.Subscription['@']) {
        return cli.category('site').doSpacesGet({ subscription: publishSettings.PublishProfile.Subscription['@'].Id },
            function(error) {
          if (error) {
            var message = error.Message;
            if (typeof message === 'string' && message.indexOf('The subscription is not authorized for this feature.') >= 0) {
              log.silly('Error getting site locations - ignored: ', error);
              error = undefined;
            }
          }
          callback(error);
        });
      }
      return callback();

      function convertPfx(pfx) {
        var pem = pfx2pem(pfx);
        utils.writeFileSyncMode(pemPath, pem.toString(), 'utf8');
        log.verbose('Converted PFX data to ' + pemPath);
      }

      function processSettings(file, settings) {
        if (!settings.PublishProfile ||
            !settings.PublishProfile['@'] ||
            !settings.PublishProfile['@'].ManagementCertificate) {
          throw new Error('Invalid publishSettings file. Use "azure account download" to download publishing credentials.');
        }

        var attribs = settings.PublishProfile['@'];
        var subs = settings.PublishProfile.Subscription;
        if (typeof subs === 'undefined' || subs === undefined) {
          subs = [];
        } else if (typeof (subs[0]) === 'undefined') {
          subs = [subs];
        }

        if (attribs.Url) {
          var endpointInfo = utils.validateEndpoint(attribs.Url);
          var config = account.readConfig();
          config.endpoint = endpointInfo;
          account.writeConfig(config);
          log.info('Setting service endpoint to:', config.endpoint);
        }

        if (subs.length === 0) {
          log.warning('Importing profile with no subscriptions');
        }
        else {
          for (var index in subs) {
            log.info('Found subscription:', subs[index]['@'].Name);
            log.verbose('  Id:', subs[index]['@'].Id);
          }
        }

        log.verbose('Parsing management certificate');
        var pfx = new Buffer(attribs.ManagementCertificate, 'base64');
        convertPfx(pfx);

        log.verbose('Storing account information at', publishSettingsFilePath);
        utils.writeFileSyncMode(publishSettingsFilePath, readBuffer); // folder already created by convertPfx()
        if (subs.length !== 0) {
          log.info('Setting default subscription to:', subs[0]['@'].Name);
          log.info('Use "azure account set" to change to a different one.')
          var config = account.readConfig();
          config.subscription = subs[0]['@'].Id;
          account.writeConfig(config);
        }
        log.warn('The \'' + file + '\' file contains sensitive information.');
        log.warn('Remember to delete it now that it has been imported.');
        log.info('Account publish settings imported successfully');
      }
    });

  account.command('clear')
    .whiteListPowershell()
    .description('Remove any of the stored account info stored by import or config set')

    .action(function () {
      function deleteIfExists(file, isDir) {
        if (fs.existsSync(file)) {
          log.silly('Removing ' + file);
          (isDir ? fs.rmdirSync : fs.unlinkSync)(file);
          return true;
        } else {
          log.silly(file + ' does not exist');
        }
      }
      var isDeleted = deleteIfExists(pemPath);
      isDeleted = deleteIfExists(publishSettingsFilePath) || isDeleted; // in this order only
      isDeleted = account.clearConfig() || isDeleted;
      isDeleted = cacheUtils.clear() || isDeleted;
      try {
        deleteIfExists(azureDirectory, true);
      } catch (err) {
        log.warn('Couldn\'t remove ' + azureDirectory);
      }
      log.info(isDeleted ? 'Account settings cleared successfully'
          : 'Account settings are already clear');
    });

  var affinityGroup = account.category('affinity-group')
    .description('Commands to manage your Azure affinity groups');

  affinityGroup.command('list')
    .description('List locations available for your account')
    .execute(function (options, callback) {
      listLAG('AffinityGroups', options, callback);
    });

  function listLAG(what, options, callback) {
    var channel = utils.createServiceManagementService(cli.category('account').lookupSubscriptionId(options.subscription),
      cli.category('account'), log);

    var textName = what.replace(/([A-Z])/g, ' $1').toLowerCase();
    var progress = cli.progress('Fetching' + textName);
    utils.doServiceManagementOperation(channel, 'list' + what, function (error, response) {
      progress.end();
      if (!error) {
        if (response.body.length > 0) {
          log.table(response.body, function (row, item) {
            if ('DisplayName' in item) { // for location
              row.cell('Name', item.DisplayName);
            } else {
              row.cell('Name', item.Name);
            }

            if ('Label' in item) {
              row.cell('Label', Buffer(item.Label, 'base64').toString());
            }
            if ('Location' in item) {
              row.cell('Location', item.Location || '');
            }
          });
        } else {
          if (log.format().json) {
            log.json([]);
          } else {
            log.info('No' + textName + ' found');
          }
        }
      }
      callback(error);
    });
  }
  account.listLAG = listLAG;

  var storage = account.category('storage')
    .description('Commands to manage your Azure storage account');

  storage.command('list')
        .description('List storage accounts available for your account')
        .execute(function (options, callback) {
          var channel = utils.createServiceManagementService(cli.category('account').lookupSubscriptionId(options.subscription),
              cli.category('account'), log);

          var progress = cli.progress('Fetching storage accounts');
          utils.doServiceManagementOperation(channel, 'listStorageAccounts', function (error, response) {
            progress.end();
            if (!error) {
              if (response.body.length > 0) {
                log.table(response.body, function (row, item) {
                  row.cell('Name', item.ServiceName);
                  var storageServiceProperties = item.StorageServiceProperties;
                  if ('Label' in storageServiceProperties) {
                    row.cell('Label', Buffer(storageServiceProperties.Label, 'base64').toString());
                  }
                  // This will display affinity group GUID and GeoPrimaryLocation (if present) if Location is not present
                  // Affinity group or location display name is not present in the data
                  row.cell('Location', storageServiceProperties.Location ||
                      (storageServiceProperties.AffinityGroup || '') +
                      (storageServiceProperties.GeoPrimaryRegion ? ' (' + storageServiceProperties.GeoPrimaryRegion + ')' : ''));
                });
              } else {
                if (log.format().json) {
                  log.json([]);
                } else {
                  log.info('No storage accounts found');
                }
              }
            }
            callback(error);
          });
        });

  account.readPublishSettings = function () {
    var publishSettings = {};

    var parser = new xml2js.Parser();
    parser.on('end', function (result) { publishSettings = result; });
    try {
      log.silly('Reading publish settings', publishSettingsFilePath);
      var readBuffer = fs.readFileSync(publishSettingsFilePath);
      parser.parseString(readBuffer);
    } catch (err) {
      // publish settings file is not expected for all scenarios
    }

    return publishSettings;
  };

  account.readSubscriptions = function () {
    if (!fs.existsSync(publishSettingsFilePath)) {
      throw new Error('No publish settings file found. Please use "azure account import" first.');
    }

    var parser = new xml2js.Parser();
    var publishSettings = null;
    parser.on('end', function (settings) { publishSettings = settings; });
    var readBuffer = fs.readFileSync(publishSettingsFilePath);

    try {
      parser.parseString(readBuffer);
    } catch (err) {
      if (err.toString().indexOf('Non-whitespace before first tag') === -1) {
        // This looks like an xml parsing error, not PFX.
        callback(err);
      }

      log.silly('Unable to read file as xml publish settings file.');
      publishSettings = null;
    }

    if (publishSettings) {
      var subs = publishSettings.PublishProfile.Subscription;
      if (typeof subs === 'undefined' || subs === undefined) {
        subs = [];
      } else if (typeof (subs[0]) === 'undefined') {
        subs = [subs];
      }

      if (subs.length === 0) {
        log.warning('No subscriptions.');
      } else {
        var subscriptions = [];
        for (var s in subs) {
          subscriptions[s] = {
            Name: subs[s]['@'].Name,
            Id: subs[s]['@'].Id
          };
        }

        return subscriptions;
      }
    } else {
      throw new Error('Invalid publish settings file.')
    }
  }

  account.defaultSubscriptionId = function () {
    return account.readConfig().subscription;
  };

  account.lookupSubscriptionId = function (subscription) {
    // use default subscription if not passed as an argument
    if (subscription === undefined) {
      subscription = account.readConfig().subscription;
    }

    // load and normalize publish settings
    var publishSettings = account.readPublishSettings();

    if (publishSettings && publishSettings.PublishProfile) {
      var subs = publishSettings.PublishProfile.Subscription;
      if (subs === 'undefined') {
        subs = [];
      } else if (typeof (subs[0]) === 'undefined') {
        subs = [subs];
      }

      // use subscription id when the subscription name matches
      for (var index in subs) {
        if (subs[index]['@'].Name === subscription) {
          return subs[index]['@'].Id;
        }
      }
    }

    return subscription;
  };

  account.managementCertificate = function () {
    var pemFile = path.join(utils.azureDir(), 'managementCertificate.pem');
    log.silly('Reading pem', pemFile);
    return keyFiles.readFromFile(pemFile);
  };

  account.managementEndpointUrl = function () {
    var cfg = account.readConfig();
    return cfg.endpoint;
  };
};

<|endoftext|>


<commit_before>/*globals RegExp,define*/
/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved
 *
 * @author brollb / https://github/brollb
 *
 * Visual constraint language for WebGME
 */

define(['plugin/PluginConfig',
        'plugin/PluginBase'], function (PluginConfig,
                                       PluginBase){
   "use strict";

   var DEFAULT = '__default__',
       VIOLATION_VARIABLE_NAME = 'violationInfo',
       ITERATOR_PLACEHOLDER = '%__iterator__',
       ITERATOR_BASE = 'i',
       UNIQUENESS_COEFFICIENT = 10000;

   var ConstraintPlugin = function() {
        //Call base class's constructor
        PluginBase.call(this);

        //Defined in Constriant Language META
        this._variableTypes = { 'dictionary': 'var %name = {};',
                                'Collection': 'var %name = [];',
                                '__default__': 'var %name = null;' };
    };

    //basic functions and setting for plugin inheritance
    ConstraintPlugin.prototype = Object.create(PluginBase.prototype);
    ConstraintPlugin.prototype.constructor = ConstraintPlugin;

    ConstraintPlugin.prototype.getName = function () {
        return "Constraint Creator";
    };

    ConstraintPlugin.prototype._loadStartingNodes = function(callback){
        //we load the children of the active node
        var self = this;
        self._nodeCache = {};

        var load = function(node, fn){
            self.core.loadChildren(node,function(err,children){
                if(err){
                    fn(err);
                } else {
                    var j = children.length,
                        e = null; //error

                    if(j === 0){
                        fn(null);
                    }

                    var callbackIfDone = function(err){
                        e = e || err;
                        if(--j === 0){//callback only on last child
                            fn(e);
                        }
                    };

                    for(var i=0;i<children.length;i++){
                        self._nodeCache[self.core.getPath(children[i])] = children[i];
                        load(children[i], callbackIfDone);
                    }
                }
            });
        };

        load(self.activeNode, callback);

    };

    ConstraintPlugin.prototype.getNode = function(nodePath){
        //we check only our node cache
        return this._nodeCache[nodePath];
    };

    ConstraintPlugin.prototype.getAllNodeIds = function(){
        return Object.keys(this._nodeCache);
    };

    ConstraintPlugin.prototype._isTypeOf = function(node,type){
        //now we make the check based upon path
        if(node === undefined || node === null || type === undefined || type === null){
            return false;
        }

        var self = this;

        if (typeof node === "string"){//if the node is the nodeId
            node = self.getNode(node);
        }

        while(node){
            if(self.core.getPath(node) === self.core.getPath(type)){
                return true;
            }
            node = self.core.getBase(node);
        }
        return false;
    };

    ConstraintPlugin.prototype._createConstraintMapping = function(){
        //Code map:
        //
        //Adding the mapping of node META name to code
        //% sign indicates it will be replaced with either
        //attribute of the given name or ptr tgt of the given name
        //
        //These correspond to META items

        //Check for name collisions
        //Violations_Variable
        VIOLATION_VARIABLE_NAME = this._createUniqueName(VIOLATION_VARIABLE_NAME);

        //iterator base
        ITERATOR_PLACEHOLDER = this._createUniqueName(ITERATOR_PLACEHOLDER);
        ITERATOR_BASE = this._createUniqueName(ITERATOR_BASE);

        this._constraintMapping = {   'bp': 'function(core, currentNode){\n' +
                                                'var ' + VIOLATION_VARIABLE_NAME + ' = { hasViolation: false };' +
                                                '\n\n%code\n' +
                                                'return ' + VIOLATION_VARIABLE_NAME + '\n}',

                                      'map': { 'Add': "%first + %second",
                                               'Subtract': "%first - %second",
                                               'Multiply': "(%first) * (%second)",
                                               'Divide': "(%first)/(%second)",
                                               'Less Than': "(%first) < (%second)",
                                               'Greater Than': "(%first) > (%second)",
                                               'Equals': "(%first) === (%second)",

                                               //Control flow
                                               'If': "if (%cond){\n%true_next\n}",
                                               'ForEach': "for (var " + ITERATOR_PLACEHOLDER +
                                                   " = %collection.length-1; " + ITERATOR_PLACEHOLDER +
                                                   " >= 0; " + ITERATOR_PLACEHOLDER + "--){\n "+
                                                   "\t%iter = %collection[i];\n%true_next\n}",
                                               'While': "while (%cond){\n %true_next\n}",

                                               //Variables
                                               'Variable': "%name",
                                               'Collection': "%name",
                                               'Node': "%name",
                                               'NodeSet': "%name",
                                               'Singleton': "%name",

                                               //Collection mappings
                                               'addToCollection': "%collection.push(%first)",
                                               'contains': "%collection.indexOf(%first) !== -1",

                                               //Constraint specific mappings
                                               'getAttribute': "core.getAttribute(%second, %first)",//FIXME
                                               'getPointer': "this.getNode(core.getPointerPath(%node, %first))",
                                               'getParent': "this.getNode(core.getParentPath(%node))",
                                               'getChildren': "core.getChildrenPaths(%node)",

                                               'markViolation': VIOLATION_VARIABLE_NAME + " = { hasViolation: true," +
                                                   " message: %Message, nodes: %node };\n",

                                               //TODO Figure out how to have the children be children nodes...
                                               'not': "!(%first)",
                                               'getLength': "%first.length",

                                               //A few basic utilities
                                               'Return': "return %first;",
                                               'Set': '%first = %second;' },

                                        'ext': 'js' };

    };

    ConstraintPlugin.prototype._createUniqueName = function(variable){
        var newName = variable;

        while(this.variables[newName]){
            newName = variable + '_' + Math.floor(Math.random()*UNIQUENESS_COEFFICIENT);
        }
        this.variables[newName] = true;//Register the variable name
        return newName;
    };

    ConstraintPlugin.prototype._getNewIterator = function(){
        return this._createUniqueName(ITERATOR_BASE);
    };

    ConstraintPlugin.prototype.main = function (callback) {
        var self = this;
        self.config = self.getCurrentConfig();

        if(!self._isTypeOf(self.activeNode, self.META.Constraint)){
            self._errorMessages(self.activeNode,
                "Current project is an invalid type. Please run the plugin on a constraint definition.");
        }

        self._loadStartingNodes(function(err){
            if(err){
                //finishing
                self.result.success = false;
                callback(err,self.result);
            } else {
                //executing the plugin
                self.logger.info("Finished loading children");
                err = self._runSync();
                if(err){
                    self.result.success = false;
                    callback(err,self.result);
                } else {
                    //Download language files
                    self._saveOutput(self.generatedCode, function(err){
                        if(err){
                            self.result.success = false;
                            callback(err,self.result);
                        } else {
                            if(callback){
                                self.result.success = true;
                                callback(null,self.result);
                            }
                        }
                    });
                }
            }
        });
    };

    ConstraintPlugin.prototype._runSync = function(){
        var err = null,
            currentNode,
            variables = [],//List of variables to declare
            nodeIds,
            l,
            i;

        this.variables = {};//List of declared variables
        this.projectName = this.core.getAttribute(this.activeNode,'name');
        this.generatedCode = "";

        currentNode = null;
        nodeIds = this.getAllNodeIds();
        i = nodeIds.length;

        //Find the hat and declare variables
        while(i-- && currentNode === null){
            if(this._isTypeOf(nodeIds[i], this.META.Hat) && !this._isTypeOf(nodeIds[i], this.META.Command)){
               //Found the starting node
               currentNode = this.getNode(nodeIds[i]);
               //What if they have more than one "start" node?
               //TODO

            } else if(this._isTypeOf(nodeIds[i], this.META.Variable)){
                variables.push(nodeIds[i]);
            }
        }

        //Declare all the variables
        this._declareVariables(variables);
        this._createConstraintMapping();

        //Follow the next pointers and map each object to it's given code
        while(this.core.getPointerPath(currentNode, 'next')){
            currentNode = this.getNode(this.core.getPointerPath(currentNode, 'next'));
            this.generatedCode += this._generateCode(currentNode) + "\n";
        }

        this.generatedCode = this._constraintMapping.bp.replace("%code", this.generatedCode);

        return err;
    };

    ConstraintPlugin.prototype._declareVariables = function(variables){
        var types = Object.keys(this._variableTypes),
            foundType,
            variableType,
            variable,
            j;

        for (var i = variables.length -1; i >= 0; i--){
            variable = this.getNode(variables[i]);
            variableType = null;
            j = types.length;

            while (j-- && !variableType){
                if (this._isTypeOf(variable, this.META[types[j]])){
                    variableType = this._variableTypes[types[j]];
                }
            }

            if (!variableType){
                variableType = this._variableTypes[DEFAULT];
            }

            this._declareVar(variable, variableType);
        }

        this.generatedCode += "\n";
    };

    ConstraintPlugin.prototype._declareVar = function(variable, typeInfo){
        var varName = this.core.getAttribute(variable, 'name');
        if (!this.variables[varName]){
            this.generatedCode += typeInfo.replace(new RegExp("%name", "g"), varName) + '\n';
            this.variables[varName] = true;
        }
    };

    ConstraintPlugin.prototype._generateCode = function(node){
        //Map stuff to code and return the code snippet
        var base = this.core.getBase(node),
            typeName = this.core.getAttribute(base, 'name'),
            snippet = this._constraintMapping.map[typeName],//Get the code for the given node...
            ptrs = this.core.getPointerNames(node),
            attributes = this.core.getAttributeNames(node),
            snippetTagContent = {},
            snippetTag,
            keys,
            i,
            n;

        //If the attribute name is in the snippet, substitute the attr name with the value
        i = attributes.length;
        while (i--){
            snippetTag = '%' + attributes[i];
            if (snippet.indexOf(snippetTag) !== -1){
                snippetTagContent[snippetTag] = 'undefined';
                snippetTagContent[snippetTag] = this.core.getAttribute(node, attributes[i]);

                if (attributes[i] !== 'name' && this.core.getAttributeMeta(node, attributes[i]).type === 'string'){
                    snippetTagContent[snippetTag] = '"' + snippetTagContent[snippetTag] + '"';
                }
            }
        }

        //If ptr name is present in the snippet, swap it out with the code from the tgt
        //ptrs have precedence over attributes
        i = ptrs.length;
        while(i--){
            snippetTag = '%' + ptrs[i];
            if (snippet.indexOf(snippetTag) !== -1){

                if(this.core.getPointerPath(node, ptrs[i])){
                    snippetTagContent[snippetTag] = this._getBlockCode(this.core.getPointerPath(node, ptrs[i]));
                }
                if (!snippetTagContent[snippetTag]){
                    snippetTagContent[snippetTag] = 'undefined';
                }
            }
        }

        //Handle any iterators
        if (snippet.indexOf(ITERATOR_PLACEHOLDER) !== -1){
            snippetTagContent[ITERATOR_PLACEHOLDER] = this._getNewIterator();
        }

        keys = Object.keys(snippetTagContent);
        for (i = keys.length-1; i >= 0; i--){
            snippetTag = keys[i];
            snippet = snippet.replace(new RegExp(snippetTag, "g"), snippetTagContent[snippetTag]);
            delete snippetTagContent[snippetTag];
        }

        return snippet;
    };

    ConstraintPlugin.prototype._getBlockCode = function(nodeId){
        //Return code that is part of another block

        if(this._isTypeOf(nodeId, this.META.Predicate)){
            //Return the snippet inline
            return this._generateCode(this.getNode(nodeId));

        }

        if(this._isTypeOf(nodeId, this.META.Command)){//Return the snippet with an indent
            var node = this.getNode(nodeId),
                snippet = "\t" + this._generateCode(node).replace(/\n/g, "\n\t");

            while(this.core.getPointerPath(node, 'next') && this._isTypeOf(this.core.getPointerPath(node, 'next'), this.META.Command)){
                node = this.getNode(this.core.getPointerPath(node, 'next'));
                snippet += "\n\t" + this._generateCode(node).replace(/\n/g, "\n\t");
            }

            return snippet;
        }
    };

    //Thanks to Tamas for the next two functions
    ConstraintPlugin.prototype._saveOutput = function(code, callback){
        var self = this,
            fileName = self.projectName.replace(/ /g, "_"),
            artifact = self.blobClient.createArtifact(fileName+"_code"),

            //Function to check if we have added all files
            checkIfShouldSaveAll = function(err){
                if(err){
                    callback(err);
                } else {
                    self.blobClient.saveAllArtifacts(function(err, hashes) {
                        if (err) {
                            callback(err);
                        } else {
                            self.logger.info('Artifacts are saved here:');
                            self.logger.info(hashes);

                            // result add hashes
                            for (var j = 0; j < hashes.length; j += 1) {
                                self.result.addArtifact(hashes[j]);
                            }

                            self.result.setSuccess(true);
                            callback(null);
                        }
                    });
                }
            };

        //Save all files
        artifact.addFile(fileName + "." + self._constraintMapping.ext,code,checkIfShouldSaveAll);
    };

    ConstraintPlugin.prototype._errorMessages = function(message){
        var self = this;
        self.createMessage(self.activeNode,message);
    };

    return ConstraintPlugin;

});
<commit_msg>Added support for using node/nodeId interchangeably<commit_after>/*globals RegExp,define*/
/*
 * Copyright (C) 2013 Vanderbilt University, All rights reserved
 *
 * @author brollb / https://github/brollb
 *
 * Visual constraint language for WebGME
 */

define(['plugin/PluginConfig',
        'plugin/PluginBase'], function (PluginConfig,
                                       PluginBase){
   "use strict";

   var DEFAULT = '__default__',
       VIOLATION_VARIABLE_NAME = 'violationInfo',
       ITERATOR_PLACEHOLDER = '%__iterator__',
       ITERATOR_BASE = 'i',
       UNIQUENESS_COEFFICIENT = 10000;

   var ConstraintPlugin = function() {
        //Call base class's constructor
        PluginBase.call(this);

        //Defined in Constriant Language META
        this._variableTypes = { 'dictionary': 'var %name = {};',
                                'Collection': 'var %name = [];',
                                '__default__': 'var %name = null;' };
    };

    //basic functions and setting for plugin inheritance
    ConstraintPlugin.prototype = Object.create(PluginBase.prototype);
    ConstraintPlugin.prototype.constructor = ConstraintPlugin;

    ConstraintPlugin.prototype.getName = function () {
        return "Constraint Creator";
    };

    ConstraintPlugin.prototype._loadStartingNodes = function(callback){
        //we load the children of the active node
        var self = this;
        self._nodeCache = {};

        var load = function(node, fn){
            self.core.loadChildren(node,function(err,children){
                if(err){
                    fn(err);
                } else {
                    var j = children.length,
                        e = null; //error

                    if(j === 0){
                        fn(null);
                    }

                    var callbackIfDone = function(err){
                        e = e || err;
                        if(--j === 0){//callback only on last child
                            fn(e);
                        }
                    };

                    for(var i=0;i<children.length;i++){
                        self._nodeCache[self.core.getPath(children[i])] = children[i];
                        load(children[i], callbackIfDone);
                    }
                }
            });
        };

        load(self.activeNode, callback);

    };

    ConstraintPlugin.prototype.getNode = function(nodePath){
        //we check only our node cache
        return this._nodeCache[nodePath];
    };

    ConstraintPlugin.prototype.getAllNodeIds = function(){
        return Object.keys(this._nodeCache);
    };

    ConstraintPlugin.prototype._isTypeOf = function(node,type){
        //now we make the check based upon path
        if(node === undefined || node === null || type === undefined || type === null){
            return false;
        }

        var self = this;

        if (typeof node === "string"){//if the node is the nodeId
            node = self.getNode(node);
        }

        while(node){
            if(self.core.getPath(node) === self.core.getPath(type)){
                return true;
            }
            node = self.core.getBase(node);
        }
        return false;
    };

    ConstraintPlugin.prototype._createConstraintMapping = function(){
        //Code map:
        //
        //Adding the mapping of node META name to code
        //% sign indicates it will be replaced with either
        //attribute of the given name or ptr tgt of the given name
        //
        //These correspond to META items

        //Check for name collisions
        //Violations_Variable
        VIOLATION_VARIABLE_NAME = this._createUniqueName(VIOLATION_VARIABLE_NAME);

        //iterator base
        ITERATOR_PLACEHOLDER = this._createUniqueName(ITERATOR_PLACEHOLDER);
        ITERATOR_BASE = this._createUniqueName(ITERATOR_BASE);

        this._constraintMapping = {   'bp': 'function(core, currentNode){\n\n' +
                                                'var ' + VIOLATION_VARIABLE_NAME + ' = { hasViolation: false };' +
                                                '\n\n%code\n' +
                                                'return ' + VIOLATION_VARIABLE_NAME + '\n}',

                                      'map': { 'Add': "%first + %second",
                                               'Subtract': "%first - %second",
                                               'Multiply': "(%first) * (%second)",
                                               'Divide': "(%first)/(%second)",
                                               'Less Than': "(%first) < (%second)",
                                               'Greater Than': "(%first) > (%second)",
                                               'Equals': "(%first) === (%second)",

                                               //Control flow
                                               'If': "if (%cond){\n%true_next\n}",
                                               'ForEach': "for (var " + ITERATOR_PLACEHOLDER +
                                                   " = %collection.length-1; " + ITERATOR_PLACEHOLDER +
                                                   " >= 0; " + ITERATOR_PLACEHOLDER + "--){\n "+
                                                   "\t%iter = %collection[i];\n%true_next\n}",
                                               'While': "while (%cond){\n %true_next\n}",

                                               //Variables
                                               'Variable': "%name",
                                               'Collection': "%name",
                                               'Node': "%name",
                                               'NodeSet': "%name",
                                               'Singleton': "%name",

                                               //Collection mappings
                                               'addToCollection': "%collection.push(%first)",
                                               'contains': "%collection.indexOf(%first) !== -1",

                                               //Constraint specific mappings
                                               //node specific mappings
                                               'getAttribute': "core.getAttribute(getNode(%second), %first)",//FIXME
                                               'getPointer': "core.getPointerPath(getNode(%node), %first)",
                                               'getParent': "core.getParentPath(getNode(%node))",
                                               'getChildren': "core.getChildrenPaths(getNode(%node))",

                                               'markViolation': VIOLATION_VARIABLE_NAME + " = { hasViolation: true," +
                                                   " message: %Message, nodes: %node };\n",

                                               //TODO Figure out how to have the children be children nodes...
                                               'not': "!(%first)",
                                               'getLength': "%first.length",

                                               //A few basic utilities
                                               'Return': "return %first;",
                                               'Set': '%first = %second;' },

                                        'ext': 'js' };

    };

    ConstraintPlugin.prototype._createUniqueName = function(variable){
        var newName = variable;

        while(this.variables[newName]){
            newName = variable + '_' + Math.floor(Math.random()*UNIQUENESS_COEFFICIENT);
        }
        this.variables[newName] = true;//Register the variable name
        return newName;
    };

    ConstraintPlugin.prototype._getNewIterator = function(){
        return this._createUniqueName(ITERATOR_BASE);
    };

    ConstraintPlugin.prototype.main = function (callback) {
        var self = this;
        self.config = self.getCurrentConfig();

        if(!self._isTypeOf(self.activeNode, self.META.Constraint)){
            self._errorMessages(self.activeNode,
                "Current project is an invalid type. Please run the plugin on a constraint definition.");
        }

        self._loadStartingNodes(function(err){
            if(err){
                //finishing
                self.result.success = false;
                callback(err,self.result);
            } else {
                //executing the plugin
                self.logger.info("Finished loading children");
                err = self._runSync();
                if(err){
                    self.result.success = false;
                    callback(err,self.result);
                } else {
                    //Download language files
                    self._saveOutput(self.generatedCode, function(err){
                        if(err){
                            self.result.success = false;
                            callback(err,self.result);
                        } else {
                            if(callback){
                                self.result.success = true;
                                callback(null,self.result);
                            }
                        }
                    });
                }
            }
        });
    };

    ConstraintPlugin.prototype._runSync = function(){
        var err = null,
            currentNode,
            variables = [],//List of variables to declare
            nodeIds,
            l,
            i;

        this.variables = {};//List of declared variables
        this.projectName = this.core.getAttribute(this.activeNode,'name');
        this.generatedCode = "";

        currentNode = null;
        nodeIds = this.getAllNodeIds();
        i = nodeIds.length;

        //Find the hat and declare variables
        while(i-- && currentNode === null){
            if(this._isTypeOf(nodeIds[i], this.META.Hat) && !this._isTypeOf(nodeIds[i], this.META.Command)){
               //Found the starting node
               currentNode = this.getNode(nodeIds[i]);
               //What if they have more than one "start" node?
               //TODO

            } else if(this._isTypeOf(nodeIds[i], this.META.Variable)){
                variables.push(nodeIds[i]);
            }
        }

        //Declare all the variables
        this._declareVariables(variables);
        this._createConstraintMapping();

        //Follow the next pointers and map each object to it's given code
        while(this.core.getPointerPath(currentNode, 'next')){
            currentNode = this.getNode(this.core.getPointerPath(currentNode, 'next'));
            this.generatedCode += this._generateCode(currentNode) + "\n";
        }

        this.generatedCode = this._constraintMapping.bp.replace("%code", this.generatedCode);

        return err;
    };

    ConstraintPlugin.prototype._declareVariables = function(variables){
        var types = Object.keys(this._variableTypes),
            foundType,
            variableType,
            variable,
            j;

        for (var i = variables.length -1; i >= 0; i--){
            variable = this.getNode(variables[i]);
            variableType = null;
            j = types.length;

            while (j-- && !variableType){
                if (this._isTypeOf(variable, this.META[types[j]])){
                    variableType = this._variableTypes[types[j]];
                }
            }

            if (!variableType){
                variableType = this._variableTypes[DEFAULT];
            }

            this._declareVar(variable, variableType);
        }

        this.generatedCode += "\n";
    };

    ConstraintPlugin.prototype._declareVar = function(variable, typeInfo){
        var varName = this.core.getAttribute(variable, 'name');
        if (!this.variables[varName]){
            this.generatedCode += typeInfo.replace(new RegExp("%name", "g"), varName) + '\n';
            this.variables[varName] = true;
        }
    };

    ConstraintPlugin.prototype._generateCode = function(node){
        //Map stuff to code and return the code snippet
        var base = this.core.getBase(node),
            typeName = this.core.getAttribute(base, 'name'),
            snippet = this._constraintMapping.map[typeName],//Get the code for the given node...
            ptrs = this.core.getPointerNames(node),
            attributes = this.core.getAttributeNames(node),
            snippetTagContent = {},
            snippetTag,
            keys,
            i,
            n;

        //If the attribute name is in the snippet, substitute the attr name with the value
        i = attributes.length;
        while (i--){
            snippetTag = '%' + attributes[i];
            if (snippet.indexOf(snippetTag) !== -1){
                snippetTagContent[snippetTag] = 'undefined';
                snippetTagContent[snippetTag] = this.core.getAttribute(node, attributes[i]);

                if (attributes[i] !== 'name' && this.core.getAttributeMeta(node, attributes[i]).type === 'string'){
                    snippetTagContent[snippetTag] = '"' + snippetTagContent[snippetTag] + '"';
                }
            }
        }

        //If ptr name is present in the snippet, swap it out with the code from the tgt
        //ptrs have precedence over attributes
        i = ptrs.length;
        while(i--){
            snippetTag = '%' + ptrs[i];
            if (snippet.indexOf(snippetTag) !== -1){

                if(this.core.getPointerPath(node, ptrs[i])){
                    snippetTagContent[snippetTag] = this._getBlockCode(this.core.getPointerPath(node, ptrs[i]));
                }
                if (!snippetTagContent[snippetTag]){
                    snippetTagContent[snippetTag] = 'undefined';
                }
            }
        }

        //Handle any iterators
        if (snippet.indexOf(ITERATOR_PLACEHOLDER) !== -1){
            snippetTagContent[ITERATOR_PLACEHOLDER] = this._getNewIterator();
        }

        keys = Object.keys(snippetTagContent);
        for (i = keys.length-1; i >= 0; i--){
            snippetTag = keys[i];
            snippet = snippet.replace(new RegExp(snippetTag, "g"), snippetTagContent[snippetTag]);
            delete snippetTagContent[snippetTag];
        }

        return snippet;
    };

    ConstraintPlugin.prototype._getBlockCode = function(nodeId){
        //Return code that is part of another block

        if(this._isTypeOf(nodeId, this.META.Predicate)){
            //Return the snippet inline
            return this._generateCode(this.getNode(nodeId));

        }

        if(this._isTypeOf(nodeId, this.META.Command)){//Return the snippet with an indent
            var node = this.getNode(nodeId),
                snippet = "\t" + this._generateCode(node).replace(/\n/g, "\n\t");

            while(this.core.getPointerPath(node, 'next') && this._isTypeOf(this.core.getPointerPath(node, 'next'), this.META.Command)){
                node = this.getNode(this.core.getPointerPath(node, 'next'));
                snippet += "\n\t" + this._generateCode(node).replace(/\n/g, "\n\t");
            }

            return snippet;
        }
    };

    //Thanks to Tamas for the next two functions
    ConstraintPlugin.prototype._saveOutput = function(code, callback){
        var self = this,
            fileName = self.projectName.replace(/ /g, "_"),
            artifact = self.blobClient.createArtifact(fileName+"_code"),

            //Function to check if we have added all files
            checkIfShouldSaveAll = function(err){
                if(err){
                    callback(err);
                } else {
                    self.blobClient.saveAllArtifacts(function(err, hashes) {
                        if (err) {
                            callback(err);
                        } else {
                            self.logger.info('Artifacts are saved here:');
                            self.logger.info(hashes);

                            // result add hashes
                            for (var j = 0; j < hashes.length; j += 1) {
                                self.result.addArtifact(hashes[j]);
                            }

                            self.result.setSuccess(true);
                            callback(null);
                        }
                    });
                }
            };

        //Save all files
        artifact.addFile(fileName + "." + self._constraintMapping.ext,code,checkIfShouldSaveAll);
    };

    ConstraintPlugin.prototype._errorMessages = function(message){
        var self = this;
        self.createMessage(self.activeNode,message);
    };

    return ConstraintPlugin;

});
<|endoftext|>


<commit_before>// AJAX Plugin
// Docs Here:
// http://jquery.com/docs/ajax/

if ( typeof XMLHttpRequest == 'undefined' && typeof window.ActiveXObject == 'function') {
	XMLHttpRequest = function() {
		return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') >= 0) ?
			"Microsoft.XMLHTTP" : "Msxml2.XMLHTTP");
	};
}

// Counter for holding the active query's
$.xmlActive=0;

$.xml = function( type, url, data, ret ) {
	var xml = new XMLHttpRequest();

	if ( xml ) {
		// Open the socket
		xml.open(type || "GET", url, true);
		if ( data )
			xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		// Set header so calling script knows that it's an XMLHttpRequest
		xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

		/* Force "Connection: close" for Mozilla browsers to work around
		 * a bug where XMLHttpReqeuest sends an incorrect Content-length
		 * header. See Mozilla Bugzilla #246651.
		 */
		if ( xml.overrideMimeType )
			xml.setRequestHeader('Connection', 'close');

		xml.onreadystatechange = function() {
			// Socket is openend
			if ( xml.readyState == 1 ) {
				// Increase counter
				$.xmlActive++;

				// Show loader if needed
				if ( ($.xmlActive >= 1) && ($.xmlCreate) )
					$.xmlCreate();
			}

			// Socket is closed and data is available
			if ( xml.readyState == 4 ) {
				// Decrease counter
				$.xmlActive--;

				// Hide loader if needed
				if ( ($.xmlActive <= 0) && ($.xmlDestroy) ) {
					$.xmlDestroy();
					$.xmlActive = 0
				}

				// Process result
				if ( ret )
					ret(xml);
			}
		};

		xml.send(data)
	}
};

$.httpData = function(r,type) {
	return r.getResponseHeader("content-type").indexOf("xml") > 0 || type == "xml" ?
		r.responseXML : r.responseText;
};

$.get = function( url, ret, type ) {
	$.xml( "GET", url, null, function(r) {
		if ( ret ) { ret( $.httpData(r,type) ); }
	});
};

$.getXML = function( url, ret ) {
	$.get( url, ret, "xml" );
};

$.post = function( url, data, ret, type ) {
	$.xml( "POST", url, $.param(data), function(r) {
		if ( ret ) { ret( $.httpData(r,type) ); }
	});
};

$.postXML = function( url, data, ret ) {
	$.post( url, data, ret, "xml" );
};

$.param = function(a) {
	var s = [];
	if (a && typeof a == 'object' && a.constructor == Array) {
		for ( var i=0; i < a.length; i++ ) {
			s[s.length] = a[i].name + "=" + encodeURIComponent( a[i].value );
		}
	} else {
		for ( var j in a ) {
			s[s.length] = j + "=" + encodeURIComponent( a[j] );
		}
	}
	return s.join("&");
};

$.fn.load = function(a,o,f) {
	// Arrrrghhhhhhhh!!
	// I overwrote the event plugin's .load
	// this won't happen again, I hope -John
	if ( a && a.constructor == Function ) {
		return this.bind("load", a);
	}

	var t = "GET";
	if ( o && o.constructor == Function ) {
		f = o;
		o = null;
	}
	if (o !== null) {
		o = $.param(o);
		t = "POST";
	}
	var self = this;
	$.xml(t,a,o,function(h){
		h = h.responseText;
		self.html(h).find("script").each(function(){
			try {
				$.eval( this.text || this.textContent || this.innerHTML );
			} catch(e){}
		});
		if(f){f(h);}
	});
	return this;
};

/**
 * name:       $.fn.formValues
 * example:    $('#frmLogin').formValues('sButton')
 * docs:       Gets form values and creates a key=>value array of the found values.
 *             Optionally adds the button which is clicked if you provide it.
 *             Only does this for ENABLED elements in the order of the form.
 */
$.fn.formValues = function(sButton) {
	var a = [];
	var elp = {INPUT:true, TEXTAREA:true, OPTION:true};

	// Loop the shite
	$('*', this).each(function() {
		// Skip disabled elements
		if (this.disabled)
			return;

		// Skip elements not of the types in elp
		if (!elp[this.tagName.toUpperCase()])
			return;

		// Skip submit buttons and image elements
		if ((this.type == 'submit') || (this.type == 'image'))
 			return;

		// Skip non-selected options
		var sP = this.parentNode.nodeName.toUpperCase();
		if (((sP == 'SELECT') || (sP == 'OPTGROUP')) && (!this.selected))
			return;

		// Skip non-checked nodes
		if (((this.type == 'radio') || (this.type == 'checkbox')) && (!this.checked))
			return;

		// If we come here, everything is fine
		var sN = this.name || this.id || this.parentNode.name || this.parentNode.id;
		var sV = this.value;
		if ((!sN) && (sP == 'OPTGROUP'))
			sN = this.parentNode.parentNode.name || this.parentNode.parentNode.id;

		// Add the data
		a.push({ name: sN, value: sV });
	});

	// Add submit button if needed
	if (sButton && (sButton !== null)) {
		var el = $(sButton).get(0);
		a.push({
			name: el.name || el.id || el.parentNode.name || el.parentNode.id,
			value: el.value
		});
	}

	// Done
	return a;
};

/**
 * name:       $.fn.update
 * example:    $('someJQueryObject').update('sURL', 'sAction', 'aValues', 'fCallback');
 * docs:       Calls sURL with sAction and sends the aValues
 *	            Puts the results from that call in the jQuery object and calls fCallback
 */
$.fn.update = function(sURL, sMethod, aValues, fCallback) {
	var el = this;

	// Process
	$.xml(
		sMethod || "GET",
		sURL || "",
		$.param(aValues),
		function(sResult) {
			sResult = $.httpData(sResult);

			// Update the element with the new HTML
			el.html(sResult);

			// Evaluate the scripts AFTER this (so you can allready modify the new HTML!)
			el.html(sResult).find("script").each(function(){
				try { $.eval( this.text || this.textContent || this.innerHTML ); } catch(e) { }
			});

			// And call the callback handler :)
			if (fCallback && (fCallback.constructor == Function))
				fCallback();
		}
	);
};

/**
 * name:			$.fn.serialize
 * example:    $('someJQueryObject').serialize('sButton', 'fCallback');
 * docs:       Calls the form's action with the correct method and the serialized values.
 *             Optionally adds the button which is clicked if you provide it.
 *             When there are results, the fCallback function is called.
 */
$.fn.serialize = function(sButton, fCallback) {
	var el = this.get(0);

	// Process
	$.xml(
		el.method || "GET",
		el.action || "",
		$.param(this.formValues(sButton)),
		function(sResult) {
			if (fCallback && (fCallback.constructor == Function))
				fCallback($.httpData(sResult));
		}
	);
};
<commit_msg>Some errors in the formvalues() function<commit_after>// AJAX Plugin
// Docs Here:
// http://jquery.com/docs/ajax/

if ( typeof XMLHttpRequest == 'undefined' && typeof window.ActiveXObject == 'function') {
	XMLHttpRequest = function() {
		return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') >= 0) ?
			"Microsoft.XMLHTTP" : "Msxml2.XMLHTTP");
	};
}

// Counter for holding the active query's
$.xmlActive=0;

$.xml = function( type, url, data, ret ) {
	var xml = new XMLHttpRequest();

	if ( xml ) {
		// Open the socket
		xml.open(type || "GET", url, true);
		if ( data )
			xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		// Set header so calling script knows that it's an XMLHttpRequest
		xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

		/* Force "Connection: close" for Mozilla browsers to work around
		 * a bug where XMLHttpReqeuest sends an incorrect Content-length
		 * header. See Mozilla Bugzilla #246651.
		 */
		if ( xml.overrideMimeType )
			xml.setRequestHeader('Connection', 'close');

		xml.onreadystatechange = function() {
			// Socket is openend
			if ( xml.readyState == 1 ) {
				// Increase counter
				$.xmlActive++;

				// Show loader if needed
				if ( ($.xmlActive >= 1) && ($.xmlCreate) )
					$.xmlCreate();
			}

			// Socket is closed and data is available
			if ( xml.readyState == 4 ) {
				// Decrease counter
				$.xmlActive--;

				// Hide loader if needed
				if ( ($.xmlActive <= 0) && ($.xmlDestroy) ) {
					$.xmlDestroy();
					$.xmlActive = 0
				}

				// Process result
				if ( ret )
					ret(xml);
			}
		};

		xml.send(data)
	}
};

$.httpData = function(r,type) {
	return r.getResponseHeader("content-type").indexOf("xml") > 0 || type == "xml" ?
		r.responseXML : r.responseText;
};

$.get = function( url, ret, type ) {
	$.xml( "GET", url, null, function(r) {
		if ( ret ) { ret( $.httpData(r,type) ); }
	});
};

$.getXML = function( url, ret ) {
	$.get( url, ret, "xml" );
};

$.post = function( url, data, ret, type ) {
	$.xml( "POST", url, $.param(data), function(r) {
		if ( ret ) { ret( $.httpData(r,type) ); }
	});
};

$.postXML = function( url, data, ret ) {
	$.post( url, data, ret, "xml" );
};

$.param = function(a) {
	var s = [];
	if (a && typeof a == 'object' && a.constructor == Array) {
		for ( var i=0; i < a.length; i++ ) {
			s[s.length] = a[i].name + "=" + encodeURIComponent( a[i].value );
		}
	} else {
		for ( var j in a ) {
			s[s.length] = j + "=" + encodeURIComponent( a[j] );
		}
	}
	return s.join("&");
};

$.fn.load = function(a,o,f) {
	// Arrrrghhhhhhhh!!
	// I overwrote the event plugin's .load
	// this won't happen again, I hope -John
	if ( a && a.constructor == Function ) {
		return this.bind("load", a);
	}

	var t = "GET";
	if ( o && o.constructor == Function ) {
		f = o;
		o = null;
	}
	if (o !== null) {
		o = $.param(o);
		t = "POST";
	}
	var self = this;
	$.xml(t,a,o,function(h){
		h = h.responseText;
		self.html(h).find("script").each(function(){
			try {
				$.eval( this.text || this.textContent || this.innerHTML );
			} catch(e){}
		});
		if(f){f(h);}
	});
	return this;
};

/**
 * name:       $.fn.formValues
 * example:    $('#frmLogin').formValues('sButton')
 * docs:       Gets form values and creates a key=>value array of the found values.
 *             Optionally adds the button which is clicked if you provide it.
 *             Only does this for ENABLED elements in the order of the form.
 */
$.fn.formValues = function(sButton) {
	var a = [];
	var ok = {INPUT:true, TEXTAREA:true, OPTION:true};

	// Loop the shite
	$('*', this).each(function() {
		// Skip elements not of the types in ok
		if (!ok[this.tagName.toUpperCase()])
			return;

		// Skip disabled elements
		if (this.disabled)
			return;

		// Skip submit buttons and image elements
		if ((this.type == 'submit') || (this.type == 'image'))
 			return;

		// Skip non-selected options
		var oParent = this.parentNode;
		var sNn = oParent.nodeName.toUpperCase();
		if (((sNn == 'SELECT') || (sNn == 'OPTGROUP')) && (!this.selected))
			return;

		// Skip non-checked nodes
		if (((this.type == 'radio') || (this.type == 'checkbox')) && (!this.checked))
			return;

		// If we come here, everything is fine
		var sKey = this.name || this.id || oParent.name || oParent.id;
		var sValue = this.value;

		// If we don't have an ID, and the parent is an OPTGROUP,
		// get the NAME or ID of the OPTGROUP's parent
		if ((!sKey) && (sNn == 'OPTGROUP') && (oParent = oParent.parentNode))
			sKey = oParent.name || oParent.id;

		// Add the data
		a.push({ name: sKey, value: sValue });
	});

	// Add submit button if needed
	if (sButton && (sButton !== null)) {
		var el = $(sButton).get(0);
		a.push({
			name: el.name || el.id || el.parentNode.name || el.parentNode.id,
			value: el.value
		});
	}

	// Done
	return a;
};

/**
 * name:       $.fn.update
 * example:    $('someJQueryObject').update('sURL', 'sAction', 'aValues', 'fCallback');
 * docs:       Calls sURL with sAction and sends the aValues
 *	            Puts the results from that call in the jQuery object and calls fCallback
 */
$.fn.update = function(sURL, sMethod, aValues, fCallback) {
	var el = this;

	// Process
	$.xml(
		sMethod || "GET",
		sURL || "",
		$.param(aValues),
		function(sResult) {
			sResult = $.httpData(sResult);

			// Update the element with the new HTML
			el.html(sResult);

			// Evaluate the scripts AFTER this (so you can allready modify the new HTML!)
			el.html(sResult).find("script").each(function(){
				try { $.eval( this.text || this.textContent || this.innerHTML ); } catch(e) { }
			});

			// And call the callback handler :)
			if (fCallback && (fCallback.constructor == Function))
				fCallback();
		}
	);
};

/**
 * name:			$.fn.serialize
 * example:    $('someJQueryObject').serialize('sButton', 'fCallback');
 * docs:       Calls the form's action with the correct method and the serialized values.
 *             Optionally adds the button which is clicked if you provide it.
 *             When there are results, the fCallback function is called.
 */
$.fn.serialize = function(sButton, fCallback) {
	var el = this.get(0);

	// Process
	$.xml(
		el.method || "GET",
		el.action || "",
		$.param(this.formValues(sButton)),
		function(sResult) {
			if (fCallback && (fCallback.constructor == Function))
				fCallback($.httpData(sResult));
		}
	);
};
<|endoftext|>


<commit_before>'use strict';

$(function() {
  var $alertViewBackdrop = $('
');
  $(document.body).append($alertViewBackdrop);

  /**
    Shows the AlertView modal.
    @param {Object} Optional properties: title, message, buttons, and callback.
  */
  window.AlertView = {
    show: function(settings) {
      var title = settings.title;
      var message = settings.message;
      var buttons = settings.buttons;
      var callback = settings.callback;

      var $alertViewElement = $('
');

      if (title) $('
' + title + '
').appendTo($alertViewElement);

      if (message) $('
' + message + '
').appendTo($alertViewElement);

      if (buttons) {
        var numberOfButtons = buttons.length;
        if (numberOfButtons > 0) {
          $alertViewElement.addClass('button-count-' + numberOfButtons);
          for (var i = 0; i < numberOfButtons; i++) {
            $('' + buttons[i] + '').appendTo($alertViewElement);
          }
        }
      }

      if (callback && typeof callback === 'function') {
        $alertViewElement.delegate('a', 'click', function(evt) {
          evt.preventDefault();

          callback(parseInt($(this).attr('data-button-index'), 10));

          $alertViewElement.remove();
        });
      }

      // Add the alertViewElement just before the backdrop
      $alertViewBackdrop.before($alertViewElement);
    }
  };

});<commit_msg>Fixed bug where the AlertView modal would only close if there was a callback function assigned to the button that was clicked.<commit_after>'use strict';

$(function() {
  var $alertViewBackdrop = $('
');
  $(document.body).append($alertViewBackdrop);

  /**
    Shows the AlertView modal.
    @param {Object} Optional properties: title, message, buttons, and callback.
  */
  window.AlertView = {
    show: function(settings) {
      var title = settings.title;
      var message = settings.message;
      var buttons = settings.buttons;
      var callback = settings.callback;

      var $alertViewElement = $('
');

      if (title) $('
' + title + '
').appendTo($alertViewElement);

      if (message) $('
' + message + '
').appendTo($alertViewElement);

      if (buttons) {
        var numberOfButtons = buttons.length;
        if (numberOfButtons > 0) {
          $alertViewElement.addClass('button-count-' + numberOfButtons);
          for (var i = 0; i < numberOfButtons; i++) {
            $('' + buttons[i] + '').appendTo($alertViewElement);
          }
        }
      }

      $alertViewElement.delegate('a', 'click', function(evt) {
        evt.preventDefault();

        if (callback && typeof callback === 'function') {
          callback(parseInt($(this).attr('data-button-index'), 10));
        }

        $alertViewElement.remove();
      });

      // Add the alertViewElement just before the backdrop
      $alertViewBackdrop.before($alertViewElement);
    }
  };

});<|endoftext|>


<commit_before>// facebook login
window.fbAsyncInit = function() {
FB.init({
  appId      : '434443279939497', // App ID
  channelUrl : '//www.thebluealliance.com/channel', // Channel File
  status     : true, // check login status
  cookie     : true, // enable cookies to allow the server to access the session
  xfbml      : true  // parse XFBML
});

// Additional initialization code here
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
  if (response.authResponse) {
    // user has auth'd your app and is logged into Facebook
    FB.api('/me', function(me){
      if (me.name) {
        $('#auth-displayname').html(me.name);
      }
    })
    $('#auth-loggedout').hide();
    $('#auth-loggedin').show();
  } else {
    // user has not auth'd your app, or is not logged into Facebook
    $('#auth-loggedout').show();
    $('#auth-loggedin').hide();
  }
});

// respond to clicks on the login and logout links
$('#auth-loginlink').click(function(){
  FB.login();
});
$('#auth-logoutlink').click(function(){
  FB.logout();
});
};

// Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

function selectTypeaheadResult(item, val, text) {
	if (!isNaN(val)) {
		url = "http://www.thebluealliance.com/team/" + val;
	} else {
		url = "http://www.thebluealliance.com/event/" + val;
	}
	window.location.href = url;
}

// General JS for all pages
var finish_utc;
$(document).ready(function(){
	// Jumping to page section
    $('.smooth-scroll').bind('click',function(event){
        var $anchor = $(this);
        var $navbar_position = $('.navbar').css('top');
        var $navbar_height = parseInt($('.navbar').css('height'));
        var $offset = 0;

        // Takes care of changing navbar size/position due to @media width
        if ($navbar_position == '0px') {
          $offset = $navbar_height;
        }

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - $offset
        }, 250);
        event.preventDefault();
    });

	// Fancybox
	$(".fancybox").fancybox();

	// Disable browser autocompletes
	$('.search-query').attr('autocomplete', 'off');

	// Typeahead for search
	// Currently does a one-time JSON get that returns
	// the entire list of teams and events.
	// Can be optimized.
	$('.search-query').focus(function() {
		if (!$('.search-query').data('typeahead')) {
			$.getJSON('/_/typeahead', function(data) {
				$('.search-query').typeahead({
					// Used for when we implement a better typeahead solution
			    	/*ajax: {
				    	    url: '/_/typeahead',
				    	    method: 'get',
				    	    triggerLength: 3,
				    },*/
					source: data,
			    	itemSelected: selectTypeaheadResult
			    });
			});
		};
	});

	// Tooltips
	$("[rel=tooltip]").tooltip();

	// Fitvids
	$('.fitvids').fitVids();
});
<commit_msg>Remove unused var in JS<commit_after>// facebook login
window.fbAsyncInit = function() {
FB.init({
  appId      : '434443279939497', // App ID
  channelUrl : '//www.thebluealliance.com/channel', // Channel File
  status     : true, // check login status
  cookie     : true, // enable cookies to allow the server to access the session
  xfbml      : true  // parse XFBML
});

// Additional initialization code here
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
  if (response.authResponse) {
    // user has auth'd your app and is logged into Facebook
    FB.api('/me', function(me){
      if (me.name) {
        $('#auth-displayname').html(me.name);
      }
    })
    $('#auth-loggedout').hide();
    $('#auth-loggedin').show();
  } else {
    // user has not auth'd your app, or is not logged into Facebook
    $('#auth-loggedout').show();
    $('#auth-loggedin').hide();
  }
});

// respond to clicks on the login and logout links
$('#auth-loginlink').click(function(){
  FB.login();
});
$('#auth-logoutlink').click(function(){
  FB.logout();
});
};

// Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

function selectTypeaheadResult(item, val, text) {
	if (!isNaN(val)) {
		url = "http://www.thebluealliance.com/team/" + val;
	} else {
		url = "http://www.thebluealliance.com/event/" + val;
	}
	window.location.href = url;
}

// General JS for all pages
$(document).ready(function(){
	// Jumping to page section
    $('.smooth-scroll').bind('click',function(event){
        var $anchor = $(this);
        var $navbar_position = $('.navbar').css('top');
        var $navbar_height = parseInt($('.navbar').css('height'));
        var $offset = 0;

        // Takes care of changing navbar size/position due to @media width
        if ($navbar_position == '0px') {
          $offset = $navbar_height;
        }

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - $offset
        }, 250);
        event.preventDefault();
    });

	// Fancybox
	$(".fancybox").fancybox();

	// Disable browser autocompletes
	$('.search-query').attr('autocomplete', 'off');

	// Typeahead for search
	// Currently does a one-time JSON get that returns
	// the entire list of teams and events.
	// Can be optimized.
	$('.search-query').focus(function() {
		if (!$('.search-query').data('typeahead')) {
			$.getJSON('/_/typeahead', function(data) {
				$('.search-query').typeahead({
					// Used for when we implement a better typeahead solution
			    	/*ajax: {
				    	    url: '/_/typeahead',
				    	    method: 'get',
				    	    triggerLength: 3,
				    },*/
					source: data,
			    	itemSelected: selectTypeaheadResult
			    });
			});
		};
	});

	// Tooltips
	$("[rel=tooltip]").tooltip();

	// Fitvids
	$('.fitvids').fitVids();
});
<|endoftext|>


<commit_before>var cacheName = 'weatherPWA-step-6-1';
var filesToCache = [];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
});<commit_msg>changed self.addListener('activate';<commit_after>var cacheName = 'weatherPWA-step-6-1';
var filesToCache = [];

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', function(e) {
  console.log('[ServiceWorker] Activate');
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (key !== cacheName) {
          console.log('[ServiceWorker] Removing old cache', key);
          return caches.delete(key);
        }
      }));
    })
  );
  return self.clients.claim();
});<|endoftext|>


<commit_before>exports['Should correctly timeout mongos socket operation and then correctly re-execute'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var Mongos = configuration.require.Mongos,
      ObjectId = configuration.require.BSON.ObjectId,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var server = null;
    var running = true;
    // Current index for the ismaster
    var currentStep = 0;
    // Primary stop responding
    var stopRespondingPrimary = false;

    // Extend the object
    var extend = function(template, fields) {
      for(var name in template) fields[name] = template[name];
      return fields;
    }

    // Default message fields
    var defaultFields = {
      "ismaster" : true,
      "msg" : "isdbgrid",
      "maxBsonObjectSize" : 16777216,
      "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000,
      "localTime" : new Date(),
      "maxWireVersion" : 3,
      "minWireVersion" : 0,
      "ok" : 1
    }

    // Primary server states
    var serverIsMaster = [extend(defaultFields, {})];
    var timeoutPromise = function(timeout) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve();
        }, timeout);
      });
    }

    // Boot the mock
    co(function*() {
      server = yield mockupdb.createServer(52000, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield server.receive();

          // Get the document
          var doc = request.document;
          if(doc.ismaster && currentStep == 0) {
            request.reply(serverIsMaster[0]);
            currentStep += 1;
          } else if(doc.insert && currentStep == 1) {
            // Stop responding to any calls (emulate dropping packets on the floor)
            if(stopRespondingPrimary) {
              yield timeoutPromise(1500);
              continue;
            }

            currentStep += 1;
          } else if(doc.ismaster && currentStep == 2) {
            request.reply(serverIsMaster[0]);
          } else if(doc.insert && currentStep == 2) {
            request.reply({ok:1, n:doc.documents, lastOp: new Date()});
          }
        }
      });

      // Start dropping the packets
      setTimeout(function() {
        stopRespondingPrimary = true;
        currentIsMasterState = 1;
      }, 5000);
    });

    // Attempt to connect
    var server = new Mongos([
        { host: 'localhost', port: 52000 },
      ], {
      connectionTimeout: 3000,
      socketTimeout: 1000,
      haInterval: 1000,
      size: 1
    });

    // Add event listeners
    server.once('connect', function(_server) {
      _server.insert('test.test', [{created:new Date()}], function(err, r) {
        test.ok(err != null);

        // Let auto-reconnect run and restablish connection
        setTimeout(function() {
          _server.insert('test.test', [{created:new Date()}], function(err, r) {
            test.equal(null, err);

            server.destroy();
            running = false;
            test.done();
          });
        }, 1200)
      });
    });

    server.on('error', function(){});
    server.connect();
  }
}
<commit_msg>minor test fix for single mongos<commit_after>exports['Should correctly timeout mongos socket operation and then correctly re-execute'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var Mongos = configuration.require.Mongos,
      ObjectId = configuration.require.BSON.ObjectId,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var server = null;
    var running = true;
    // Current index for the ismaster
    var currentStep = 0;
    // Primary stop responding
    var stopRespondingPrimary = false;

    // Extend the object
    var extend = function(template, fields) {
      for(var name in template) fields[name] = template[name];
      return fields;
    }

    // Default message fields
    var defaultFields = {
      "ismaster" : true,
      "msg" : "isdbgrid",
      "maxBsonObjectSize" : 16777216,
      "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000,
      "localTime" : new Date(),
      "maxWireVersion" : 3,
      "minWireVersion" : 0,
      "ok" : 1
    }

    // Primary server states
    var serverIsMaster = [extend(defaultFields, {})];
    var timeoutPromise = function(timeout) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve();
        }, timeout);
      });
    }

    // Boot the mock
    co(function*() {
      server = yield mockupdb.createServer(52000, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield server.receive();

          // Get the document
          var doc = request.document;
          if(doc.ismaster && currentStep == 0) {
            request.reply(serverIsMaster[0]);
            currentStep += 1;
          } else if(doc.insert && currentStep == 1) {
            // Stop responding to any calls (emulate dropping packets on the floor)
            if(stopRespondingPrimary) {
              yield timeoutPromise(1500);
              continue;
            }

            currentStep += 1;
            stopRespondingPrimary = false;
          } else if(doc.ismaster && currentStep == 2) {
            request.reply(serverIsMaster[0]);
          } else if(doc.insert && currentStep == 2) {
            request.reply({ok:1, n:doc.documents, lastOp: new Date()});
          }
        }
      });

      // Start dropping the packets
      setTimeout(function() {
        stopRespondingPrimary = true;
        currentIsMasterState = 1;
      }, 1000);
    });

    // Attempt to connect
    var server = new Mongos([
        { host: 'localhost', port: 52000 },
      ], {
      connectionTimeout: 3000,
      socketTimeout: 1000,
      haInterval: 1000,
      size: 1
    });

    // Add event listeners
    server.once('connect', function(_server) {
      _server.insert('test.test', [{created:new Date()}], function(err, r) {
        test.ok(err != null);

        // Let auto-reconnect run and restablish connection
        setTimeout(function() {
          _server.insert('test.test', [{created:new Date()}], function(err, r) {
            test.equal(null, err);

            server.destroy();
            running = false;
            test.done();
          });
        }, 1200)
      });
    });

    server.on('error', function(){});
    server.connect();
  }
}
<|endoftext|>