/*
Arguments match those of knRestifyHandler.  This constructor validates the
arguments, stores copies, and pregenerates some fields of response bodies
that we know won't change (like the start time).
774448
function knServiceContext(args)
{
	mod_assert.equal(typeof (args['uri_base']), 'string',
	    '"uri_base" must be a string');
	mod_assert.equal(typeof (args['service_name']), 'string',
	    '"service_name" must be a string');
	mod_assert.equal(typeof (args['version']), 'string',
	    '"version" must be a string');
	mod_assert.equal(typeof (args['ident']), 'string',
	    '"ident" must be a string');
	mod_assert.equal(typeof (args['list_types']), 'function',
	    '"list_types" must be a function');
	mod_assert.equal(typeof (args['list_objects']), 'function',
	    '"list_objects" must be a function');
	mod_assert.equal(typeof (args['get']), 'function',
	    '"get" must be a function');

	this.kns_service = {
		name: args['service_name'],
		ident: args['ident'],
		version: args['version']
	};

	if ('component' in args) {
		mod_assert.equal(typeof (args['component']), 'string',
		    '"component" must be a string');
		this.kns_service['component'] = args['component'];
	}

	this.kns_list_types = args['list_types'];
	this.kns_list_objects = args['list_objects'];
	this.kns_get = args['get'];

	if ('stats' in args) {
		mod_assert.equal(typeof (args['stats']), 'function',
		    '"stats" must be a function');
		this.kns_stats = args['stats'];
	}

	if ('schema' in args) {
		mod_assert.equal(typeof (args['schema']), 'function',
		    '"schema" must be a function');
		this.kns_schema = args['schema'];
	}

	this.kns_uri_base = mod_nutil.chopSlashes(args['uri_base']);
	this.kns_started = new Date(
	    Date.now() - process.uptime() * MILLISEC).toISOString();
}
391306
private SemanticStatus argumentsMatch(final String arg1, final String arg2) {

        if (arg1.startsWith(ENCODE_PREFIX)) {
            if (arg2.startsWith(FUNC_PREFIX)) {
                return INVALID_RETURN_TYPE_ARGUMENT;
            }
            if (!arg2.startsWith(ENCODE_PREFIX)) {
                return INVALID_ENCODING_ARGUMENT;
            }

            final String[] tokens1 = PARAMS_REGEX.split(arg1);
            if (tokens1.length != 2) {
                return INVALID_ENCODING_ARGUMENT;
            }

            final String[] tokens2 = PARAMS_REGEX.split(arg2);
            if (tokens2.length != 2) {
                return INVALID_ENCODING_ARGUMENT;
            }

            // If either token is the wildcard, any encoding is valid.
            if (isWildcard(tokens1[1]) || isWildcard(tokens2[1])) {
                return VALID;
            }

            final ValueEncoding ve1 = getValueEncoding(tokens1[1]);
            ValueEncoding ve2 = getValueEncoding(tokens2[1]);
            if (ve2 != null) {
                if (ve1.isAssignableFrom(ve2)) {
                    return VALID;
                }
                return INVALID_ENCODING_ARGUMENT;
            }
            // Fallback to verification based on all character discriminators
            for (final Character c : tokens2[1].toCharArray()) {
                ve2 = getValueEncoding(c);
                if (ve1.isAssignableFrom(ve2)) {
                    return VALID;
                }
            }
            return INVALID_ENCODING_ARGUMENT;
        }

        if (arg1.startsWith(FUNC_PREFIX)) {
            if (arg2.startsWith(ENCODE_PREFIX))
                return INVALID_RETURN_TYPE_ARGUMENT;
            if (!arg2.startsWith(FUNC_PREFIX))
                return INVALID_RETURN_TYPE_ARGUMENT;

            final String[] tokens1 = PARAMS_REGEX.split(arg1);
            if (tokens1.length != 2)
                return INVALID_RETURN_TYPE_ARGUMENT;

            final String[] tokens2 = PARAMS_REGEX.split(arg2);
            if (tokens2.length != 2)
                return INVALID_RETURN_TYPE_ARGUMENT;

            final ReturnType re1 = ReturnType.getReturnType(tokens1[1]);
            final ReturnType re2 = ReturnType.getReturnType(tokens2[1]);

            if (re1 != re2 && !re1.isAssignableFrom(re2))
                return INVALID_RETURN_TYPE_ARGUMENT;
            return VALID;
        }

        return null;
    }
914473
function extendErrorBody(ctor) {
  /**
   * Parse errror's arguments to extract the 'options' object.
   * Extracted from https://github.com/restify/errors/blob/master/lib/helpers.js#L30
   * @param  {} ctorArgs Arguments of the error.
   */
  function parseOptions(ctorArgs) {
    function parse() {
      let options = null;

      if (_.isPlainObject(arguments[0])) {
        // See https://github.com/restify/errors#new-erroroptions--printf-args
        options = arguments[0] || {};
      } else if (
        arguments[0] instanceof Error &&
        _.isPlainObject(arguments[1])
      ) {
        // See https://github.com/restify/errors#new-errorpriorerr-options--printf-args
        options = arguments[1] || {};
      }
      return options;
    }

    // Calls constructor args.
    return parse.apply(null, ctorArgs);
  }

  /**
   * Dynamically create a constructor.
   * Must be anonymous fn.
   * @constructor
   */
  // Use an object because otherwise the variable name is shown as function name.
  const anonymous = {};
  anonymous.hook = function() {
    const options = parseOptions(arguments) || {};
    // Calls the parent constructor with itself as scope.
    ctor.apply(this, arguments);
    // Adds custom options to itself
    patchErrorBody(this, options);
  };
  // Inherits from the original error.
  // Is that necessary??
  util.inherits(anonymous.hook, ctor);

  // Make the prototype an instance of the old class.
  anonymous.hook.prototype = ctor.prototype;

  // Assign display name
  anonymous.hook.displayName = ctor.displayName + 'Hook';

  return anonymous.hook;
}
698168
function validate () {
    var this$1 = this;
    var args = [], len = arguments.length;
    while ( len-- ) args[ len ] = arguments[ len ];

    var validators;
    var value;
    var cb;
    var ret = true;

    if (args.length === 3) {
      validators = [args[0]];
      value = args[1];
      cb = args[2];
    } else if (args.length === 2) {
      if (isPlainObject(args[0])) {
        validators = [args[0].validator];
        value = args[0].value || this.getValue();
        cb = args[1];
      } else {
        validators = this._keysCached(this._uid.toString(), this.results);
        value = args[0];
        cb = args[1];
      }
    } else if (args.length === 1) {
      validators = this._keysCached(this._uid.toString(), this.results);
      value = this.getValue();
      cb = args[0];
    } else {
      validators = this._keysCached(this._uid.toString(), this.results);
      value = this.getValue();
      cb = null;
    }

    if (args.length === 3 || (args.length === 2 && isPlainObject(args[0]))) {
      ret = this._validate(validators[0], value, cb);
    } else {
      validators.forEach(function (validator) {
        ret = this$1._validate(validator, value, cb);
      });
    }

    return ret
  }
262336
function parseArrayInitializer() {
        var elements = [], node = new Node(), restSpread;

        expect('[');

        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else if (match('...')) {
                restSpread = new Node();
                lex();
                restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));

                if (!match(']')) {
                    isAssignmentTarget = isBindingElement = false;
                    expect(',');
                }
                elements.push(restSpread);
            } else {
                elements.push(inheritCoverGrammar(parseAssignmentExpression));

                if (!match(']')) {
                    expect(',');
                }
            }
        }

        lex();

        return node.finishArrayExpression(elements);
    }
22967
def _processArgs(self, entry, *_args, **_kwargs):
        

        # We need the args to be a list so we can mutate them
        args = list(_args)
        kwargs = copy.deepcopy(_kwargs)

        reqArgs = entry['args']
        routeParams = {}

        query = {}
        payload = None
        kwApiArgs = {}

        paginationHandler = None
        paginationLimit = None

        # There are three formats for calling methods:
        #   1. method(v1, v1, payload)
        #   2. method(payload, k1=v1, k2=v2)
        #   3. method(payload=payload, query=query, params={k1: v1, k2: v2})
        if len(kwargs) == 0:
            if 'input' in entry and len(args) == len(reqArgs) + 1:
                payload = args.pop()
            if len(args) != len(reqArgs):
                log.debug(args)
                log.debug(reqArgs)
                raise exceptions.TaskclusterFailure('Incorrect number of positional arguments')
            log.debug('Using method(v1, v2, payload) calling convention')
        else:
            # We're considering kwargs which are the api route parameters to be
            # called 'flat' because they're top level keys.  We're special
            # casing calls which have only api-arg kwargs and possibly a payload
            # value and handling them directly.
            isFlatKwargs = True
            if len(kwargs) == len(reqArgs):
                for arg in reqArgs:
                    if not kwargs.get(arg, False):
                        isFlatKwargs = False
                        break
                if 'input' in entry and len(args) != 1:
                    isFlatKwargs = False
                if 'input' not in entry and len(args) != 0:
                    isFlatKwargs = False
                else:
                    pass  # We're using payload=, query= and param=
            else:
                isFlatKwargs = False

            # Now we're going to handle the two types of kwargs.  The first is
            # 'flat' ones, which are where the api params
            if isFlatKwargs:
                if 'input' in entry:
                    payload = args.pop()
                kwApiArgs = kwargs
                log.debug('Using method(payload, k1=v1, k2=v2) calling convention')
                warnings.warn(
                    "The method(payload, k1=v1, k2=v2) calling convention will soon be deprecated",
                    PendingDeprecationWarning
                )
            else:
                kwApiArgs = kwargs.get('params', {})
                payload = kwargs.get('payload', None)
                query = kwargs.get('query', {})
                paginationHandler = kwargs.get('paginationHandler', None)
                paginationLimit = kwargs.get('paginationLimit', None)
                log.debug('Using method(payload=payload, query=query, params={k1: v1, k2: v2}) calling convention')

        if 'input' in entry and isinstance(payload, type(None)):
            raise exceptions.TaskclusterFailure('Payload is required')

        # These all need to be rendered down to a string, let's just check that
        # they are up front and fail fast
        for arg in args:
            if not isinstance(arg, six.string_types) and not isinstance(arg, int):
                raise exceptions.TaskclusterFailure(
                    'Positional arg "%s" to %s is not a string or int' % (arg, entry['name']))

        for name, arg in six.iteritems(kwApiArgs):
            if not isinstance(arg, six.string_types) and not isinstance(arg, int):
                raise exceptions.TaskclusterFailure(
                    'KW arg "%s: %s" to %s is not a string or int' % (name, arg, entry['name']))

        if len(args) > 0 and len(kwApiArgs) > 0:
            raise exceptions.TaskclusterFailure('Specify either positional or key word arguments')

        # We know for sure that if we don't give enough arguments that the call
        # should fail.  We don't yet know if we should fail because of two many
        # arguments because we might be overwriting positional ones with kw ones
        if len(reqArgs) > len(args) + len(kwApiArgs):
            raise exceptions.TaskclusterFailure(
                '%s takes %d args, only %d were given' % (
                    entry['name'], len(reqArgs), len(args) + len(kwApiArgs)))

        # We also need to error out when we have more positional args than required
        # because we'll need to go through the lists of provided and required args
        # at the same time.  Not disqualifying early means we'll get IndexErrors if
        # there are more positional arguments than required
        if len(args) > len(reqArgs):
            raise exceptions.TaskclusterFailure('%s called with too many positional args',
                                                entry['name'])

        i = 0
        for arg in args:
            log.debug('Found a positional argument: %s', arg)
            routeParams[reqArgs[i]] = arg
            i += 1

        log.debug('After processing positional arguments, we have: %s', routeParams)

        routeParams.update(kwApiArgs)

        log.debug('After keyword arguments, we have: %s', routeParams)

        if len(reqArgs) != len(routeParams):
            errMsg = '%s takes %s args, %s given' % (
                entry['name'],
                ','.join(reqArgs),
                routeParams.keys())
            log.error(errMsg)
            raise exceptions.TaskclusterFailure(errMsg)

        for reqArg in reqArgs:
            if reqArg not in routeParams:
                errMsg = '%s requires a "%s" argument which was not provided' % (
                    entry['name'], reqArg)
                log.error(errMsg)
                raise exceptions.TaskclusterFailure(errMsg)

        return routeParams, payload, query, paginationHandler, paginationLimit
238266
private void callMissedHitHandler(K key) {
		if (!map.containsKey(key)) {
			if (missedHitHandler == null) {
				throw new RuntimeException("No Missed Hit Handler");
			}

			V v = missedHitHandler.loadForCache(key);
			if (v != null) {
				put(key, v);
			}
		}
	}
190748
private static final Object putIfMatch( final NonBlockingHashMap topmap, final Object[] kvs, final Object key, final Object putval, final Object expVal ) {
    assert putval != null;
    assert !(putval instanceof Prime);
    assert !(expVal instanceof Prime);
    final int fullhash = hash  (key); // throws NullPointerException if key null
    final int len      = len   (kvs); // Count of key/value pairs, reads kvs.length
    final CHM chm      = chm   (kvs); // Reads kvs[0]
    final int[] hashes = hashes(kvs); // Reads kvs[1], read before kvs[0]
    int idx = fullhash & (len-1);

    // ---
    // Key-Claim stanza: spin till we can claim a Key (or force a resizing).
    int reprobe_cnt=0;
    Object K=null, V=null;
    Object[] newkvs=null;
    while( true ) {             // Spin till we get a Key slot
      V = val(kvs,idx);         // Get old value (before volatile read below!)
      K = key(kvs,idx);         // Get current key
      if( K == null ) {         // Slot is free?
        // Found an empty Key slot - which means this Key has never been in
        // this table.  No need to put a Tombstone - the Key is not here!
        if( putval == TOMBSTONE ) return putval; // Not-now & never-been in this table
        // Claim the null key-slot
        if( CAS_key(kvs,idx, null, key ) ) { // Claim slot for Key
          chm._slots.add(1);      // Raise key-slots-used count
          hashes[idx] = fullhash; // Memoize fullhash
          break;                  // Got it!
        }
        // CAS to claim the key-slot failed.
        //
        // This re-read of the Key points out an annoying short-coming of Java
        // CAS.  Most hardware CAS's report back the existing value - so that
        // if you fail you have a *witness* - the value which caused the CAS
        // to fail.  The Java API turns this into a boolean destroying the
        // witness.  Re-reading does not recover the witness because another
        // thread can write over the memory after the CAS.  Hence we can be in
        // the unfortunate situation of having a CAS fail *for cause* but
        // having that cause removed by a later store.  This turns a
        // non-spurious-failure CAS (such as Azul has) into one that can
        // apparently spuriously fail - and we avoid apparent spurious failure
        // by not allowing Keys to ever change.
        K = key(kvs,idx);       // CAS failed, get updated value
        assert K != null;       // If keys[idx] is null, CAS shoulda worked
      }
      // Key slot was not null, there exists a Key here

      // We need a volatile-read here to preserve happens-before semantics on
      // newly inserted Keys.  If the Key body was written just before inserting
      // into the table a Key-compare here might read the uninitalized Key body.
      // Annoyingly this means we have to volatile-read before EACH key compare.
      newkvs = chm._newkvs;     // VOLATILE READ before key compare

      if( keyeq(K,key,hashes,idx,fullhash) )
        break;                  // Got it!

      // get and put must have the same key lookup logic!  Lest 'get' give
      // up looking too soon.
      //topmap._reprobes.add(1);
      if( ++reprobe_cnt >= reprobe_limit(len) || // too many probes or
          key == TOMBSTONE ) { // found a TOMBSTONE key, means no more keys
        // We simply must have a new table to do a 'put'.  At this point a
        // 'get' will also go to the new table (if any).  We do not need
        // to claim a key slot (indeed, we cannot find a free one to claim!).
        newkvs = chm.resize(topmap,kvs);
        if( expVal != null ) topmap.help_copy(newkvs); // help along an existing copy
        return putIfMatch(topmap,newkvs,key,putval,expVal);
      }

      idx = (idx+1)&(len-1); // Reprobe!
    } // End of spinning till we get a Key slot

    // ---
    // Found the proper Key slot, now update the matching Value slot.  We
    // never put a null, so Value slots monotonically move from null to
    // not-null (deleted Values use Tombstone).  Thus if 'V' is null we
    // fail this fast cutout and fall into the check for table-full.
    if( putval == V ) return V; // Fast cutout for no-change

    // See if we want to move to a new table (to avoid high average re-probe
    // counts).  We only check on the initial set of a Value from null to
    // not-null (i.e., once per key-insert).  Of course we got a 'free' check
    // of newkvs once per key-compare (not really free, but paid-for by the
    // time we get here).
    if( newkvs == null &&       // New table-copy already spotted?
        // Once per fresh key-insert check the hard way
        ((V == null && chm.tableFull(reprobe_cnt,len)) ||
         // Or we found a Prime, but the JMM allowed reordering such that we
         // did not spot the new table (very rare race here: the writing
         // thread did a CAS of _newkvs then a store of a Prime.  This thread
         // reads the Prime, then reads _newkvs - but the read of Prime was so
         // delayed (or the read of _newkvs was so accelerated) that they
         // swapped and we still read a null _newkvs.  The resize call below
         // will do a CAS on _newkvs forcing the read.
         V instanceof Prime) )
      newkvs = chm.resize(topmap,kvs); // Force the new table copy to start
    // See if we are moving to a new table.
    // If so, copy our slot and retry in the new table.
    if( newkvs != null )
      return putIfMatch(topmap,chm.copy_slot_and_check(topmap,kvs,idx,expVal),key,putval,expVal);

    // ---
    // We are finally prepared to update the existing table
    assert !(V instanceof Prime);

    // Must match old, and we do not?  Then bail out now.  Note that either V
    // or expVal might be TOMBSTONE.  Also V can be null, if we've never
    // inserted a value before.  expVal can be null if we are called from
    // copy_slot.

    if( expVal != NO_MATCH_OLD && // Do we care about expected-Value at all?
        V != expVal &&            // No instant match already?
        (expVal != MATCH_ANY || V == TOMBSTONE || V == null) &&
        !(V==null && expVal == TOMBSTONE) &&    // Match on null/TOMBSTONE combo
        (expVal == null || !expVal.equals(V)) ) // Expensive equals check at the last
      return V;                                 // Do not update!

    // Actually change the Value in the Key,Value pair
    if( CAS_val(kvs, idx, V, putval ) ) {
      // CAS succeeded - we did the update!
      // Both normal put's and table-copy calls putIfMatch, but table-copy
      // does not (effectively) increase the number of live k/v pairs.
      if( expVal != null ) {
        // Adjust sizes - a striped counter
        if(  (V == null || V == TOMBSTONE) && putval != TOMBSTONE ) chm._size.add( 1);
        if( !(V == null || V == TOMBSTONE) && putval == TOMBSTONE ) chm._size.add(-1);
      }
    } else {                    // Else CAS failed
      V = val(kvs,idx);         // Get new value
      // If a Prime'd value got installed, we need to re-run the put on the
      // new table.  Otherwise we lost the CAS to another racing put.
      // Simply retry from the start.
      if( V instanceof Prime )
        return putIfMatch(topmap,chm.copy_slot_and_check(topmap,kvs,idx,expVal),key,putval,expVal);
    }
    // Win or lose the CAS, we are done.  If we won then we know the update
    // happened as expected.  If we lost, it means "we won but another thread
    // immediately stomped our update with no chance of a reader reading".
    return (V==null && expVal!=null) ? TOMBSTONE : V;
  }
27936
async function validateArguments(args, operation) {
    let error = new Error();
    let body = undefined;

    error.name = 'ArgumentError';
    if (!operation) {
        let verbs = ["add", "clone", "delete", "export", "package", "get", "import", "list", "publish", "query", "set", "suggest", "train", "update"];
        if (verbs.indexOf(args._[0]) < 0)
            error.message = `'${args._[0]}' is not a valid action`;
        else if (args._.length >= 2)
            error.message = `'${args._[1]}' is not a valid resource`;
        else
            error.message = `missing resource\n`;
        throw error;
    }

    switch (operation.target[0]){
        case "userazureaccounts":
        case "appazureaccounts":
            switch (operation.methodAlias) {
                case "list":
                    if (args.hasOwnProperty("armToken")) {
                        args.customHeaders["Authorization"] = `Bearer ${args.armToken}`;
                    }
                    break;
                }
                break;
                case "appazureaccount":
                    switch (operation.methodAlias) {
                        case "add":
                        case "delete":
                            if (args.hasOwnProperty("armToken")) {
                                args.customHeaders["Authorization"] = `Bearer ${args.armToken}`;
                            }
                            break;
                        }
                        break;
    }

    const entitySpecified = typeof args.in === 'string';
    const entityRequired = !!operation.entityName;

    if (entityRequired) {
        if (entitySpecified) {
            body = await getFileInput(args);
        }
        else {
            // make up a request body from command line args
            switch (operation.target[0]) {
                case "version":
                    switch (operation.methodAlias) {
                        case "publish":
                            if (args.versionId) {
                                body = {
                                    versionId: `${args.versionId}`,
                                    isStaging: args.staging === 'true'
                                };
                            }
                            break;
                        case "rename":
                        case "update":
                        case "clone":
                            if (args.newVersionId) {
                                body = {
                                    version: `${args.newVersionId}`
                                };
                            }
                            break;
                    }
                    break;

                case "settings":
                    switch (operation.methodAlias) {
                        case "update":
                            if (args.hasOwnProperty("public")) {
                                body = {
                                    isPublic: args.public === 'true'
                                };
                            }
                            break;
                    }
                    break;
                case "versionsettings":
                    switch (operation.methodAlias) {
                        case "update":
                            if (args.hasOwnProperty("useAllTrainingData")) {
                                body = [{
                                    name: "UseAllTrainingData",
                                    value: args.useAllTrainingData === 'true' ? 'true' : 'false'
                                }];
                            }
                            break;
                    }
                    break;
                case "appazureaccount":
                    if (args.azureSubscriptionId && args.resourceGroup && args.accountName) {
                        body = {
                            azureSubscriptionId: `${args.azureSubscriptionId}`,
                            resourceGroup: `${args.resourceGroup}`,
                            accountName: `${args.accountName}`
                        };
                    }
                    break;

                default:
                    error.message = `The --in requires an input of type: ${operation.entityType}`;
                    throw error;
            }
        }
    }
    return body;
    // Note that the ServiceBase will validate params that may be required.
}
817798
function (context, callback) {

            if (this.$resourceConfiguration.$.upsert === true) {
                callback(new HttpError("Please create with PUT", 405));
                return;
            }

            var self = this,
                model,
                processor;

            flow()
                .seq("collection", function (cb) {
                    self._findCollection(context, cb);
                })
                .seq(function () {
                    model = this.vars.collection.createItem();

                    var payload = context.request.params;

                    processor = self.$restHandler.$restDataSource.getProcessorForModel(model);

                    model.set(processor.parse(model, payload));

                    if (model.createdField) {
                        model.set(model.createdField, new Date());
                    }
                })
                .seq(function () {
                    self._generateAutoValues(model);
                })
                .seq(function (cb) {
                    self._validate(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelSave(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelCreate(model, context, cb);
                })
                // validate and save model
                .seq(function (cb) {
                    model.validateAndSave({action: DataSource.ACTION.CREATE }, cb);
                })
                .seq(function (cb) {
                    self._afterModelCreate(model, context, cb);
                }).
                exec(function (err, results) {
                    if (!err) {
                        // TODO: do correct invalidation
                        results.collection.invalidatePageCache();

                        var body = JSON.stringify(processor.compose(model, null));

                        var response = context.response;
                        response.writeHead(201, "", {
                            'Content-Type': 'application/json',
                            'Location': context.request.urlInfo.uri + "/" + model.identifier()
                        });

                        response.write(body);
                        response.end();

                        callback(null);
                    } else {
                        if (!(err instanceof HttpError)) {
                            var statusCode = 400;
                            // TODO: add more error handling
                            err = new HttpError(err, statusCode);
                        }
                        callback(err);
                    }
                });
        }
323757
def <<(arg)
            case arg
            when PositionalArgument, KeywordArgument, FlagArgument, RestArgument
                if @arguments[arg.key]
                    raise ArgumentError, "An argument with key '#{arg.key}' has already been defined"
                end
                if arg.short_key && @short_keys[arg.short_key]
                    raise ArgumentError, "The short key '#{arg.short_key}' has already been registered by the '#{
                        @short_keys[arg.short_key]}' argument"
                end
                if arg.is_a?(RestArgument) && rest_args
                    raise ArgumentError, "Only one rest argument can be defined"
                end
                @arguments[arg.key] = arg
                @short_keys[arg.short_key] = arg if arg.short_key
            else
                raise ArgumentError, "arg must be an instance of PositionalArgument, KeywordArgument, " +
                    "FlagArgument or RestArgument"
            end
        end
679281
private void respondToListSets(Map<String, String> args,
                                   String baseURL,
                                   List<?> sets,
                                   ResumptionToken resumptionToken,
                                   PrintWriter out) {
        appendTop(out);
        appendRequest(args, baseURL, out);
        out.println("  <ListSets>");
        for (int i = 0; i < sets.size(); i++) {
            SetInfo s = (SetInfo) sets.get(i);
            out.println("    <set>");
            out.println("      <setSpec>" + s.getSpec() + "</setSpec>");
            out.println("      <setName>" + s.getName() + "</setName>");
            Iterator<String> iter = s.getDescriptions().iterator();
            while (iter.hasNext()) {
                out.println("      <setDescription>\n");
                out.println(iter.next());
                out.println("      </setDescription>\n");
            }
            out.println("    </set>");
        }
        appendResumptionToken(resumptionToken, out);
        out.println("  </ListSets>");
        appendBottom(out);
    }
808905
private void verifyArguments(JmxExecRequest request, OperationAndParamType pTypes, int pNrParams, List<Object> pArgs) {
        if ( (pNrParams > 0 && pArgs == null) || (pArgs != null && pArgs.size() != pNrParams)) {
            throw new IllegalArgumentException("Invalid number of operation arguments. Operation " +
                    request.getOperation() + " on " + request.getObjectName() + " requires " + pTypes.paramClasses.length +
                    " parameters, not " + (pArgs == null ? 0 : pArgs.size()) + " as given");
        }
    }
861617
protected static void validateParamsPresence(Map params, String... keys) {
        for (String name : keys) {
            if (!params.containsKey(name)) {
                throw new IllegalArgumentException("parameter: '" + name + "' is missing");
            }
        }
    }
176219
function ko(fn, isParamHandler) {
	// handlers and middlewares may have safeguard properties to be skipped
	if ('$$koified' in fn) {
		return fn;
	}

	let handler = function (req, res, next) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args);
	};

	let errHandler = function (err, req, res, next) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args, true);
	};

	let paramHandler = function (req, res, next, val) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args);
	};

	let wrapper;

	// the way Express distinguishes error handlers from regular ones
	if (fn.length === 4) {
		wrapper = isParamHandler ? paramHandler : errHandler;
	} else {
		wrapper = handler;
	}

	// safeguard
	Object.defineProperty(wrapper, '$$koified', {
		configurable: true,
		writable: true,
		value: true
	});

	return wrapper;
}
1000007
def validate(self, generator, axesToMove=None, **kwargs):
        # type: (AGenerator, AAxesToMove, **Any) -> AConfigureParams
        
        iterations = 10
        # We will return this, so make sure we fill in defaults
        for k, default in self._block.configure.defaults.items():
            if k not in kwargs:
                kwargs[k] = default
        # The validated parameters we will eventually return
        params = ConfigureParams(generator, axesToMove, **kwargs)
        # Make some tasks just for validate
        part_contexts = self.create_part_contexts()
        # Get any status from all parts
        status_part_info = self.run_hooks(
            ReportStatusHook(p, c) for p, c in part_contexts.items())
        while iterations > 0:
            # Try up to 10 times to get a valid set of parameters
            iterations -= 1
            # Validate the params with all the parts
            validate_part_info = self.run_hooks(
                ValidateHook(p, c, status_part_info, **kwargs)
                for p, c, kwargs in self._part_params(part_contexts, params))
            tweaks = ParameterTweakInfo.filter_values(validate_part_info)
            if tweaks:
                for tweak in tweaks:
                    deserialized = self._block.configure.takes.elements[
                        tweak.parameter].validate(tweak.value)
                    setattr(params, tweak.parameter, deserialized)
                    self.log.debug(
                        "Tweaking %s to %s", tweak.parameter, deserialized)
            else:
                # Consistent set, just return the params
                return params
        raise ValueError("Could not get a consistent set of parameters")
272879
def validate_read(self, kwargs):
        
        kwargs = super().validate_read(kwargs)
        if 'start' in kwargs or 'stop' in kwargs:
            raise NotImplementedError("start and/or stop are not supported "
                                      "in fixed Sparse reading")
        return kwargs