text:
var common = require('../common');
var fs = require('fs');
var path = require('path');
var url = require('url');
var crypto = require('crypto');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;
var Channel = require('../channel');
var async = require('async');
var child_process = require('child_process');
var utils = require('../utils');
var constants = require('../constants');
var cacheUtils = require('../cacheUtils');

exports.init = function (cli) {

  var log = cli.output;

  function getChannel() {
    var account = cli.category('account');
    var managementEndpoint = url.parse(utils.getManagementEndpointUrl(account.managementEndpointUrl()));
    var pem = account.managementCertificate();
    var host = managementEndpoint.hostname;
    var port = managementEndpoint.port;

    var channel = new Channel({
      host: host,
      port: port,
      key: pem.key,
      cert: pem.cert
    }).header('x-ms-version', '2011-02-25');

    var proxyString =
            process.env.HTTPS_PROXY ||
            process.env.https_proxy ||
            process.env.ALL_PROXY ||
            process.env.all_proxy;

    if (proxyString !== undefined) {
      var proxyUrl = url.parse(proxyString);
      if (proxyUrl.protocol !== 'http:' &&
                proxyUrl.protocol !== 'https:') {
        // fall-back parsing support XXX_PROXY=host:port environment variable values
        proxyUrl = url.parse('http://' + proxyString);
      }

      channel = channel.add({ proxy: proxyUrl });
    }

    return channel;
  }

  var site = cli.category('site')
        .description('Commands to manage your web sites');

  site.command('list')
        .whiteListPowershell()
        .description('List your web sites')
        .option('-s, --subscription <id>', 'use the subscription id')
        .execute(function (options, _) {
          var parameters = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription)
          };

          var sites = site.doSitesGet(parameters, _);

          if (sites && sites.length > 0) {
            for (var s in sites) {
              sites[s] = clean(sites[s]);
            }

            log.table(sites, function (row, s) {
              row.cell('Name', s.Name);
              row.cell('State', s.State);
              row.cell('Host names', s.HostNames);
            });
          } else {
            log.info('No sites created yet. You can create new sites using "azure site create" or through the portal.');
          }
        });

  function choose(data, callback) {
    cli.choose(data, function (x) { callback(undefined, x); });
  }
  function prompt(label, callback) {
    cli.prompt(label, function (x) { callback(undefined, x); });
  }
  function confirm(label, callback) {
    cli.confirm(label, function (x) {
      if (!x) {
        log.warn('The operation was cancelled by the user');
      }
      callback(undefined, x);
    });
  }
  site.confirm = confirm;

  site.command('create [name]')
        .whiteListPowershell()
        .description('Create a new web site')
        .option('-s, --subscription <id>', 'use the subscription id')
        .option('--location <location>', 'the geographic region to create the website')
        .option('--hostname <hostname>', 'custom host name to use')
        .option('--git', 'configure git on web site and local folder')
        .execute(function (nameArg, options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            git: options.git,
            site: {
              name: nameArg,
              webspace: options.location,
              hostname: options.hostname
            },
            flags: {
            }
          };

          promptForSiteName(_);
          determineIfSiteExists(_);
          promptForLocation(_);
          determineIfCurrentDirectoryIsGitWorkingTree(_);
          initGitOnCurrentDirectory(_);
          copyIisNodeWhenServerJsPresent(_);
          updateLocalConfigWithSiteName(_);
          createSiteAndInitializeRemoteRepo(_);
          addRemoteToLocalGitRepo(_);

          function promptForSiteName(_) {
            log.silly('promptForSiteName');
            if (context.site.name === undefined) {
              log.help('Need a site name');
              context.site.name = prompt('Name: ', _);
            }
          }

          function determineIfSiteExists(_) {
            log.silly('determineIfSiteExists');
            var sites = site.doSitesGet(context, _);
            var hits = sites.filter(function (item) {
              return utils.ignoreCaseEquals(item.Name, context.site.name);
            });
            if (hits.length === 1) {
              log.info('Updating existing site');
              context.flags.siteExists = true;
              if (context.site.webspace === undefined) {
                context.site.webspace = hits[0].WebSpace;
                log.verbose('Existing site location is ', context.site.webspace)
              } else if (context.site.webspace !== hits[0].WebSpace) {
                throw new Error('Expected location ' + context.site.webspace + ' but was ' + hits[0].WebSpace);
              }
            }
          }

          function promptForLocation(_) {
            log.silly('promptForLocation');
            var spaces = cacheUtils.readSpaces(context, _);
            if (!spaces || !spaces.length) {
              spaces = site.doSpacesGet(context, _);
            }

            if (context.site.webspace !== undefined) {
              // Map user-provided value to GeoRegion display name, if unique match exists
              var displayNameMatches = spaces.filter(function (space) {
                return space.GeoRegion === context.site.webspace;
              });

              if (displayNameMatches.length === 1) {
                context.site.webspace = displayNameMatches[0].Name;
              }
            }

            if (context.site.webspace !== undefined) {
              // Don't prompt if location has been inferred or provided
              return;
            }

            if (spaces.length === 0) {
              portalCreateSiteInstruction(context, _);
              throw new Error('First site must be created on portal');
            } else if (spaces.length == 1) {
              context.site.webspace = spaces[0].Name;
              log.info('Using location', spaces[0].GeoRegion);
            } else {
              log.help('Choose a region');
              context.site.webspace = spaces[choose(spaces.map(function (space) {
                return space.GeoRegion;
              }), _)].Name;
            }
          }

          function determineIfCurrentDirectoryIsGitWorkingTree(_) {
            log.silly('determineIfCurrentDirectoryIsGitWorkingTree');

            try {
              var isInsideWorkTree = exec('git rev-parse --git-dir', _);
              var lines = isInsideWorkTree.stdout + isInsideWorkTree.stderr;
              context.flags.isGitWorkingTree = lines.split('\n').some(function (line) {
                return line === '.git';
              });
            } catch (err) {
              context.flags.isGitWorkingTree = false;
            }
          }

          function initGitOnCurrentDirectory(_) {
            log.silly('initGitOnCurrentDirectoryIfNeeded');
            if (context.flags.isGitWorkingTree) {
              return;
            }

            if (!options.git) {
              return;
            }

            context.publishingUsers = site.doPublishingUsersGet(context, _);
            context.publishingUser = getPublishingUser(context, _);

            log.info('Executing `git init`');
            exec('git init', _);

            if (!utils.pathExistsSync('.gitignore')) {
              log.info('Creating default .gitignore file');
              fs.writeFile('.gitignore', 'node_modules\nazure_error', _);
            }

            context.flags.isGitWorkingTree = true;
          }

          function copyIisNodeWhenServerJsPresent(_) {
            log.silly('copyWebConfigWhenServerJsPresent');
            if (!utils.pathExistsSync('iisnode.yml') && (utils.pathExistsSync('server.js') || utils.pathExistsSync('app.js'))) {
              log.info('Creating default iisnode.yml file');
              var sourcePath = path.join(__dirname, '../templates/node/iisnode.yml');
              fs.writeFile('iisnode.yml', fs.readFile(sourcePath, _), _);
            }
          }

          function updateLocalConfigWithSiteName(_) {
            log.silly('updateLocalConfigWithSiteName');
            if (context.flags.isGitWorkingTree) {
              var cfg = site.readConfig(_);
              cfg.name = context.site.name;
              cfg.webspace = context.site.webspace;
              site.writeConfig(cfg, _);
            }
          }

          function createSiteAndInitializeRemoteRepo(_) {
            log.silly('createSiteAndInitializeRemoteRepo');
            if (!context.flags.siteExists) {
              site.doSitesPost(context, _);
              site.doRepositoryPost(context, _);
              context.repo = site.doRepositoryGet(context, _);
            } else {
              context.repo = site.doRepositoryGet(context, _);
              if (!context.repo) {
                site.doRepositoryPost(context, _);
                context.repo = site.doRepositoryGet(context, _);
              }
            }
            log.silly('context.repo', context.repo);
          }

          function addRemoteToLocalGitRepo(_) {
            log.silly('addRemoteToLocalGitRepo');
            if (!context.flags.isGitWorkingTree) {
              log.info('To create a local git repository to publish to the remote site, please rerun this command with the --git flag: "azure site create ' + ((context.site && context.site.name) || '{site name}') + ' --git".')
              return;
            }

            if (!context.publishingUser) {
              context.publishingUsers = site.doPublishingUsersGet(context, _);
              context.publishingUser = getPublishingUser(context, _);
            }

            log.verbose('Detecting git and local git folder');
            var remotes = exec('git remote', _);
            var azureExists = (remotes.stdout + remotes.stderr).split('\n').some(function (item) {
              return item === 'azure';
            });

            if (azureExists) {
              log.verbose('Removing existing azure remote alias');
              exec('git remote rm azure', _);
            }

            var gitUri = getGitUri(context.repo, context.site.name, context.publishingUser);
            log.info('Executing `git remote add azure ' + gitUri + '`');
            exec('git remote add azure ' + gitUri, _);
          }
        });

  function portalCreateSiteInstruction(context, _) {
    log.help('You must create your first web site using the Windows Azure portal.');
    log.help('Please follow these steps in the portal:');
    log.help('1. At the bottom of the page, click on New > Web Site > Quick Create');
    log.help('2. Type "' + ((context.site && context.site.name) || '{site name}') + '" in the URL field');
    log.help('3. Click on "Create Web Site"');
    log.help('4. Once the site has been created, click on the site name');
    log.help('5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.');
    if (context.git) {
      log.help('6. Back in the console window, rerun this command by typing "azure site create {site name} --git"');
    }

    if (confirm('Launch browser to portal now? (y/n) ', _)) {
      log.help('Launching portal.');
      var href = utils.getPortalUrl();
      common.launchBrowser(href);
    }
  }

  function getPublishingUser(context, _) {
    var publishingUsers = toArray(context.publishingUsers);
    var filters = publishingUsers.filter(function (item) {
      return typeof item === 'string' && item.length <= 64;
    });

    if (filters.length === 0) {
      portalGitInitInstruction(context, _);
      throw new Error('Git credentials needs to be setup on the portal');
    } else if (publishingUsers.length === 1 && filters.length === 1) {
      return filters[0];
    }

    log.help('Please provide the username for Git deployment.');
    log.help('If you don\'t have one, please configure it in the management portal.');
    return prompt('Publishing username: ', _);
  }

  function portalGitInitInstruction(context, _) {
    log.help('You must create your git publishing credentials using the Windows Azure portal.');
    log.help('Please follow these steps in the portal:');
    log.help('1. In the menu on the left select "Web Sites"');
    log.help('2. Click on the site named "' + ((context.site && context.site.name) || '{site name}') + '" or any other site');
    log.help('3. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.');
    if (context.git) {
      log.help('4. Back in the console window, rerun this command by typing "azure site create {site name} --git"');
    }

    if (confirm('Launch browser to portal now? (y/n) ', _)) {
      log.help('Launching portal.');
      var href = utils.getPortalUrl();
      common.launchBrowser(href);
    }
  }

  var location = site.category('location')
        .description('Commands to manage your Azure locations');

  location.command('list')
        .whiteListPowershell()
        .description('List locations available for your account')
        .execute(function (options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription)
          };

          var spaces = site.doSpacesGet(context, _);
          if (spaces && spaces.length) {
            for (var s in spaces) {
              spaces[s] = clean(spaces[s]);
            }

            log.table(spaces, function (row, item) {
              row.cell('Name', item.GeoRegion);
            });
          } else {
            portalCreateSiteInstruction(context, _);
          }
        });

  site.command('portal [name]')
        .whiteListPowershell()
        .description('Opens the portal in a browser to manage your web sites')
        .execute(function (name, options, _) {

          var href = utils.getPortalUrl();
          if (name) {
            href = href + '#Workspaces/WebsiteExtension/Website/' + name + '/dashboard';
          }

          common.launchBrowser(href);
        });

  site.command('browse [name]')
        .whiteListPowershell()
        .description('Open your web site in a browser.')
        .option('-s, --subscription <id>', 'use the subscription id')
        .execute(function (name, options, _) {

          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            site: {
              name: name
            }
          };

          var cache = lookupSiteNameAndWebSpace(context, _);
          var siteData = clean(cache || site.doSiteGet(context, _));

          var href = 'http://' + toArray(siteData.HostNames)[0];

          common.launchBrowser(href);
        });

  site.command('show [name]')
        .whiteListPowershell()
        .description('Show details for a web site')
        .option('-s, --subscription <id>', 'use the subscription id')
        .execute(function (name, options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            site: {
              name: name
            }
          };

          lookupSiteNameAndWebSpace(context, _);

          log.info('Showing details for site');
          log.verbose('Parameters', context);

          var result = async.parallel([
            function (_) { return site.doSiteGet(context, _); },
            function (_) { return site.doSiteConfigGet(context, _); }
            ],
            _);

          var repositoryUri = getRepositoryUri(result[0]);
          var gitUri = repositoryUri ? getGitUri(repositoryUri, context.site.name) : 'none';

          if (log.format().json) {
            var data = {
              site: clean(result[0]),
              config: clean(result[1]),
              gitRepositoryUri: gitUri
            };

            log.json(data);
          } else {
            logEachData('Site', result[0]);
            logEachData('Config', result[1]);

            log.data('GitRepositoryUri', gitUri);
          }
        });

  function lookupSiteName(context, _) {
    if (context.site.name !== undefined) {
      // no need to read further
      return;
    }

    var cfg = site.readConfig(_);
    if (cfg && cfg.name) {
      // using the name from current location
      context.site.name = cfg.name;
      context.site.webspace = cfg.webspace;
      return;
    }

    context.site.name = prompt('Web site name: ', _);

    if (!context.site.name) {
      throw new Error('Invalid site name');
    }
  }

  function lookupSiteWebSpace(context, _) {
    log.verbose('Attempting to locate site ', context.site.name);
    var sites = site.doSitesGet(context, _);
    for (var index in sites) {
      if (utils.ignoreCaseEquals(sites[index].Name, context.site.name)) {
        log.verbose('Site located at ', sites[index].WebSpace);
        context.site.webspace = sites[index].WebSpace;
      }
    }
    if (context.site.webspace === undefined) {
      throw new Error('Unable to locate site named ' + context.site.name);
    }
  }

  function lookupSiteNameAndWebSpace(context, _) {
    lookupSiteName(context, _);
    var cache = cacheUtils.readSite(context, _);
    if (cache || context.site.webspace) {
      context.site.webspace = (cache && cache.WebSpace) || context.site.webspace;
      return cache;
    }
    lookupSiteWebSpace(context, _);
  }

  site.lookupSiteNameAndWebSpace = lookupSiteNameAndWebSpace;

  function getRepositoryUri(siteData) {
    if (siteData.SiteProperties.Properties) {
      for (var i = 0; i < siteData.SiteProperties.Properties.NameValuePair.length; ++i) {
        var pair = siteData.SiteProperties.Properties.NameValuePair[i];
        if (utils.ignoreCaseEquals(pair.Name, "RepositoryUri")) {
          if (typeof pair.Value === 'string') {
            if (!endsWith(pair.Value, '/')) {
              // Make sure there is a trailing slash
              pair.Value += '/';
            }

            return pair.Value;
          } else {
            return null;
          }
        }
      }
    }

    return null;
  }

  site.getRepositoryUri = getRepositoryUri;

  function getGitUri(repositoryUri, siteName, auth) {
    var repoUrl = url.parse(repositoryUri);

    if (auth) {
      repoUrl.auth = auth;
    }

    var sitePath = siteName + '.git';

    if (!endsWith(repoUrl.path, '/')) {
      // Make sure trailing slash exists
      repoUrl.path += '/';
    }
    repoUrl.path += sitePath;

    if (!endsWith(repoUrl.pathname, '/')) {
      // Make sure trailing slash exists
      repoUrl.pathname += '/';
    }
    repoUrl.pathname += sitePath;

    return url.format(repoUrl);
  }

  function getRepositoryAuth(siteData) {
    var userName, password;
    for (var i = 0; i < siteData.SiteProperties.Properties.NameValuePair.length; ++i) {
      var pair = siteData.SiteProperties.Properties.NameValuePair[i];
      if (utils.ignoreCaseEquals(pair.Name, "PublishingUsername")) {
        userName = pair.Value;
      } else if (utils.ignoreCaseEquals(pair.Name, "PublishingPassword")) {
        password = pair.Value;
      }
    }
    return userName && (userName + ":" + password);
  }
  site.getRepositoryAuth = getRepositoryAuth;

  site.command('delete [name]')
        .whiteListPowershell()
        .description('Delete a web site')
        .option('-s, --subscription <id>', 'use the subscription id')
        .option('-q, --quiet', 'quiet mode, do not ask for delete confirmation')
        .execute(function (name, options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            site: {
              name: name
            }
          };

          lookupSiteNameAndWebSpace(context, _);

          log.info('Deleting site', context.site.name);
          if (!options.quiet && !confirm('Delete ' + context.site.name + ' site?  (y/n) ', _)) {
            return;
          }

          var progress = cli.progress('Deleting site');
          try {
            var result = getChannel()
                    .path(context.subscription)
                    .path('services')
                    .path('webspaces')
                    .path(context.site.webspace)
                    .path('sites')
                    .path(context.site.name)
                    .DELETE(_);
            cacheUtils.deleteSite(context, _);
          }
          finally {
            progress.end();
          }
          log.info('Site ' + context.site.name + ' has been deleted');
        });

  site.command('start [name]')
        .whiteListPowershell()
        .description('Start a web site')
        .option('-s, --subscription <id>', 'use the subscription id')
        .execute(function (name, options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            site: {
              name: name
            }
          };

          lookupSiteNameAndWebSpace(context, _);

          log.info('Starting site', context.site.name);

          var progress = cli.progress('Updating site state');
          try {
            var result = getChannel()
                    .path(context.subscription)
                    .path('services')
                    .path('webspaces')
                    .path(context.site.webspace)
                    .path('sites')
                    .path(context.site.name)
                    .header('Content-Type', 'application/xml')
                    .PUT(function (req) {
                      req.write('<Site xmlns="http://schemas.microsoft.com/windowsazure">');
                      req.write('<HostNames>');
                      req.write('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">');
                      req.write(context.site.name + utils.getHostNameSuffix());
                      req.write('</string>');
                      req.write('</HostNames>');
                      req.write('<Name>');
                      req.write(context.site.name);
                      req.write('</Name>');
                      req.write('<State>');
                      req.write('Running');
                      req.write('</State>');
                      req.write('</Site>');

                      req.end();
                    }, _);
          }
          finally {
            progress.end();
          }

          log.info('Site ' + context.site.name + ' has been started');
        });

  site.command('stop [name]')
        .whiteListPowershell()
        .description('Stop a web site')
        .option('-s, --subscription <id>', 'use the subscription id')
        .execute(function (name, options, _) {
          var context = {
            subscription: cli.category('account').lookupSubscriptionId(options.subscription),
            site: {
              name: name
            }
          };

          lookupSiteNameAndWebSpace(context, _);

          log.info('Stopping site', context.site.name);

          var progress = cli.progress('Updating site state');
          try {
            var result = getChannel()
                    .path(context.subscription)
                    .path('services')
                    .path('webspaces')
                    .path(context.site.webspace)
                    .path('sites')
                    .path(context.site.name)
                    .header('Content-Type', 'application/xml')
                    .PUT(function (req) {
                      req.write('<Site xmlns="http://schemas.microsoft.com/windowsazure">');
                      req.write('<HostNames>');
                      req.write('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">');
                      req.write(context.site.name + utils.getHostNameSuffix());
                      req.write('</string>');
                      req.write('</HostNames>');
                      req.write('<Name>');
                      req.write(context.site.name);
                      req.write('</Name>');
                      req.write('<State>');
                      req.write('Stopped');
                      req.write('</State>');
                      req.write('</Site>');

                      req.end();
                    }, _);
          }
          finally {
            progress.end();
          }

          log.info('Site ' + context.site.name + ' has been stopped');
        });

  /////////////////
  // config and settings

  site.readConfig = function (_) {
    return {
      name: site.readConfigValue('azure.site.name', _),
      webspace: site.readConfigValue('azure.site.webspace', _)
    };
  };

  site.writeConfig = function (cfg, _) {
    site.writeConfigValue('azure.site.name', cfg.name, _);
    site.writeConfigValue('azure.site.webspace', cfg.webspace, _);
  };

  site.readConfigValue = function (name, _) {
    try {
      var result = exec('git config --get ' + name, _);
      return (result.stdout + result.stderr).trim();
    }
    catch (err) {
      log.silly('Unable to read config', err);
      return '';
    }
  };

  site.writeConfigValue = function (name, value, _) {
    exec('git config ' + name + ' ' + value, _);
  };

  /////////////////
  // remote api operations

  site.doSitesPost = function (options, callback) {
    log.info('Creating a new web site at ' + options.site.name + utils.getHostNameSuffix());
    log.verbose('Subscription', options.subscription);
    log.verbose('Webspace', options.site.webspace);
    log.verbose('Site', options.site.name);

    var progress = cli.progress('Sending site information');
    getChannel()
              .path(options.subscription)
              .path('services')
              .path('webspaces')
              .path(options.site.webspace)
              .path('sites')
              .header('Content-Type', 'application/xml')
              .POST(
                  writers.Site.xml(options.site),
                  function (err, result) {
                    progress.end();
                    if (err) {
                      logError('Failed to create site', err);
                    } else {
                      return cacheUtils.saveSite(options, result, function (err) {
                        log.info('Created website at ' + clean(result).HostNames);
                        log.verbose('Site', clean(result));
                        return callback(err, result);
                      });
                    }

                    if (err && typeof err.Message !== 'string') {
                      return callback('Invalid service request', result);
                    } else {
                      return callback(err, result);
                    }
                  });
  };

  site.doRepositoryPost = function (options, callback) {
    log.info('Initializing remote Azure repository');
    log.verbose('Subscription', options.subscription);
    log.verbose('Webspace', options.site.webspace);
    log.verbose('Site', options.site.name);

    var progress = cli.progress('Updating site information');
    getChannel()
              .path(options.subscription)
              .path('services')
              .path('webspaces')
              .path(options.site.webspace)
              .path('sites')
              .path(options.site.name)
              .path('repository')
              .POST(
                  "",
                  function (err, result) {
                    progress.end();
                    if (err) {
                      logError('Failed to initialize repository', err);
                    } else {
                      log.info('Repository initialized');
                    }
                    return callback(err, result);
                  });
  };

  site.doSpacesGet = function (options, _) {
    log.verbose('Subscription', options.subscription);

    var progress = cli.progress('Enumerating locations');
    try {
      var result = getChannel()
                .path(options.subscription)
                .path('services')
                .path('webspaces')
                .path('')
                .GET(_);

      log.json('silly', result);
      var spaces = toArray(result.WebSpace);
      cacheUtils.saveSpaces(options, spaces, _);
      return spaces;
    }
    finally {
      progress.end();
    }
  };

  site.doSitesGet = function (options, _) {
    log.verbose('Subscription', options.subscription);

    var spaces = site.doSpacesGet(options, _);

    var channel = getChannel()
            .path(options.subscription)
            .path('services')
            .path('webspaces');

    var progress = cli.progress('Enumerating sites');
    try {
      var result = async.map(
                spaces,
                function (webspace, _) {
                  return channel
                        .path(webspace.Name)
                        .path('sites')
                        .path('')
                        .query('propertiesToInclude', 'repositoryuri,publishingpassword,publishingusername')
                        .GET(_);
                },
                _);

      var sites = [];
      result.forEach(function (item) {
        sites = sites.concat(toArray(item.Site));
      });
      result = sites;

      log.json('verbose', sites);
      cacheUtils.saveSites(options, result, _);
      return sites;
    }
    finally {
      progress.end();
    }
  };

  site.doSiteGet = function (options, callback) {
    var progress = cli.progress('Retrieving site information');
    getChannel()
              .path(options.subscription)
              .path('services')
              .path('webspaces')
              .path(options.site.webspace)
              .path('sites')
              .path(options.site.name)
              .query('propertiesToInclude', 'repositoryuri,publishingpassword,publishingusername')
              .GET(
                  function (err, result) {
                    progress.end();
                    if (err) {
                      logError('Failed to get site info', err);
                      if (err.Code === 'NotFound') {
                        return cacheUtils.deleteSite(options, function () {
                          return callback(err, result);
                        });
                      }
                    } else {
                      return cacheUtils.saveSite(options, result, function (err) {
                        log.verbose('Site', clean(result));
                        return callback(err, result);
                      });
                    }
                    return callback(err, result);
                  });
  };

  site.doSiteConfigGet = function (options, callback) {
    var progress = cli.progress('Retrieving site config information');
    getChannel()
              .path(options.subscription)
              .path('services')
              .path('webspaces')
              .path(options.site.webspace)
              .path('sites')
              .path(options.site.name)
              .path('config')
              .GET(
                  function (err, result) {
                    progress.end();
                    if (err) {
                      logError('Failed to get site config info', err);
                    } else {
                      log.verbose('SiteConfig', clean(result));
                    }
                    return callback(err, result);
                  });
  };

  site.doRepositoryGet = function (options, _) {
    var siteData = site.doSiteGet(options, _);
    return getRepositoryUri(siteData);
  };

  site.doPublishingUsersGet = function (options, _) {
    var progress = cli.progress('Retrieving user information');
    try {
      var publishingUsers = clean(getChannel()
                .path(options.subscription)
                .path('services')
                .path('webspaces')
                .path('')
                .query('properties', 'publishingUsers')
                .GET(_));

      log.verbose('PublishingUsers', publishingUsers);
      return publishingUsers;
    }
    finally {
      progress.end();
    }
  };

  /////////////////
  // helper methods

  var writers = {
    Site: {
      xml: function (site) {
        return function (req) {
          req.write('<Site xmlns="http://schemas.microsoft.com/windowsazure">');
          req.write('<HostNames>');
          req.write('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">');
          req.write(site.name + utils.getHostNameSuffix());
          req.write('</string>');

          if (site.hostname) {
            req.write('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">');
            req.write(site.hostname);
            req.write('</string>');
          }
          req.write('</HostNames>');
          req.write('<Name>');
          req.write(site.name);
          req.write('</Name>');
          req.write('</Site>');

          req.end();
        };
      }
    }
  };

  function clean(source) {
    if (typeof (source) === 'string') {
      return source;
    }

    var target = {};
    var hasString = false;
    var hasNonString = false;
    var stringValue = '';

    for (var prop in source) {
      if (prop == '@') {
        continue;
      } else {
        if (prop === '#' || prop === 'string' || prop.substring(prop.length - 7) === ':string') {
          hasString = true;
          stringValue = source[prop];
        } else {
          hasNonString = true;
        }
        target[prop] = clean(source[prop]);
      }
    }
    if (hasString && !hasNonString) {
      return stringValue;
    }
    return target;
  }

  function logEachData(title, data) {
    var cleaned = clean(data);
    for (var property in cleaned) {
      log.data(title + ' ' + property, cleaned[property]);
    }
  }
  site.logEachData = logEachData;

  function logError(message, err) {
    if (arguments.length == 1) {
      err = message;
      message = undefined;
    } else {
      log.error(message);
    }

    if (err) {
      if (err.message) {
        //                log.error(err.message);
        log.verbose('stack', err.stack);
        log.json('silly', err);
      }
      else if (err.Message) {
        //                log.error(err.Message);
        log.json('verbose', clean(err));
      }
      else {
        //                log.error(err);
      }
    }
  }

  function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
  }

  function toArray(testObject) {
    return isArray(testObject) ? testObject : typeof testObject === 'undefined' ? [] : [testObject];
  }

  function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }

  function exec(cmd, cb) {
    child_process.exec(cmd, function (err, stdout, stderr) {
      cb(err, {
        stdout: stdout,
        stderr: stderr
      });
    });
  }
};


text:
from __future__ import unicode_literals
from ..mesh import TVTKBaseInterface

def test_TVTKBaseInterface_inputs():
    input_map = dict(ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    )
    inputs = TVTKBaseInterface.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createLog2 = void 0;

var _factory = require("../../utils/factory");

var _collection = require("../../utils/collection");

var _number = require("../../plain/number");

var name = 'log2';
var dependencies = ['typed', 'config', 'Complex'];
var createLog2 =
/* #__PURE__ */
(0, _factory.factory)(name, dependencies, function (_ref) {
  var typed = _ref.typed,
      config = _ref.config,
      Complex = _ref.Complex;

  /**
   * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.log2(x)
   *
   * Examples:
   *
   *    math.log2(0.03125)           // returns -5
   *    math.log2(16)                // returns 4
   *    math.log2(16) / math.log2(2) // returns 4
   *    math.pow(2, 4)               // returns 16
   *
   * See also:
   *
   *    exp, log, log1p, log10
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the logarithm.
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            Returns the 2-base logarithm of `x`
   */
  var log2 = typed(name, {
    number: function number(x) {
      if (x >= 0 || config.predictable) {
        return (0, _number.log2Number)(x);
      } else {
        // negative value -> complex value computation
        return _log2Complex(new Complex(x, 0));
      }
    },
    Complex: _log2Complex,
    BigNumber: function BigNumber(x) {
      if (!x.isNegative() || config.predictable) {
        return x.log(2);
      } else {
        // downgrade to number, return Complex valued result
        return _log2Complex(new Complex(x.toNumber(), 0));
      }
    },
    'Array | Matrix': function ArrayMatrix(x) {
      return (0, _collection.deepMap)(x, log2);
    }
  });
  /**
   * Calculate log2 for a complex value
   * @param {Complex} x
   * @returns {Complex}
   * @private
   */

  function _log2Complex(x) {
    var newX = Math.sqrt(x.re * x.re + x.im * x.im);
    return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2);
  }

  return log2;
});
exports.createLog2 = createLog2;


text:
package edu.rice.habanero.actors

import java.util.concurrent.ForkJoinPool.ManagedBlocker
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.{ConcurrentLinkedQueue, ForkJoinPool}

import edu.rice.hj.runtime.config.HjSystemProperty
import edu.rice.hj.runtime.util.ModCountDownLatch
import fj.Effect
import fj.control.parallel.{Actor, Strategy}

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Promise}

/**
 *
 * @author Shams Imam (shams@rice.edu)
 */
object FuncJavaActorState {

  val actorLatch = new ModCountDownLatch(0)

  def awaitTermination() {
    try {
      actorLatch.await()
    } catch {
      case ex: InterruptedException => {
        ex.printStackTrace()
      }
    }
  }
}

object FuncJavaPool {

  var executors = {
    val workers: Int = HjSystemProperty.numWorkers.getPropertyValue.toInt
    new ForkJoinPool(workers)
  }

  def await[A](aPromise: Promise[A]): A = {
    val blocker = new ManagedBlocker {
      override def block(): Boolean = {
        Await.result(aPromise.future, Duration.Inf)
        true
      }

      override def isReleasable(): Boolean = {
        aPromise.isCompleted
      }
    }
    ForkJoinPool.managedBlock(blocker)
    val res = Await.result(aPromise.future, Duration.Inf)
    res
  }

  def shutdown(): Unit = executors.shutdown()
}

abstract class FuncJavaActor[MsgType] {

  private val startTracker = new AtomicBoolean(false)
  private val exitTracker = new AtomicBoolean(false)

  // Lock to ensure the actor only acts on one message at a time
  private val suspended = new AtomicBoolean(false)

  // Queue to hold pending messages
  private val mbox = new ConcurrentLinkedQueue[MsgType]()

  private val strategy = Strategy.executorStrategy[fj.Unit](FuncJavaPool.executors)
  private val effect = new Effect[MsgType] {
    override def e(msg: MsgType): Unit = receive(msg)
  }

  // Product so the actor can use its strategy (to act on messages in other threads, to handle exceptions, etc.)
  private val processor: fj.P1[fj.Unit] = new fj.P1[fj.Unit]() {
    def _1(): fj.Unit = {
      // get next item from queue
      val a: MsgType = mbox.poll()
      // if there is one, process it
      if (a != null) {
        effect.e(a)
        // try again, in case there are more messages
        strategy.par(this)
      } else {
        // clear the lock
        suspended.set(true)
        // work again, in case someone else queued up a message while we were holding the lock
        work()
      }
      fj.Unit.unit()
    }
  }

  // The FunctionJava queued actor to which the messages are delegated
  private val fjActor = {

    // inspired from fj.control.parallel.Actor#queueActor() method
    Actor.actor[MsgType](Strategy.seqStrategy[fj.Unit](), new Effect[MsgType]() {

      // Effect's body -- queues up a message and tries to un-suspend the actor
      override def e(msg: MsgType): Unit = {
        mbox.offer(msg)
        work()
      }
    })
  }

  // If there are pending messages, use the strategy to run the processor
  def work(): Unit = {
    if (!mbox.isEmpty && suspended.compareAndSet(true, false)) {
      strategy.par(processor)
    }
  }

  final def receive(msg: MsgType): Unit = {
    if (!exitTracker.get()) {
      process(msg)
    }
  }

  def process(msg: MsgType): Unit

  def send(msg: MsgType) {
    fjActor.act(msg)
  }

  final def hasStarted() = {
    startTracker.get()
  }

  final def start() = {
    if (!hasStarted()) {
      FuncJavaActorState.actorLatch.updateCount()
      onPreStart()
      onPostStart()
      startTracker.set(true)

      // allow fjActor to start acting on messages
      suspended.set(true)
      work()
    }
  }

  /**
   * Convenience: specify code to be executed before actor is started
   */
  protected def onPreStart() = {
  }

  /**
   * Convenience: specify code to be executed after actor is started
   */
  protected def onPostStart() = {
  }

  final def hasExited() = {
    exitTracker.get()
  }

  final def exit() = {
    val success = exitTracker.compareAndSet(false, true)
    if (success) {
      onPreExit()
      onPostExit()
      FuncJavaActorState.actorLatch.countDown()
    }
  }

  /**
   * Convenience: specify code to be executed before actor is terminated
   */
  protected def onPreExit() = {
  }

  /**
   * Convenience: specify code to be executed after actor is terminated
   */
  protected def onPostExit() = {
  }
}


text:
package org.redisson.remote;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 * @author Nikita Koksharov
 *
 */
public class ResponseEntry {

    public static class Result {

        private final CompletableFuture<? extends RRemoteServiceResponse> promise;
        private final ScheduledFuture<?> responseTimeoutFuture;

        public Result(CompletableFuture<? extends RRemoteServiceResponse> promise, ScheduledFuture<?> responseTimeoutFuture) {
            super();
            this.promise = promise;
            this.responseTimeoutFuture = responseTimeoutFuture;
        }

        public <T extends RRemoteServiceResponse> CompletableFuture<T> getPromise() {
            return (CompletableFuture<T>) promise;
        }

        public ScheduledFuture<?> getResponseTimeoutFuture() {
            return responseTimeoutFuture;
        }

    }

    private final Map<String, List<Result>> responses = new HashMap<String, List<Result>>();
    private final AtomicBoolean started = new AtomicBoolean();

    public Map<String, List<Result>> getResponses() {
        return responses;
    }

    public AtomicBoolean getStarted() {
        return started;
    }

}


text:
A small example for logging frontend JavaScript exceptions

## Prerequisites

* NodeJS

## Running the code

Just `cd` to the project directory run `npm install` followed by `node index.js`.
The server will launch and you can access the website by visiting `http://localhost:3000/static`

## Logs

Following JSON will be sent to the server on JavaScript errors:

```javascript
{
   "msg": "Uncaught ReferenceError: a is not defined",
   "fingerprint": "38602aaafc4c5682ee3ff45079482bcf",
   "trace":[
      {
         "functionName": "HTMLButtonElement.onclick",
         "fileName": "http://localhost:3000/static/",
         "lineNumber": 11,
         "columnNumber": 25,
         "source": "    at HTMLButtonElement.onclick (http://localhost:3000/static/:11:25)"
      }
   ],
   "platform": {
      "browser": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
      "cookiesEnabled": true
   }
}
```


text:
set -e

[ -z "${PAX}" ] && echo "Environment variable PAX must point to a clone of the Pax repo" && exit 2

# NOTE to not have any symbols, instead of an empty ${DEFINE} use a dud one like "NOTHING"
if [ -z "${DEFINE}" ]
then
  # Default symbols
  DEFINE="DEBUG TRACE LITE"
fi

xbuild Pax_Lite.csproj /t:Rebuild /p:DefineConstants="${DEFINE}"
xbuild Pax.csproj /p:DefineConstants="${DEFINE}"
xbuild examples/Examples.csproj /p:DefineConstants="${DEFINE}"
xbuild examples/Hub.csproj /p:DefineConstants="${DEFINE}"

echo Success


text:
package com.doctusoft.jsf.comp;

import java.util.ArrayList;

import lombok.Getter;

import com.doctusoft.jsf.comp.model.IsNamingContainer;
import com.doctusoft.jsf.comp.model.IsRepeating;
import com.doctusoft.jsf.comp.model.JsfAjaxBehaviorModel;
import com.doctusoft.jsf.comp.model.JsfAjaxTarget;
import com.doctusoft.jsf.comp.model.JsfBaseComponentModel;

public class JsfAjaxBehavior {

	@Getter
	private JsfAjaxBehaviorModel model = new JsfAjaxBehaviorModel();

	protected void ensureExecuteList() {
		if (model.getExecute() == null) {
			model.setExecute(new ArrayList<JsfAjaxTarget>());
		}
	}

	/**
	 * nb: automatic id resolution is only partially possible, see {@link #resolveIdPart(JsfBaseComponent)}
	 */
	public JsfAjaxBehavior execute(JsfBaseComponent<?, ?> component) {
		ensureExecuteList();
		model.getExecute().add(new JsfAjaxTarget(component.getModel()));
		return this;
	}

	public JsfAjaxBehavior execute(String execute) {
		ensureExecuteList();
		model.getExecute().add(new JsfAjaxTarget(execute));
		return this;
	}

	/**
	 * nb: automatic id resolution is only partially possible, see {@link #resolveIdPart(JsfBaseComponent)}
	 */
	public JsfAjaxBehavior render(JsfBaseComponent<?, ?> component) {
		ensureRenderList();
		model.getRender().add(new JsfAjaxTarget(component.getModel()));
		return this;
	}

	/**
	 * nb: a qualified id chain cannot be resolved through repeating components.
	 */
	public static String resolveIdPart(final JsfBaseComponentModel model) {
		String id = "";
		JsfBaseComponentModel item = model;
		while (item != null) {
			if (item.getRootIdChain() != null) {
				id = item.getRootIdChain();
				break;
			} else if (item instanceof IsNamingContainer) {
				if (item instanceof IsRepeating)
					throw new RuntimeException("Cannot resolve the qualified id of this component, because it's contained in a repeating container");
				id = ":" + item.getId() + id;
			}
			item = item.getParent();
		}
		id += ":" + model.getId();
		return id;
	}

	public JsfAjaxBehavior render(String render) {
		ensureRenderList();
		model.getRender().add(new JsfAjaxTarget(render));
		return this;
	}

	protected void ensureRenderList() {
		if (model.getRender() == null) {
			model.setRender(new ArrayList<JsfAjaxTarget>());
		}
	}

	public JsfAjaxBehavior withEvent(String event) {
		model.setEvent(event);
		return this;
	}

	public JsfAjaxBehavior applyOn(JsfBaseComponent<?, ?> component) {
		component.withAjax(this);
		return this;
	}

}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * Represents a Cloud VPN Tunnel resource.
 *
 * For more information about VPN, read the the Cloud VPN Overview. (== resource_for beta.vpnTunnels
 * ==) (== resource_for v1.vpnTunnels ==)
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VpnTunnel extends com.google.api.client.json.GenericJson {

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String creationTimestamp;

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String description;

  /**
   * [Output Only] Detailed status message for the VPN tunnel.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String detailedStatus;

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.math.BigInteger id;

  /**
   * IKE protocol version to use when establishing the VPN tunnel with the peer VPN gateway.
   * Acceptable IKE versions are 1 or 2. The default version is 2.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer ikeVersion;

  /**
   * [Output Only] Type of resource. Always compute#vpnTunnel for VPN tunnels.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * Local traffic selector to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges must be
   * disjoint. Only IPv4 is supported.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> localTrafficSelector;

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * URL of the peer side external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created. This field is exclusive with the field
   * peerGcpGateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String peerExternalGateway;

  /**
   * The interface ID of the external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer peerExternalGatewayInterface;

  /**
   * URL of the peer side HA GCP VPN gateway to which this VPN tunnel is connected. Provided by the
   * client when the VPN tunnel is created. This field can be used when creating highly available
   * VPN from VPC network to VPC network, the field is exclusive with the field peerExternalGateway.
   * If provided, the VPN tunnel will automatically use the same vpnGatewayInterface ID in the peer
   * GCP VPN gateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String peerGcpGateway;

  /**
   * IP address of the peer VPN gateway. Only IPv4 is supported.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String peerIp;

  /**
   * [Output Only] URL of the region where the VPN tunnel resides. You must specify this field as
   * part of the HTTP request URL. It is not settable as a field in the request body.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String region;

  /**
   * Remote traffic selectors to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be
   * disjoint. Only IPv4 is supported.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> remoteTrafficSelector;

  /**
   * URL of the router resource to be used for dynamic routing.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String router;

  /**
   * [Output Only] Server-defined URL for the resource.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String selfLink;

  /**
   * Shared secret used to set the secure session between the Cloud VPN gateway and the peer VPN
   * gateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String sharedSecret;

  /**
   * Hash of the shared secret.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String sharedSecretHash;

  /**
   * [Output Only] The status of the VPN tunnel, which can be one of the following: - PROVISIONING:
   * Resource is being allocated for the VPN tunnel.  - WAITING_FOR_FULL_CONFIG: Waiting to receive
   * all VPN-related configs from the user. Network, TargetVpnGateway, VpnTunnel, ForwardingRule,
   * and Route resources are needed to setup the VPN tunnel.  - FIRST_HANDSHAKE: Successful first
   * handshake with the peer VPN.  - ESTABLISHED: Secure session is successfully established with
   * the peer VPN.  - NETWORK_ERROR: Deprecated, replaced by NO_INCOMING_PACKETS  -
   * AUTHORIZATION_ERROR: Auth error (for example, bad shared secret).  - NEGOTIATION_FAILURE:
   * Handshake failed.  - DEPROVISIONING: Resources are being deallocated for the VPN tunnel.  -
   * FAILED: Tunnel creation has failed and the tunnel is not ready to be used.  -
   * NO_INCOMING_PACKETS: No incoming packets from peer.  - REJECTED: Tunnel configuration was
   * rejected, can be result of being blacklisted.  - ALLOCATING_RESOURCES: Cloud VPN is in the
   * process of allocating all required resources.  - STOPPED: Tunnel is stopped due to its
   * Forwarding Rules being deleted for Classic VPN tunnels or the project is in frozen state.  -
   * PEER_IDENTITY_MISMATCH: Peer identity does not match peer IP, probably behind NAT.  -
   * TS_NARROWING_NOT_ALLOWED: Traffic selector narrowing not allowed for an HA-VPN tunnel.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String status;

  /**
   * URL of the Target VPN gateway with which this VPN tunnel is associated. Provided by the client
   * when the VPN tunnel is created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String targetVpnGateway;

  /**
   * URL of the VPN gateway with which this VPN tunnel is associated. Provided by the client when
   * the VPN tunnel is created. This must be used (instead of target_vpn_gateway) if a High
   * Availability VPN gateway resource is created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String vpnGateway;

  /**
   * The interface ID of the VPN gateway with which this VPN tunnel is associated.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer vpnGatewayInterface;

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * @return value or {@code null} for none
   */
  public java.lang.String getCreationTimestamp() {
    return creationTimestamp;
  }

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * @param creationTimestamp creationTimestamp or {@code null} for none
   */
  public VpnTunnel setCreationTimestamp(java.lang.String creationTimestamp) {
    this.creationTimestamp = creationTimestamp;
    return this;
  }

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * @return value or {@code null} for none
   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * @param description description or {@code null} for none
   */
  public VpnTunnel setDescription(java.lang.String description) {
    this.description = description;
    return this;
  }

  /**
   * [Output Only] Detailed status message for the VPN tunnel.
   * @return value or {@code null} for none
   */
  public java.lang.String getDetailedStatus() {
    return detailedStatus;
  }

  /**
   * [Output Only] Detailed status message for the VPN tunnel.
   * @param detailedStatus detailedStatus or {@code null} for none
   */
  public VpnTunnel setDetailedStatus(java.lang.String detailedStatus) {
    this.detailedStatus = detailedStatus;
    return this;
  }

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * @return value or {@code null} for none
   */
  public java.math.BigInteger getId() {
    return id;
  }

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * @param id id or {@code null} for none
   */
  public VpnTunnel setId(java.math.BigInteger id) {
    this.id = id;
    return this;
  }

  /**
   * IKE protocol version to use when establishing the VPN tunnel with the peer VPN gateway.
   * Acceptable IKE versions are 1 or 2. The default version is 2.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getIkeVersion() {
    return ikeVersion;
  }

  /**
   * IKE protocol version to use when establishing the VPN tunnel with the peer VPN gateway.
   * Acceptable IKE versions are 1 or 2. The default version is 2.
   * @param ikeVersion ikeVersion or {@code null} for none
   */
  public VpnTunnel setIkeVersion(java.lang.Integer ikeVersion) {
    this.ikeVersion = ikeVersion;
    return this;
  }

  /**
   * [Output Only] Type of resource. Always compute#vpnTunnel for VPN tunnels.
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * [Output Only] Type of resource. Always compute#vpnTunnel for VPN tunnels.
   * @param kind kind or {@code null} for none
   */
  public VpnTunnel setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * Local traffic selector to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges must be
   * disjoint. Only IPv4 is supported.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getLocalTrafficSelector() {
    return localTrafficSelector;
  }

  /**
   * Local traffic selector to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges must be
   * disjoint. Only IPv4 is supported.
   * @param localTrafficSelector localTrafficSelector or {@code null} for none
   */
  public VpnTunnel setLocalTrafficSelector(java.util.List<java.lang.String> localTrafficSelector) {
    this.localTrafficSelector = localTrafficSelector;
    return this;
  }

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * @param name name or {@code null} for none
   */
  public VpnTunnel setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * URL of the peer side external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created. This field is exclusive with the field
   * peerGcpGateway.
   * @return value or {@code null} for none
   */
  public java.lang.String getPeerExternalGateway() {
    return peerExternalGateway;
  }

  /**
   * URL of the peer side external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created. This field is exclusive with the field
   * peerGcpGateway.
   * @param peerExternalGateway peerExternalGateway or {@code null} for none
   */
  public VpnTunnel setPeerExternalGateway(java.lang.String peerExternalGateway) {
    this.peerExternalGateway = peerExternalGateway;
    return this;
  }

  /**
   * The interface ID of the external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getPeerExternalGatewayInterface() {
    return peerExternalGatewayInterface;
  }

  /**
   * The interface ID of the external VPN gateway to which this VPN tunnel is connected. Provided by
   * the client when the VPN tunnel is created.
   * @param peerExternalGatewayInterface peerExternalGatewayInterface or {@code null} for none
   */
  public VpnTunnel setPeerExternalGatewayInterface(java.lang.Integer peerExternalGatewayInterface) {
    this.peerExternalGatewayInterface = peerExternalGatewayInterface;
    return this;
  }

  /**
   * URL of the peer side HA GCP VPN gateway to which this VPN tunnel is connected. Provided by the
   * client when the VPN tunnel is created. This field can be used when creating highly available
   * VPN from VPC network to VPC network, the field is exclusive with the field peerExternalGateway.
   * If provided, the VPN tunnel will automatically use the same vpnGatewayInterface ID in the peer
   * GCP VPN gateway.
   * @return value or {@code null} for none
   */
  public java.lang.String getPeerGcpGateway() {
    return peerGcpGateway;
  }

  /**
   * URL of the peer side HA GCP VPN gateway to which this VPN tunnel is connected. Provided by the
   * client when the VPN tunnel is created. This field can be used when creating highly available
   * VPN from VPC network to VPC network, the field is exclusive with the field peerExternalGateway.
   * If provided, the VPN tunnel will automatically use the same vpnGatewayInterface ID in the peer
   * GCP VPN gateway.
   * @param peerGcpGateway peerGcpGateway or {@code null} for none
   */
  public VpnTunnel setPeerGcpGateway(java.lang.String peerGcpGateway) {
    this.peerGcpGateway = peerGcpGateway;
    return this;
  }

  /**
   * IP address of the peer VPN gateway. Only IPv4 is supported.
   * @return value or {@code null} for none
   */
  public java.lang.String getPeerIp() {
    return peerIp;
  }

  /**
   * IP address of the peer VPN gateway. Only IPv4 is supported.
   * @param peerIp peerIp or {@code null} for none
   */
  public VpnTunnel setPeerIp(java.lang.String peerIp) {
    this.peerIp = peerIp;
    return this;
  }

  /**
   * [Output Only] URL of the region where the VPN tunnel resides. You must specify this field as
   * part of the HTTP request URL. It is not settable as a field in the request body.
   * @return value or {@code null} for none
   */
  public java.lang.String getRegion() {
    return region;
  }

  /**
   * [Output Only] URL of the region where the VPN tunnel resides. You must specify this field as
   * part of the HTTP request URL. It is not settable as a field in the request body.
   * @param region region or {@code null} for none
   */
  public VpnTunnel setRegion(java.lang.String region) {
    this.region = region;
    return this;
  }

  /**
   * Remote traffic selectors to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be
   * disjoint. Only IPv4 is supported.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getRemoteTrafficSelector() {
    return remoteTrafficSelector;
  }

  /**
   * Remote traffic selectors to use when establishing the VPN tunnel with the peer VPN gateway. The
   * value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be
   * disjoint. Only IPv4 is supported.
   * @param remoteTrafficSelector remoteTrafficSelector or {@code null} for none
   */
  public VpnTunnel setRemoteTrafficSelector(java.util.List<java.lang.String> remoteTrafficSelector) {
    this.remoteTrafficSelector = remoteTrafficSelector;
    return this;
  }

  /**
   * URL of the router resource to be used for dynamic routing.
   * @return value or {@code null} for none
   */
  public java.lang.String getRouter() {
    return router;
  }

  /**
   * URL of the router resource to be used for dynamic routing.
   * @param router router or {@code null} for none
   */
  public VpnTunnel setRouter(java.lang.String router) {
    this.router = router;
    return this;
  }

  /**
   * [Output Only] Server-defined URL for the resource.
   * @return value or {@code null} for none
   */
  public java.lang.String getSelfLink() {
    return selfLink;
  }

  /**
   * [Output Only] Server-defined URL for the resource.
   * @param selfLink selfLink or {@code null} for none
   */
  public VpnTunnel setSelfLink(java.lang.String selfLink) {
    this.selfLink = selfLink;
    return this;
  }

  /**
   * Shared secret used to set the secure session between the Cloud VPN gateway and the peer VPN
   * gateway.
   * @return value or {@code null} for none
   */
  public java.lang.String getSharedSecret() {
    return sharedSecret;
  }

  /**
   * Shared secret used to set the secure session between the Cloud VPN gateway and the peer VPN
   * gateway.
   * @param sharedSecret sharedSecret or {@code null} for none
   */
  public VpnTunnel setSharedSecret(java.lang.String sharedSecret) {
    this.sharedSecret = sharedSecret;
    return this;
  }

  /**
   * Hash of the shared secret.
   * @return value or {@code null} for none
   */
  public java.lang.String getSharedSecretHash() {
    return sharedSecretHash;
  }

  /**
   * Hash of the shared secret.
   * @param sharedSecretHash sharedSecretHash or {@code null} for none
   */
  public VpnTunnel setSharedSecretHash(java.lang.String sharedSecretHash) {
    this.sharedSecretHash = sharedSecretHash;
    return this;
  }

  /**
   * [Output Only] The status of the VPN tunnel, which can be one of the following: - PROVISIONING:
   * Resource is being allocated for the VPN tunnel.  - WAITING_FOR_FULL_CONFIG: Waiting to receive
   * all VPN-related configs from the user. Network, TargetVpnGateway, VpnTunnel, ForwardingRule,
   * and Route resources are needed to setup the VPN tunnel.  - FIRST_HANDSHAKE: Successful first
   * handshake with the peer VPN.  - ESTABLISHED: Secure session is successfully established with
   * the peer VPN.  - NETWORK_ERROR: Deprecated, replaced by NO_INCOMING_PACKETS  -
   * AUTHORIZATION_ERROR: Auth error (for example, bad shared secret).  - NEGOTIATION_FAILURE:
   * Handshake failed.  - DEPROVISIONING: Resources are being deallocated for the VPN tunnel.  -
   * FAILED: Tunnel creation has failed and the tunnel is not ready to be used.  -
   * NO_INCOMING_PACKETS: No incoming packets from peer.  - REJECTED: Tunnel configuration was
   * rejected, can be result of being blacklisted.  - ALLOCATING_RESOURCES: Cloud VPN is in the
   * process of allocating all required resources.  - STOPPED: Tunnel is stopped due to its
   * Forwarding Rules being deleted for Classic VPN tunnels or the project is in frozen state.  -
   * PEER_IDENTITY_MISMATCH: Peer identity does not match peer IP, probably behind NAT.  -
   * TS_NARROWING_NOT_ALLOWED: Traffic selector narrowing not allowed for an HA-VPN tunnel.
   * @return value or {@code null} for none
   */
  public java.lang.String getStatus() {
    return status;
  }

  /**
   * [Output Only] The status of the VPN tunnel, which can be one of the following: - PROVISIONING:
   * Resource is being allocated for the VPN tunnel.  - WAITING_FOR_FULL_CONFIG: Waiting to receive
   * all VPN-related configs from the user. Network, TargetVpnGateway, VpnTunnel, ForwardingRule,
   * and Route resources are needed to setup the VPN tunnel.  - FIRST_HANDSHAKE: Successful first
   * handshake with the peer VPN.  - ESTABLISHED: Secure session is successfully established with
   * the peer VPN.  - NETWORK_ERROR: Deprecated, replaced by NO_INCOMING_PACKETS  -
   * AUTHORIZATION_ERROR: Auth error (for example, bad shared secret).  - NEGOTIATION_FAILURE:
   * Handshake failed.  - DEPROVISIONING: Resources are being deallocated for the VPN tunnel.  -
   * FAILED: Tunnel creation has failed and the tunnel is not ready to be used.  -
   * NO_INCOMING_PACKETS: No incoming packets from peer.  - REJECTED: Tunnel configuration was
   * rejected, can be result of being blacklisted.  - ALLOCATING_RESOURCES: Cloud VPN is in the
   * process of allocating all required resources.  - STOPPED: Tunnel is stopped due to its
   * Forwarding Rules being deleted for Classic VPN tunnels or the project is in frozen state.  -
   * PEER_IDENTITY_MISMATCH: Peer identity does not match peer IP, probably behind NAT.  -
   * TS_NARROWING_NOT_ALLOWED: Traffic selector narrowing not allowed for an HA-VPN tunnel.
   * @param status status or {@code null} for none
   */
  public VpnTunnel setStatus(java.lang.String status) {
    this.status = status;
    return this;
  }

  /**
   * URL of the Target VPN gateway with which this VPN tunnel is associated. Provided by the client
   * when the VPN tunnel is created.
   * @return value or {@code null} for none
   */
  public java.lang.String getTargetVpnGateway() {
    return targetVpnGateway;
  }

  /**
   * URL of the Target VPN gateway with which this VPN tunnel is associated. Provided by the client
   * when the VPN tunnel is created.
   * @param targetVpnGateway targetVpnGateway or {@code null} for none
   */
  public VpnTunnel setTargetVpnGateway(java.lang.String targetVpnGateway) {
    this.targetVpnGateway = targetVpnGateway;
    return this;
  }

  /**
   * URL of the VPN gateway with which this VPN tunnel is associated. Provided by the client when
   * the VPN tunnel is created. This must be used (instead of target_vpn_gateway) if a High
   * Availability VPN gateway resource is created.
   * @return value or {@code null} for none
   */
  public java.lang.String getVpnGateway() {
    return vpnGateway;
  }

  /**
   * URL of the VPN gateway with which this VPN tunnel is associated. Provided by the client when
   * the VPN tunnel is created. This must be used (instead of target_vpn_gateway) if a High
   * Availability VPN gateway resource is created.
   * @param vpnGateway vpnGateway or {@code null} for none
   */
  public VpnTunnel setVpnGateway(java.lang.String vpnGateway) {
    this.vpnGateway = vpnGateway;
    return this;
  }

  /**
   * The interface ID of the VPN gateway with which this VPN tunnel is associated.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getVpnGatewayInterface() {
    return vpnGatewayInterface;
  }

  /**
   * The interface ID of the VPN gateway with which this VPN tunnel is associated.
   * @param vpnGatewayInterface vpnGatewayInterface or {@code null} for none
   */
  public VpnTunnel setVpnGatewayInterface(java.lang.Integer vpnGatewayInterface) {
    this.vpnGatewayInterface = vpnGatewayInterface;
    return this;
  }

  @Override
  public VpnTunnel set(String fieldName, Object value) {
    return (VpnTunnel) super.set(fieldName, value);
  }

  @Override
  public VpnTunnel clone() {
    return (VpnTunnel) super.clone();
  }

}


text:
.class public abstract Lcom/google/inject/internal/util/$ImmutableSet;
.super Lcom/google/inject/internal/util/$ImmutableCollection;
.source "ImmutableSet.java"

# interfaces
.implements Ljava/util/Set;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/inject/internal/util/$ImmutableSet$1;,
        Lcom/google/inject/internal/util/$ImmutableSet$Builder;,
        Lcom/google/inject/internal/util/$ImmutableSet$SerializedForm;,
        Lcom/google/inject/internal/util/$ImmutableSet$TransformedImmutableSet;,
        Lcom/google/inject/internal/util/$ImmutableSet$RegularImmutableSet;,
        Lcom/google/inject/internal/util/$ImmutableSet$ArrayImmutableSet;,
        Lcom/google/inject/internal/util/$ImmutableSet$SingletonImmutableSet;,
        Lcom/google/inject/internal/util/$ImmutableSet$EmptyImmutableSet;
    }
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<E:",
        "Ljava/lang/Object;",
        ">",
        "Lcom/google/inject/internal/util/$ImmutableCollection",
        "<TE;>;",
        "Ljava/util/Set",
        "<TE;>;"
    }
.end annotation

# static fields
.field private static final EMPTY_IMMUTABLE_SET:Lcom/google/inject/internal/util/$ImmutableSet;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<*>;"
        }
    .end annotation
.end field

# direct methods
.method static constructor <clinit>()V
    .locals 2

    .prologue
    .line 62
    new-instance v0, Lcom/google/inject/internal/util/$ImmutableSet$EmptyImmutableSet;

    const/4 v1, 0x0

    invoke-direct {v0, v1}, Lcom/google/inject/internal/util/$ImmutableSet$EmptyImmutableSet;-><init>(Lcom/google/inject/internal/util/$ImmutableSet$1;)V

    sput-object v0, Lcom/google/inject/internal/util/$ImmutableSet;->EMPTY_IMMUTABLE_SET:Lcom/google/inject/internal/util/$ImmutableSet;

    return-void
.end method

.method constructor <init>()V
    .locals 0

    .prologue
    .line 160
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    invoke-direct {p0}, Lcom/google/inject/internal/util/$ImmutableCollection;-><init>()V

    return-void
.end method

.method public static builder()Lcom/google/inject/internal/util/$ImmutableSet$Builder;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">()",
            "Lcom/google/inject/internal/util/$ImmutableSet$Builder",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 549
    new-instance v0, Lcom/google/inject/internal/util/$ImmutableSet$Builder;

    invoke-direct {v0}, Lcom/google/inject/internal/util/$ImmutableSet$Builder;-><init>()V

    return-object v0
.end method

.method public static copyOf(Ljava/lang/Iterable;)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">(",
            "Ljava/lang/Iterable",
            "<+TE;>;)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 125
    .local p0, "elements":Ljava/lang/Iterable;, "Ljava/lang/Iterable<+TE;>;"
    instance-of v1, p0, Lcom/google/inject/internal/util/$ImmutableSet;

    if-eqz v1, :cond_0

    move-object v0, p0

    .line 127
    check-cast v0, Lcom/google/inject/internal/util/$ImmutableSet;

    .line 130
    :goto_0
    return-object v0

    :cond_0
    invoke-static {p0}, Lcom/google/inject/internal/util/$Collections2;->toCollection(Ljava/lang/Iterable;)Ljava/util/Collection;

    move-result-object v1

    invoke-static {v1}, Lcom/google/inject/internal/util/$ImmutableSet;->copyOfInternal(Ljava/util/Collection;)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    goto :goto_0
.end method

.method public static copyOf(Ljava/util/Iterator;)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">(",
            "Ljava/util/Iterator",
            "<+TE;>;)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 141
    .local p0, "elements":Ljava/util/Iterator;, "Ljava/util/Iterator<+TE;>;"
    invoke-static {p0}, Lcom/google/inject/internal/util/$Lists;->newArrayList(Ljava/util/Iterator;)Ljava/util/ArrayList;

    move-result-object v0

    .line 142
    .local v0, "list":Ljava/util/Collection;, "Ljava/util/Collection<TE;>;"
    invoke-static {v0}, Lcom/google/inject/internal/util/$ImmutableSet;->copyOfInternal(Ljava/util/Collection;)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v1

    return-object v1
.end method

.method private static copyOfInternal(Ljava/util/Collection;)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">(",
            "Ljava/util/Collection",
            "<+TE;>;)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 149
    .local p0, "collection":Ljava/util/Collection;, "Ljava/util/Collection<+TE;>;"
    invoke-interface {p0}, Ljava/util/Collection;->size()I

    move-result v0

    packed-switch v0, :pswitch_data_0

    .line 156
    invoke-interface {p0}, Ljava/util/Collection;->size()I

    move-result v0

    invoke-static {p0, v0}, Lcom/google/inject/internal/util/$ImmutableSet;->create(Ljava/lang/Iterable;I)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    :goto_0
    return-object v0

    .line 151
    :pswitch_0
    invoke-static {}, Lcom/google/inject/internal/util/$ImmutableSet;->of()Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    goto :goto_0

    .line 154
    :pswitch_1
    invoke-interface {p0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    invoke-static {v0}, Lcom/google/inject/internal/util/$ImmutableSet;->of(Ljava/lang/Object;)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    goto :goto_0

    .line 149
    :pswitch_data_0
    .packed-switch 0x0
        :pswitch_0
        :pswitch_1
    .end packed-switch
.end method

.method private static create(Ljava/lang/Iterable;I)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 13
    .param p1, "count"    # I
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">(",
            "Ljava/lang/Iterable",
            "<+TE;>;I)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 332
    .local p0, "iterable":Ljava/lang/Iterable;, "Ljava/lang/Iterable<+TE;>;"
    invoke-static {p1}, Lcom/google/inject/internal/util/$Hashing;->chooseTableSize(I)I

    move-result v9

    .line 333
    .local v9, "tableSize":I
    new-array v8, v9, [Ljava/lang/Object;

    .line 334
    .local v8, "table":[Ljava/lang/Object;
    add-int/lit8 v7, v9, -0x1

    .line 336
    .local v7, "mask":I
    new-instance v1, Ljava/util/ArrayList;

    invoke-direct {v1, p1}, Ljava/util/ArrayList;-><init>(I)V

    .line 337
    .local v1, "elements":Ljava/util/List;, "Ljava/util/List<TE;>;"
    const/4 v3, 0x0

    .line 339
    .local v3, "hashCode":I
    invoke-interface {p0}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v5

    .local v5, "i$":Ljava/util/Iterator;
    :cond_0
    :goto_0
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v11

    if-eqz v11, :cond_2

    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    .line 340
    .local v0, "element":Ljava/lang/Object;, "TE;"
    invoke-virtual {v0}, Ljava/lang/Object;->hashCode()I

    move-result v2

    .line 341
    .local v2, "hash":I
    invoke-static {v2}, Lcom/google/inject/internal/util/$Hashing;->smear(I)I

    move-result v4

    .line 342
    .local v4, "i":I
    :goto_1
    and-int v6, v4, v7

    .line 343
    .local v6, "index":I
    aget-object v10, v8, v6

    .line 344
    .local v10, "value":Ljava/lang/Object;
    if-nez v10, :cond_1

    .line 346
    aput-object v0, v8, v6

    .line 347
    invoke-interface {v1, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 348
    add-int/2addr v3, v2

    .line 349
    goto :goto_0

    .line 350
    :cond_1
    invoke-virtual {v10, v0}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v11

    if-nez v11, :cond_0

    .line 341
    add-int/lit8 v4, v4, 0x1

    goto :goto_1

    .line 357
    .end local v0    # "element":Ljava/lang/Object;, "TE;"
    .end local v2    # "hash":I
    .end local v4    # "i":I
    .end local v6    # "index":I
    .end local v10    # "value":Ljava/lang/Object;
    :cond_2
    invoke-interface {v1}, Ljava/util/List;->size()I

    move-result v11

    const/4 v12, 0x1

    if-ne v11, v12, :cond_3

    new-instance v11, Lcom/google/inject/internal/util/$ImmutableSet$SingletonImmutableSet;

    const/4 v12, 0x0

    invoke-interface {v1, v12}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v12

    invoke-direct {v11, v12, v3}, Lcom/google/inject/internal/util/$ImmutableSet$SingletonImmutableSet;-><init>(Ljava/lang/Object;I)V

    :goto_2
    return-object v11

    :cond_3
    new-instance v11, Lcom/google/inject/internal/util/$ImmutableSet$RegularImmutableSet;

    invoke-interface {v1}, Ljava/util/List;->toArray()[Ljava/lang/Object;

    move-result-object v12

    invoke-direct {v11, v12, v3, v8, v7}, Lcom/google/inject/internal/util/$ImmutableSet$RegularImmutableSet;-><init>([Ljava/lang/Object;I[Ljava/lang/Object;I)V

    goto :goto_2
.end method

.method public static of()Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">()",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 73
    sget-object v0, Lcom/google/inject/internal/util/$ImmutableSet;->EMPTY_IMMUTABLE_SET:Lcom/google/inject/internal/util/$ImmutableSet;

    return-object v0
.end method

.method public static of(Ljava/lang/Object;)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">(TE;)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 83
    .local p0, "element":Ljava/lang/Object;, "TE;"
    new-instance v0, Lcom/google/inject/internal/util/$ImmutableSet$SingletonImmutableSet;

    invoke-virtual {p0}, Ljava/lang/Object;->hashCode()I

    move-result v1

    invoke-direct {v0, p0, v1}, Lcom/google/inject/internal/util/$ImmutableSet$SingletonImmutableSet;-><init>(Ljava/lang/Object;I)V

    return-object v0
.end method

.method public static varargs of([Ljava/lang/Object;)Lcom/google/inject/internal/util/$ImmutableSet;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<E:",
            "Ljava/lang/Object;",
            ">([TE;)",
            "Lcom/google/inject/internal/util/$ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 95
    .local p0, "elements":[Ljava/lang/Object;, "[TE;"
    array-length v0, p0

    packed-switch v0, :pswitch_data_0

    .line 101
    invoke-static {p0}, Ljava/util/Arrays;->asList([Ljava/lang/Object;)Ljava/util/List;

    move-result-object v0

    array-length v1, p0

    invoke-static {v0, v1}, Lcom/google/inject/internal/util/$ImmutableSet;->create(Ljava/lang/Iterable;I)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    :goto_0
    return-object v0

    .line 97
    :pswitch_0
    invoke-static {}, Lcom/google/inject/internal/util/$ImmutableSet;->of()Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    goto :goto_0

    .line 99
    :pswitch_1
    const/4 v0, 0x0

    aget-object v0, p0, v0

    invoke-static {v0}, Lcom/google/inject/internal/util/$ImmutableSet;->of(Ljava/lang/Object;)Lcom/google/inject/internal/util/$ImmutableSet;

    move-result-object v0

    goto :goto_0

    .line 95
    nop

    :pswitch_data_0
    .packed-switch 0x0
        :pswitch_0
        :pswitch_1
    .end packed-switch
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 2
    .param p1, "object"    # Ljava/lang/Object;
        .annotation runtime Lcom/google/inject/internal/util/$Nullable;
        .end annotation
    .end param

    .prologue
    .line 168
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    if-ne p1, p0, :cond_0

    .line 169
    const/4 v0, 0x1

    .line 177
    :goto_0
    return v0

    .line 171
    :cond_0
    instance-of v0, p1, Lcom/google/inject/internal/util/$ImmutableSet;

    if-eqz v0, :cond_1

    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->isHashCodeFast()Z

    move-result v0

    if-eqz v0, :cond_1

    move-object v0, p1

    check-cast v0, Lcom/google/inject/internal/util/$ImmutableSet;

    invoke-virtual {v0}, Lcom/google/inject/internal/util/$ImmutableSet;->isHashCodeFast()Z

    move-result v0

    if-eqz v0, :cond_1

    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->hashCode()I

    move-result v0

    invoke-virtual {p1}, Ljava/lang/Object;->hashCode()I

    move-result v1

    if-eq v0, v1, :cond_1

    .line 175
    const/4 v0, 0x0

    goto :goto_0

    .line 177
    :cond_1
    invoke-static {p0, p1}, Lcom/google/inject/internal/util/$Collections2;->setEquals(Ljava/util/Set;Ljava/lang/Object;)Z

    move-result v0

    goto :goto_0
.end method

.method public hashCode()I
    .locals 4

    .prologue
    .line 181
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    const/4 v0, 0x0

    .line 182
    .local v0, "hashCode":I
    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->iterator()Ljava/util/Iterator;

    move-result-object v1

    .local v1, "i$":Ljava/util/Iterator;
    :goto_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v3

    if-eqz v3, :cond_0

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v2

    .line 183
    .local v2, "o":Ljava/lang/Object;
    invoke-virtual {v2}, Ljava/lang/Object;->hashCode()I

    move-result v3

    add-int/2addr v0, v3

    goto :goto_0

    .line 185
    .end local v2    # "o":Ljava/lang/Object;
    :cond_0
    return v0
.end method

.method isHashCodeFast()Z
    .locals 1

    .prologue
    .line 164
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    const/4 v0, 0x0

    return v0
.end method

.method public abstract iterator()Lcom/google/inject/internal/util/$UnmodifiableIterator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Lcom/google/inject/internal/util/$UnmodifiableIterator",
            "<TE;>;"
        }
    .end annotation
.end method

.method public bridge synthetic iterator()Ljava/util/Iterator;
    .locals 1

    .prologue
    .line 59
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->iterator()Lcom/google/inject/internal/util/$UnmodifiableIterator;

    move-result-object v0

    return-object v0
.end method

.method public toString()Ljava/lang/String;
    .locals 5

    .prologue
    .line 193
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->isEmpty()Z

    move-result v3

    if-eqz v3, :cond_0

    .line 194
    const-string v3, "[]"

    .line 202
    :goto_0
    return-object v3

    .line 196
    :cond_0
    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->iterator()Lcom/google/inject/internal/util/$UnmodifiableIterator;

    move-result-object v1

    .line 197
    .local v1, "iterator":Ljava/util/Iterator;, "Ljava/util/Iterator<TE;>;"
    new-instance v2, Ljava/lang/StringBuilder;

    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->size()I

    move-result v3

    mul-int/lit8 v3, v3, 0x10

    invoke-direct {v2, v3}, Ljava/lang/StringBuilder;-><init>(I)V

    .line 198
    .local v2, "result":Ljava/lang/StringBuilder;
    const/16 v3, 0x5b

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 199
    const/4 v0, 0x1

    .local v0, "i":I
    :goto_1
    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->size()I

    move-result v3

    if-ge v0, v3, :cond_1

    .line 200
    const-string v3, ", "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 199
    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    .line 202
    :cond_1
    const/16 v3, 0x5d

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    goto :goto_0
.end method

.method writeReplace()Ljava/lang/Object;
    .locals 2

    .prologue
    .line 541
    .local p0, "this":Lcom/google/inject/internal/util/$ImmutableSet;, "Lcom/google/inject/internal/util/$ImmutableSet<TE;>;"
    new-instance v0, Lcom/google/inject/internal/util/$ImmutableSet$SerializedForm;

    invoke-virtual {p0}, Lcom/google/inject/internal/util/$ImmutableSet;->toArray()[Ljava/lang/Object;

    move-result-object v1

    invoke-direct {v0, v1}, Lcom/google/inject/internal/util/$ImmutableSet$SerializedForm;-><init>([Ljava/lang/Object;)V

    return-object v0
.end method


text:
namespace Google.Cloud.Dialogflow.V2.Snippets
{
    // [START dialogflow_v2_generated_Agents_DeleteAgent_sync_flattened_resourceNames1]
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dialogflow.V2;

    public sealed partial class GeneratedAgentsClientSnippets
    {
        /// <summary>Snippet for DeleteAgent</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void DeleteAgentResourceNames1()
        {
            // Create client
            AgentsClient agentsClient = AgentsClient.Create();
            // Initialize request argument(s)
            ProjectName parent = ProjectName.FromProject("[PROJECT]");
            // Make the request
            agentsClient.DeleteAgent(parent);
        }
    }
    // [END dialogflow_v2_generated_Agents_DeleteAgent_sync_flattened_resourceNames1]
}