Live Dao requires RESTCLIENTS_MAILMAN_KEY in the settings.py
323403
def _get_url_path(list_name):
    
    access_key = getattr(settings,
                         "RESTCLIENTS_MAILMAN_KEY",
                         "__mock_key__")
    return URL.format(key=access_key, uwnetid=list_name)
230795
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key
    elif isinstance(verifying_key, (str, unicode)):
        try:
            return load_der_public_key(
                verifying_key, backend=crypto_backend)
        except:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception:
                raise ValueError('Invalid verifying key format')
    else:
        raise ValueError('Invalid verification key type')
1071622
def bind(cls, app, *paths, methods=None, name=None, **kwargs):
        
        paths = paths or ['/%s(/{%s})?/?' % (cls.name, cls.name)]
        name = name or "api.%s" % cls.name
        return super(RESTHandler, cls).bind(app, *paths, methods=methods, name=name, **kwargs)
1318377
def start_rest_api(host, port, connection, timeout, registry,
                   client_max_size=None):
    
    loop = asyncio.get_event_loop()
    connection.open()
    app = web.Application(loop=loop, client_max_size=client_max_size)
    app.on_cleanup.append(lambda app: connection.close())

    # Add routes to the web app
    LOGGER.info('Creating handlers for validator at %s', connection.url)

    handler = RouteHandler(loop, connection, timeout, registry)

    app.router.add_post('/batches', handler.submit_batches)
    app.router.add_get('/batch_statuses', handler.list_statuses)
    app.router.add_post('/batch_statuses', handler.list_statuses)

    app.router.add_get('/state', handler.list_state)
    app.router.add_get('/state/{address}', handler.fetch_state)

    app.router.add_get('/blocks', handler.list_blocks)
    app.router.add_get('/blocks/{block_id}', handler.fetch_block)

    app.router.add_get('/batches', handler.list_batches)
    app.router.add_get('/batches/{batch_id}', handler.fetch_batch)

    app.router.add_get('/transactions', handler.list_transactions)
    app.router.add_get(
        '/transactions/{transaction_id}',
        handler.fetch_transaction)

    app.router.add_get('/receipts', handler.list_receipts)
    app.router.add_post('/receipts', handler.list_receipts)

    app.router.add_get('/peers', handler.fetch_peers)
    app.router.add_get('/status', handler.fetch_status)

    subscriber_handler = StateDeltaSubscriberHandler(connection)
    app.router.add_get('/subscriptions', subscriber_handler.subscriptions)
    app.on_shutdown.append(lambda app: subscriber_handler.on_shutdown())

    # Start app
    LOGGER.info('Starting REST API on %s:%s', host, port)

    web.run_app(
        app,
        host=host,
        port=port,
        access_log=LOGGER,
        access_log_format='%r: %s status, %b size, in %Tf s')
1065225
function ConnectionConfig(options, validateCredentials, qaMode, clientInfo)
{
  // if no value is specified for the validate credentials flag, default to true
  if (!Util.exists(validateCredentials))
  {
    validateCredentials = true;
  }

  // check for missing options
  Errors.checkArgumentExists(Util.exists(options),
      ErrorCodes.ERR_CONN_CREATE_MISSING_OPTIONS);

  // check for invalid options
  Errors.checkArgumentValid(Util.isObject(options),
      ErrorCodes.ERR_CONN_CREATE_INVALID_OPTIONS);

  // only validate credentials if necessary
  if (validateCredentials)
  {
    // check for missing username
    Errors.checkArgumentExists(Util.exists(options.username),
        ErrorCodes.ERR_CONN_CREATE_MISSING_USERNAME);

    // check for invalid username
    Errors.checkArgumentValid(Util.isString(options.username),
        ErrorCodes.ERR_CONN_CREATE_INVALID_USERNAME);

    // check for missing password
    Errors.checkArgumentExists(Util.exists(options.password),
        ErrorCodes.ERR_CONN_CREATE_MISSING_PASSWORD);

    // check for invalid password
    Errors.checkArgumentValid(Util.isString(options.password),
        ErrorCodes.ERR_CONN_CREATE_INVALID_PASSWORD);

    // check for missing account
    Errors.checkArgumentExists(Util.exists(options.account),
        ErrorCodes.ERR_CONN_CREATE_MISSING_ACCOUNT);

    // check for invalid account
    Errors.checkArgumentValid(Util.isString(options.account),
        ErrorCodes.ERR_CONN_CREATE_INVALID_ACCOUNT);

    // if region, cloud or any subdomain is included in account, split them
    // into account and region parameters.
    var dotPos = options.account.indexOf('.');
    if (dotPos > 0 && dotPos < options.account.length - 1)
    {
      options.region = options.account.substring(dotPos + 1);
      options.account = options.account.substring(0, dotPos);
    }

    // if no access url is specified, derive it from the account name and the
    // region if one is specified
    if (!Util.exists(options.accessUrl))
    {
      // extract the region if one is specified
      var region = '';
      if (Util.exists(options.region))
      {
        Errors.checkArgumentValid(Util.isString(options.region),
            ErrorCodes.ERR_CONN_CREATE_INVALID_REGION);

        if (options.region === 'us-west-2')
        {
          // if region is us-west-2, no subdomain is required.
          options.region = ''
        }
        else
        {
          // the region will look something like 'eu-central-1'; add a dot to the
          // beginning so we can insert it after the account name when building
          // the access url
          region = '.' + options.region;
        }
      }

      options.accessUrl = Util.format(
          'https://%s%s.snowflakecomputing.com', options.account, region);
    }
  }

  // check for missing accessUrl
  Errors.checkArgumentExists(Util.exists(options.accessUrl),
      ErrorCodes.ERR_CONN_CREATE_MISSING_ACCESS_URL);

  // check for invalid accessUrl
  Errors.checkArgumentValid(Util.isString(options.accessUrl),
      ErrorCodes.ERR_CONN_CREATE_INVALID_ACCESS_URL);

  var proxyHost = options.proxyHost;
  var proxyPort = options.proxyPort;

  // if we're running in node and some proxy information is specified
  var proxy;
  if (Util.isNode() && (Util.exists(proxyHost) || Util.exists(proxyPort)))
  {
    // check for missing proxyHost
    Errors.checkArgumentExists(Util.exists(proxyHost),
        ErrorCodes.ERR_CONN_CREATE_MISSING_PROXY_HOST);

    // check for invalid proxyHost
    Errors.checkArgumentValid(Util.isString(proxyHost),
        ErrorCodes.ERR_CONN_CREATE_INVALID_PROXY_HOST);

    // check for missing proxyPort
    Errors.checkArgumentExists(Util.exists(proxyPort),
        ErrorCodes.ERR_CONN_CREATE_MISSING_PROXY_PORT);

    // check for invalid proxyPort
    Errors.checkArgumentValid(Util.isNumber(proxyPort),
        ErrorCodes.ERR_CONN_CREATE_INVALID_PROXY_PORT);

    proxy =
    {
      host : proxyHost,
      port : proxyPort
    };
  }

  var warehouse = options.warehouse;
  var database  = options.database;
  var schema    = options.schema;
  var role      = options.role;

  // check for invalid warehouse
  if (Util.exists(warehouse))
  {
    Errors.checkArgumentValid(Util.isString(warehouse),
        ErrorCodes.ERR_CONN_CREATE_INVALID_WAREHOUSE);
  }

  // check for invalid database
  if (Util.exists(database))
  {
    Errors.checkArgumentValid(Util.isString(database),
        ErrorCodes.ERR_CONN_CREATE_INVALID_DATABASE);
  }

  // check for invalid schema
  if (Util.exists(schema))
  {
    Errors.checkArgumentValid(Util.isString(schema),
        ErrorCodes.ERR_CONN_CREATE_INVALID_SCHEMA);
  }

  // check for invalid role
  if (Util.exists(role))
  {
    Errors.checkArgumentValid(Util.isString(role),
        ErrorCodes.ERR_CONN_CREATE_INVALID_ROLE);
  }

  // check for invalid streamResult
  var streamResult = options.streamResult;
  if (Util.exists(streamResult))
  {
    Errors.checkArgumentValid(Util.isBoolean(streamResult),
        ErrorCodes.ERR_CONN_CREATE_INVALID_STREAM_RESULT);
  }

  // check for invalid fetchAsString
  var fetchAsString = options.fetchAsString;
  if (Util.exists(fetchAsString))
  {
    // check that the value is an array
    Errors.checkArgumentValid(Util.isArray(fetchAsString),
        ErrorCodes.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING);

    // check that all the array elements are valid
    var invalidValueIndex = NativeTypes.findInvalidValue(fetchAsString);
    Errors.checkArgumentValid(invalidValueIndex === -1,
        ErrorCodes.ERR_CONN_CREATE_INVALID_FETCH_AS_STRING_VALUES,
        JSON.stringify(fetchAsString[invalidValueIndex]));
  }

  // check for invalid clientSessionKeepAlive
  var clientSessionKeepAlive = options.clientSessionKeepAlive;
  if (Util.exists(clientSessionKeepAlive))
  {
    Errors.checkArgumentValid(Util.isBoolean(clientSessionKeepAlive),
        ErrorCodes.ERR_CONN_CREATE_INVALID_KEEP_ALIVE);
  }

  // check for invalid clientSessionKeepAliveHeartbeatFrequency
  var clientSessionKeepAliveHeartbeatFrequency = options.clientSessionKeepAliveHeartbeatFrequency;
  if (Util.exists(clientSessionKeepAliveHeartbeatFrequency))
  {
    Errors.checkArgumentValid(Util.isNumber(clientSessionKeepAliveHeartbeatFrequency),
        ErrorCodes.ERR_CONN_CREATE_INVALID_KEEP_ALIVE_HEARTBEAT_FREQ);
    clientSessionKeepAliveHeartbeatFrequency = Util.validateClientSessionKeepAliveHeartbeatFrequency(clientSessionKeepAliveHeartbeatFrequency, 14400);
  }
  
  // remember if we're in qa mode
  this._qaMode = qaMode;

  // if a client-info argument is specified, validate it
  var clientVersion;
  var clientEnvironment;
  if (Util.exists(clientInfo))
  {
    Errors.assertInternal(Util.isObject(clientInfo));
    Errors.assertInternal(Util.isString(clientInfo.version));
    Errors.assertInternal(Util.isObject(clientInfo.environment));

    clientVersion     = clientInfo.version;
    clientEnvironment = clientInfo.environment;
  }

  /**
   * Returns an object that contains information about the proxy hostname, port,
   * etc. for when http requests are made.
   *
   * @returns {Object}
   */
  this.getProxy = function()
  {
    return proxy;
  };

  /**
   * Returns the warehouse to automatically use once a connection has been
   * established.
   *
   * @returns {String}
   */
  this.getWarehouse = function()
  {
    return warehouse;
  };

  /**
   * Returns the database to automatically use once a connection has been
   * established.
   *
   * @returns {String}
   */
  this.getDatabase = function()
  {
    return database;
  };

  /**
   * Returns the schema to automatically use once a connection has been
   * established.
   *
   * @returns {String}
   */
  this.getSchema = function()
  {
    return schema;
  };

  /**
   * Returns the role to automatically use once a connection has been
   * established.
   *
   * @returns {String}
   */
  this.getRole = function()
  {
    return role;
  };

  /**
   * Returns the streamResult flag.
   *
   * @returns {boolean}
   */
  this.getStreamResult = function()
  {
    return streamResult;
  };

  /**
   * Returns the fetchAsString array.
   *
   * @returns {String[]}
   */
  this.getFetchAsString = function()
  {
    return fetchAsString;
  };

  /**
   * Returns the client type.
   *
   * @returns {String}
   */
  this.getClientType = function()
  {
    return 'JavaScript';
  };

  /**
   * Returns the client version.
   *
   * @returns {String}
   */
  this.getClientVersion = function()
  {
    return clientVersion;
  };

  /**
   * Returns a JSON object containing version information for all the various
   * components of the runtime, e.g. node, v8, openssl, etc.
   *
   * @returns {Object}
   */
  this.getClientEnvironment = function()
  {
    return clientEnvironment;
  };

  /**
   * Returns the client session keep alive setting.
   *
   * @returns {String}
   */
  this.getClientSessionKeepAlive = function()
  {
    return clientSessionKeepAlive;
  };

  /**
   * Returns the client session keep alive heartbeat frequency setting.
   *
   * @returns {String}
   */
  this.getClientSessionKeepAliveHeartbeatFrequency = function()
  {
    return clientSessionKeepAliveHeartbeatFrequency;
  };

  // save config options
  this.username  = options.username;
  this.password  = options.password;
  this.accessUrl = options.accessUrl;
  this.account   = options.account;

  // create the parameters array
  var parameters = createParameters();

  // create a map in which the keys are the parameter names and the values are
  // the corresponding parameters
  var mapParameters = {};
  var index, length, parameter;
  for (index = 0, length = parameters.length; index < length; index++)
  {
    parameter = parameters[index];
    mapParameters[parameter.name] = parameter;

    // initialize the value to the default
    parameter.value = parameter.defaultValue;
  }

  // for each property in the options object that matches a known parameter name
  var propertyName, propertyValue;
  for (propertyName in options)
  {
    if (options.hasOwnProperty(propertyName) &&
        mapParameters.hasOwnProperty(propertyName))
    {
      // if the parameter matching the property is external and the specified
      // value is valid for the parameter, update the parameter value
      propertyValue = options[propertyName];
      parameter = mapParameters[propertyName];
      if (parameter.external && parameter.validate(propertyValue))
      {
        parameter.value = propertyValue;
      }
    }
  }

  // save the parameters map
  this._mapParameters = mapParameters;
}
428912
function(req) {

    var pk = module.exports.parsePk(req);

    // Validate the required `id` parameter
    if (!pk) {

      var err = new Error(
        'No `id` parameter provided.' +
        '(Note: even if the model\'s primary key is not named `id`- ' +
        '`id` should be used as the name of the parameter- it will be ' +
        'mapped to the proper primary key name)'
      );
      err.status = 400;
      throw err;
    }

    return pk;
  }
558475
def initialize_key_source
      detect_key_source
      if args.require_key? && !self.key
        log :error, 'Unable to determine the key, which appears to be required with current args'
        raise Sym::Errors::NoPrivateKeyFound, 'Private key is required when ' + (self.action ? self.action.to_s + 'ypting' : provided_flags.join(', '))
      end
      log :debug, "initialize_key_source: detected key ends with [...#{(key ? key[-5..-1] : 'nil').bold.magenta}]"
      log :debug, "opts: #{self.provided_value_options.to_s.green.bold}"
      log :debug, "flags: #{self.provided_flags.to_s.green.bold}"
    end
1001384
function TwilioConnector(settings) {

    assert(typeof settings === 'object', 'cannot initialize TwilioConnector without a settings object');
    var connector = this;

    var accountSid = this.accountSid = settings.accountSid;
    var authToken = this.authToken = settings.authToken;
    var sgAPIKey = this.sgAPIKey = settings.sgAPIKey;

    twilio = connector.twilio = require('twilio')(accountSid, authToken);
    sgMail = connector.sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(sgAPIKey);
}
135732
function prepareWhere(opt, _modelObj) {
      if (!_modelObj) _modelObj = modelObj;
      if (!_modelObj) return;
      if (typeof _modelObj.isEncrypted !== 'function') {
        _modelObj = storeObj.model(storeObj.camelize(_modelObj.name), true);
      }
      /* Check if crypto is disabled */
      if (opt.crypto === false) return;
      if (typeof opt.where !== 'object' || !opt.where) return;
      let fields = Object.keys(opt.where);
      for (let i = 0, len = fields.length; i < len; i++) {
        let fieldName = fields[i];
        // Check for inner $and operator
        if (fieldName === '$and') {
          let tmp = {
            where: opt.where[fieldName],
            key: opt.key
          };
          prepareWhere(tmp, _modelObj);
          continue;
        }
        // Check for inner $or operator
        if (fieldName === '$or' && opt.where[fieldName] instanceof Array) {
          for (let j = 0, jlen = opt.where[fieldName].length; j < jlen; j++) {
            let tmp = {
              where: opt.where[fieldName][j],
              key: opt.key
            };
            prepareWhere(tmp, _modelObj);
          }
          continue;
        }
        if (!_modelObj.isEncrypted(fieldName)) continue;
        let fieldValue = opt.where[fieldName];
        let fieldValueType = typeof fieldValue;
        if (fieldValueType === 'undefined' || fieldValue === null) continue;
        if (fieldValue instanceof Array) {
          let tmp = [];
          for (let i = 0, len = fieldValue.length; i < len; i++) {
            let val = fieldValue[i],
              type = typeof val;
            if (type === 'number' || type === 'boolean') {
              val = val.toString();
              type = 'string';
            }
            if (type !== 'string') {
              tmp.push(val);
              continue;
            }
            if (crypto.isEncrypted(val)) {
              tmp.push(val);
              continue;
            }
            let enc = crypto.encrypt(val, opt.key);
            if (enc === null) continue;
            tmp.push(enc);
          }
          opt.where[fieldName] = tmp;
        } else if (fieldValueType === 'object') {
          // this is some kind of operator/aggregator
          let $ops = Object.keys(fieldValue);
          for (let j = 0, llen = $ops.length; j < llen; j++) {
            let opName = $ops[j],
              opValue = fieldValue[opName];
            // Special op: %
            if (opName === '$like') {
              if (!crypto.isEncrypted(opValue)) {
                if (opValue.charAt(0) === '%') opValue = opValue.substr(1);
                if (opValue.charAt(opValue.length - 1) === '%') opValue = opValue.substr(0, opValue.length - 1);
                opValue = crypto.encrypt(opValue, opt.key);
                fieldValue[opName] = opValue;
              }
            } else if (INNER_OPERATORS.indexOf(opName) !== -1) {
              if (opValue instanceof Array) {
                for (let k = 0, klen = opValue.length; k < klen; k++) {
                  if (!crypto.isEncrypted(opValue[k])) {
                    let enc = crypto.encrypt(opValue[k], opt.key);
                    if (enc != null) {
                      opValue[k] = enc;
                    }
                  }
                }
              } else if (!crypto.isEncrypted(opValue)) {
                let enc = crypto.encrypt(opValue, opt.key);
                if (enc === null) continue;
                fieldValue[opName] = enc;
              }
            }
          }
        } else {
          if (crypto.isEncrypted(fieldValue)) continue;
          let enc = crypto.encrypt(fieldValue, opt.key);
          if (enc === null) continue;
          opt.where[fieldName] = enc;
        }
      }
    }
524513
static InstallException create(RepositoryException e, Collection<String> featureNames, boolean installingAsset, RestRepositoryConnectionProxy proxy,
                                   boolean defaultRepo, boolean isOpenLiberty) {
        Throwable cause = e;
        Throwable rootCause = e;

        // Check the list of causes of the exception for connection issues
        while ((rootCause = cause.getCause()) != null && cause != rootCause) {
            if (rootCause instanceof UnknownHostException || rootCause instanceof FileNotFoundException || rootCause instanceof ConnectException) {
                return create(e, rootCause, proxy, defaultRepo);
            }
            cause = rootCause;
        }

        if (featureNames != null) {
            if (isCertPathBuilderException(cause))
                return createByKey(InstallException.CONNECTION_FAILED, e, defaultRepo ? "ERROR_FAILED_TO_CONNECT_CAUSED_BY_CERT" : "ERROR_FAILED_TO_CONNECT_REPOS_CAUSED_BY_CERT");

            String featuresListStr = InstallUtils.getFeatureListOutput(featureNames);
            InstallException ie;
            if (isOpenLiberty) {
                ie = create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(installingAsset ? "ERROR_FAILED_TO_RESOLVE_ASSETS" : "ERROR_FAILED_TO_RESOLVE_FEATURES_FOR_OPEN_LIBERTY",
                                                                           featuresListStr),
                            e);
            } else {
                ie = create(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(installingAsset ? "ERROR_FAILED_TO_RESOLVE_ASSETS" : "ERROR_FAILED_TO_RESOLVE_FEATURES",
                                                                           featuresListStr),
                            e);
            }
            ie.setData(featuresListStr);

            return ie;

        } else
            return create(e);
    }
818516
def _reinit_daq_daemons(sender, instance, **kwargs):
    
    if type(instance) is VISADevice:
        post_save.send_robust(sender=Device, instance=instance.visa_device)
    elif type(instance) is VISAVariable:
        post_save.send_robust(sender=Variable, instance=instance.visa_variable)
    elif type(instance) is VISADeviceHandler:
        # todo
        pass
    elif type(instance) is ExtendedVISAVariable:
        post_save.send_robust(sender=Variable, instance=Variable.objects.get(pk=instance.pk))
    elif type(instance) is ExtendedVISADevice:
        post_save.send_robust(sender=Device, instance=Device.objects.get(pk=instance.pk))
881937
function(api, parent, modelDefinition, remainingDepth) {
		this.parentAPI = api;
		this.RESTParent = parent;
		this.childModels = [];

		this.remainingDepth = remainingDepth - 1;

		this.model = modelDefinition.model;
		this.modelRouter = Express.Router();

		this.path = this.model.tableName.toLowerCase();
		this.primaryKey = Helpers.getPrimaryKey(this.model);
		this.associatedBy = Helpers.getAssociatedBy(this.RESTParent, this.model);

		this._initializeOptions(modelDefinition);
		this._initializeRoutes(modelDefinition);

		/**
		 * Array of valid columns in the class minus the primary key
		 * However the primary key is only 'not valid' to be set if it is
		 * marked as auto-generated.
		 */
		this.validColumns = _.keys(this.model.rawAttributes);

		if(this.model.rawAttributes[this.primaryKey]._autoGenerated)
			this.validColumns.splice(this.validColumns.indexOf(this.primaryKey), 1);
	}
1373988
@Override
    public void loadProperties(String restClientName){
        enableDynamicProperties = true;
        setClientName(restClientName);
        loadDefaultValues();
        Configuration props = ConfigurationManager.getConfigInstance().subset(restClientName);
        for (Iterator<String> keys = props.getKeys(); keys.hasNext(); ){
            String key = keys.next();
            String prop = key;
            try {
                if (prop.startsWith(getNameSpace())){
                    prop = prop.substring(getNameSpace().length() + 1);
                }
                setPropertyInternal(prop, getStringValue(props, key));
            } catch (Exception ex) {
                throw new RuntimeException(String.format("Property %s is invalid", prop));
            }
        }
    }
1133728
def create(key_body)
      client.ensure_master_key!

      path = ""
      response = access_keys_post(client.master_key, path, key_body)
      client.process_response(response.code.to_i, response.body)
    end
829269
def run(generate_pks, show_pks, host, port, uri):
    """"""
    app.config['SQLALCHEMY_DATABASE_URI'] = uri
    app.config['SANDMAN_GENERATE_PKS'] = generate_pks
    app.config['SANDMAN_SHOW_PKS'] = show_pks
    app.config['SERVER_HOST'] = host
    app.config['SERVER_PORT'] = port
    activate(name='sandmanctl')
    app.run(host=host, port=int(port), debug=True)
797801
def init_config(cls):
        
        try:
            # first load current conf and only overwrite needed params
            # we don't want to reset everything
            config_file = os.path.expanduser(cls.home_config)
            config = cls.load(config_file, 'global')
            cls._del('global', 'api.env')

            hidden_apikey = '%s...' % cls.get('api.key', '')[:6]
            apikey = click.prompt('Api key (xmlrpc)',
                                  default=hidden_apikey)
            if apikey == hidden_apikey:
                # if default value then use actual value not hidden one
                apikey = cls.get('api.key')
            env_choice = click.Choice(list(cls.apienvs.keys()))
            apienv = click.prompt('Environnment [production]/ote',
                                  default=cls.default_apienv,
                                  type=env_choice,
                                  show_default=False)
            sshkey = click.prompt('SSH keyfile',
                                  default='~/.ssh/id_rsa.pub')
            hidden_apikeyrest = '%s...' % cls.get('apirest.key', '')[:6]
            apikeyrest = click.prompt('Api key (REST)',
                                      default=hidden_apikeyrest)
            if apikeyrest == hidden_apikeyrest:
                # if default value then use actual value not hidden one
                apikeyrest = cls.get('apirest.key')

            config.update({
                'api': {'key': apikey,
                        'host': cls.apienvs[apienv]},
            })
            if apikeyrest:
                config.update({
                    'apirest': {'key': apikeyrest},
                })

            if sshkey is not None:
                sshkey_file = os.path.expanduser(sshkey)
                if os.path.exists(sshkey_file):
                    config['sshkey'] = [sshkey_file]

            directory = os.path.expanduser(os.path.dirname(config_file))
            if not os.path.exists(directory):
                mkpath(directory, 0o700)

            # save to disk
            cls.save(config_file, config)
            # load in memory
            cls.load(config_file, 'global')
        except (KeyboardInterrupt, click.exceptions.Abort):
            cls.echo('Aborted.')
            sys.exit(1)
719227
function(err, privkey, pubkey) {
      if (err) throw err;
      this.pubkey = pubkey;
      this.privkey = privkey;
      this.user_host_field = pubkey.split(' ')[2].trim();
      console.log("Adding Heroku SSH keypair via API");
      add_ssh_key(api_key, pubkey, this);
    }