Common operation wrapper
4395
function CommonOperation(operationFunc, callback) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
  var sliceStart = 2;
  if (azureutil.objectIsFunction(callback)) {
    this._userCallback = callback;
  } else {
    this._userCallback = null;
    sliceStart = 1;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
  this.run = function (cb) {
    if (!cb) cb = this._userCallback;
    operationArguments.push(cb);
    this.status = OperationState.RUNNING;
    operationFunc.apply(null, operationArguments);
    operationArguments = operationFunc = null;
  };
  
  this._fireUserCallback = function () {
    if (this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
    this._userCallback = this._callbackArguments = null;
  };
}
915279
def operation(func=None, pipeline_facts=None):
    '''
    
    '''

    # If not decorating, return function with config attached
    if func is None:
        def decorator(f):
            setattr(f, 'pipeline_facts', pipeline_facts)
            return operation(f)

        return decorator

    # Index the operation!
    module_bits = func.__module__.split('.')
    module_name = module_bits[-1]
    op_name = '.'.join((module_name, func.__name__))
    OPERATIONS.append(op_name)

    # Actually decorate!
    @wraps(func)
    def decorated_func(*args, **kwargs):
        # Prepare state/host
        #

        # If we're in CLI mode, there's no state/host passed down, we need to
        # use the global "pseudo" modules.
        if len(args) < 2 or not (
            isinstance(args[0], (State, PseudoModule))
            and isinstance(args[1], (Host, PseudoModule))
        ):
            state = pseudo_state._module
            host = pseudo_host._module

            if state.in_op:
                raise PyinfraError((
                    'Nested operation called without state/host: {0} ({1})'
                ).format(op_name, _get_call_location()))

            if state.in_deploy:
                raise PyinfraError((
                    'Nested deploy operation called without state/host: {0} ({1})'
                ).format(op_name, _get_call_location()))

        # Otherwise (API mode) we just trim off the commands
        else:
            args_copy = list(args)
            state, host = args[0], args[1]
            args = args_copy[2:]

        # In API mode we have the kwarg - if a nested operation call we have
        # current_frameinfo.
        frameinfo = kwargs.pop('frameinfo', get_caller_frameinfo())

        # Configure operation
        #

        # Name the operation
        names = None
        autoname = False

        # Look for a set as the first argument
        if len(args) > 0 and isinstance(args[0], set):
            names = args[0]
            args_copy = list(args)
            args = args[1:]

        # Generate an operation name if needed (Module/Operation format)
        else:
            autoname = True
            module_bits = func.__module__.split('.')
            module_name = module_bits[-1]
            names = {
                '{0}/{1}'.format(module_name.title(), func.__name__.title()),
            }

        if state.deploy_name:
            names = {
                '{0} | {1}'.format(state.deploy_name, name)
                for name in names
            }

        # Get the meta kwargs (globals that apply to all hosts)
        op_meta_kwargs = pop_op_kwargs(state, kwargs)

        # If this op is being called inside another, just return here
        # (any unwanted/op-related kwargs removed above).
        if state.in_op:
            return func(state, host, *args, **kwargs) or []

        filename = frameinfo.filename
        line_number = frameinfo.lineno

        # Figure out the lines this operation was called from (essentially like
        # a line-call-stack).
        op_lines = [line_number]

        if state.deploy_line_numbers:
            op_lines = list(state.deploy_line_numbers) + op_lines

        # Inject the current op file number (only incremented in CLI mode)
        op_lines.insert(0, state.current_op_file)

        # Make a hash from the call stack lines
        op_hash = make_hash(op_lines)

        # Avoid adding duplicates! This happens if an operation is called within
        # a loop - such that the filename/lineno/code _are_ the same, but the
        # arguments might be different. We just append an increasing number to
        # the op hash and also handle below with the op order.
        host_op_hashes = state.meta[host]['op_hashes']
        duplicate_op_count = 0
        while op_hash in host_op_hashes:
            logger.debug('Duplicate hash ({0}) detected!'.format(op_hash))
            op_hash = '{0}-{1}'.format(op_hash, duplicate_op_count)
            duplicate_op_count += 1

        host_op_hashes.add(op_hash)

        if duplicate_op_count:
            op_lines.append(duplicate_op_count)

        op_lines = tuple(op_lines)
        state.op_line_numbers_to_hash[op_lines] = op_hash
        logger.debug('Adding operation, {0}, called @ {1}:{2}, opLines={3}, opHash={4}'.format(
            names, filename, line_number, op_lines, op_hash,
        ))

        # Ensure shared (between servers) operation meta
        op_meta = state.op_meta.setdefault(op_hash, {
            'names': set(),
            'args': [],
        })

        # Add any meta kwargs (sudo, etc) to the meta - first parse any strings
        # as jinja templates.
        actual_op_meta_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(op_meta_kwargs)
        }
        op_meta.update(actual_op_meta_kwargs)

        # Add any new names to the set
        op_meta['names'].update(names)

        # Attach normal args, if we're auto-naming this operation
        if autoname:
            for arg in args:
                if isinstance(arg, FunctionType):
                    arg = arg.__name__

                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

            # Attach keyword args
            for key, value in six.iteritems(kwargs):
                arg = '='.join((str(key), str(value)))
                if arg not in op_meta['args']:
                    op_meta['args'].append(arg)

        # Check if we're actually running the operation on this host
        #

        # Run once and we've already added meta for this op? Stop here.
        if op_meta_kwargs['run_once']:
            has_run = False
            for ops in six.itervalues(state.ops):
                if op_hash in ops:
                    has_run = True
                    break

            if has_run:
                return OperationMeta(op_hash)

        # If we're limited, stop here - *after* we've created op_meta. This
        # ensures the meta object always exists, even if no hosts actually ever
        # execute the op (due to limit or otherwise).
        hosts = op_meta_kwargs['hosts']
        when = op_meta_kwargs['when']

        if (
            # Limited by the state's limit_hosts?
            (state.limit_hosts is not None and host not in state.limit_hosts)
            # Limited by the operation kwarg hosts?
            or (hosts is not None and host not in hosts)
            # Limited by the operation kwarg when? We check == because when is
            # normally attribute wrapped as a AttrDataBool, which is actually
            # an integer (Python doesn't allow subclassing bool!).
            or when == False  # noqa
        ):
            return OperationMeta(op_hash)

        # "Run" operation
        #

        # Otherwise, flag as in-op and run it to get the commands
        state.in_op = True
        state.current_op_hash = op_hash

        # Generate actual arguments by parsing strings as jinja2 templates. This
        # means you can string format arguments w/o generating multiple
        # operations. Only affects top level operations, as must be run "in_op"
        # so facts are gathered correctly.
        actual_args = [
            get_arg_value(state, host, a)
            for a in args
        ]

        actual_kwargs = {
            key: get_arg_value(state, host, a)
            for key, a in six.iteritems(kwargs)
        }

        # Convert to list as the result may be a generator
        commands = unroll_generators(func(
            state, host,
            *actual_args,
            **actual_kwargs
        ))

        state.in_op = False
        state.current_op_hash = None

        # Add host-specific operation data to state
        #

        # We're doing some commands, meta/ops++
        state.meta[host]['ops'] += 1
        state.meta[host]['commands'] += len(commands)

        # Add the server-relevant commands
        state.ops[host][op_hash] = {
            'commands': commands,
        }

        # Return result meta for use in deploy scripts
        return OperationMeta(op_hash, commands)

    decorated_func._pyinfra_op = func
    return decorated_func
1192987
function wrapper(my) {

  var start = process.hrtime();
  var c = 0, e = 0;
  var doit = [];
  var stream = startline({
    file: my.filename,
    encoding: 'utf8',
  });

  // options
  var open = ansi.green.open;
  var close = ansi.green.close;
  if (my.url) {
    doit
        .push([
          input.url,
          [ Object.create(null), 'url' ],
          [ output.url,
            [ open + 'ROUTE', 'METHOD', 'STATUS', 'COUNTER', close ] ] ]);
  }
  if (my.ip) {
    doit.push([ input.cc, [ Object.create(null), 'ip' ],
      [ output.ip, [ open + 'IP', 'COUNTER' + close ] ] ]);
  }
  if (my.response) {
    doit.push([ input.avg, [ {
      what: 0,
      total: 0,
      max: 0,
      min: 10000
    }, 'response' ], [ output.avg, [ open + 'RESPONSE', 'MS' + close ] ] ]);
  }
  if (my.pid) {
    doit.push([ input.cc, [ Object.create(null), 'pid' ],
      [ output.cc, [ open + 'PID' + close ] ] ]);
  }
  if (my.bytesReq) {
    doit.push([ input.avg, [ {
      what: 0,
      total: 0,
      max: 0,
      min: 10000
    }, 'bytesReq' ],
      [ output.avg, [ open + 'BYTES REQUESTED', 'BYTE' + close ] ] ]);
  }
  if (my.bytesRes) {
    doit.push([ input.avg, [ {
      what: 0,
      total: 0,
      max: 0,
      min: 10000
    }, 'bytesRes' ], [ output.avg, [ open + 'BYTES SENT', 'BYTE' + close ] ] ]);
  }
  if (my.referrer) {
    doit.push([ input.cc, [ Object.create(null), 'referrer' ],
      [ output.cc, [ open + 'REFERRER' + close ] ] ]);
  }
  if (my.auth) {
    doit.push([ input.cc, [ Object.create(null), 'auth' ],
      [ output.cc, [ open + 'USER ATHENTICATION' + close ] ] ]);
  }
  if (my.agent) {
    doit.push([ input.cc, [ Object.create(null), 'agent' ],
      [ output.cc, [ open + 'USER-AGENT' + close ] ] ]);
  }
  if (my.version) {
    doit.push([ input.cc, [ Object.create(null), 'version' ],
      [ output.cc, [ open + 'HTTP VERSION' + close ] ] ]);
  }
  if (my.level) {
    doit.push([ input.cc, [ Object.create(null), 'level' ],
      [ output.cc, [ open + 'LOG LEVEL' + close ] ] ]);
  }
  if (my.message) {
    doit.push([ input.cc, [ Object.create(null), 'message' ],
      [ output.cc, [ open + 'LOG MESSAGE' + close ] ] ]);
  }
  if (my.timestamp) {
    doit.push([ input.cc, [ Object.create(null), 'timestamp' ],
      [ output.cc, [ open + 'LOG TIMESTAMP' + close ] ] ]);
  }

  // go
  if (my.search) {
    doit = [];

    stream.on('line', function(lines) {

      var s = lines.match(my.search);
      if (s) {
        var line = lines.replace(my.search, ansi.red.open + s[0]
          + ansi.red.close + ansi.gray.open);
        // console.log(s)
        doit.push([ 'line ' + c, ansi.gray.open + line + ansi.gray.close ]);
      }
      ++c;
    });
    stream.on('close', function() {

      if (doit.length === 0) {
        console.log('Not found');
      }
      console.log(table(doit));
    });

  }

  stream.on('line', function(lines) {

    ++c;
    try {
      var line = JSON.parse(lines);
      for (var i = 0, ii = doit.length; i < ii; ++i) {
        var params = doit[i][1];
        params[0] = doit[i][0](line, params);
      }
    } catch (err) {
      ++e;
    }
  });

  stream.on('close', function() {

    var out = [];
    var csv = [];
    for (var i = 0, ii = doit.length; i < ii; ++i) {
      var buff = doit[i][2][0](doit[i][1], doit[i][2][1]);
      for (var b = 0, bb = buff.length; b < bb; ++b) {
        out.push(buff[b]);
      }
    }

    var consol = out.slice();
    if (my.report) {
      csv.push([ ansi.yellow.open + 'REPORT' + ansi.yellow.close ], [
        'line parsed', ansi.underline.open + c + ansi.underline.close ]);
      consol.push(csv[0]);
      consol.push(csv[1]);
      if (e > 0) {
        csv.push([ ansi.red.open + 'line error', e + ansi.red.close ]);
        consol.push(csv[2]);
      }
      var diff = process.hrtime(start);
      diff = ((diff[0] * 1e9 + diff[1]) / 1000000).toFixed(3) + ' ms';
      csv.push([ 'time elapsed',
        ansi.underline.open + diff + ansi.underline.close ]);
      consol.push(csv[csv.length - 1]);
    }

    // print
    if (my.csv) { // file
      var to_csv = require('./lib/csv.js');
      console.log(table(csv, {
        align: [ 'l', 'r' ],
        stringLength: function(s) {

          return s.replace(re, '').length;
        }
      }));
      to_csv(String(my.csv), out);
    } else { // console
      console.log(table(consol, {
        align: [ 'l', 'r' ],
        stringLength: function(s) {

          return s.replace(re, '').length;
        }
      }));
    }
  });

  return my;
}
1229951
def perform_set_operation(*args)
      options     = extract_options!(args)
      environment = extract_environment!(options)
      identifier  = normalize_set_identifier(environment)
      # Uses yaml when we have multiple identifiers.
      uses_yaml   = !environment.nil?
      options.merge!(:yaml => true) if uses_yaml
      args.unshift(identifier) unless identifier.nil?
      args << options
      result = rvm(*args)
      uses_yaml ? YAML.load(result.stdout) : result
    end
1173063
def parse_operation_type(lexer: Lexer) -> OperationType:
    """"""
    operation_token = expect_token(lexer, TokenKind.NAME)
    try:
        return OperationType(operation_token.value)
    except ValueError:
        raise unexpected(lexer, operation_token)
1239127
def _wrap_set_op(self, fun, arg):
        """"""
        result = fun(self, arg)
        result._autostep = self._autostep
        result.padding = self.padding
        return result
242722
def _op(self, operation, other, *allowed):
		""""""
		
		f = self._field
		
		if self._combining:  # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz).
			return reduce(self._combining,
					(q._op(operation, other, *allowed) for q in f))  # pylint:disable=protected-access
		
		# Optimize this away in production; diagnosic aide.
		if __debug__ and _complex_safety_check(f, {operation} | set(allowed)):  # pragma: no cover
			raise NotImplementedError("{self!r} does not allow {op} comparison.".format(self=self, op=operation))
		
		if other is not None:
			other = f.transformer.foreign(other, (f, self._document))
		
		return Filter({self._name: {operation: other}})
1310310
public static <T> Operation<T> operation(Class<? extends T> type, Operator operator,
                                             Expression<?>... args) {
        return operation(type, operator, ImmutableList.copyOf(args));
    }
368724
function handleOperation(handlers, mode, checkArity, req, res, done) {
  // parse path:
  // - first part is the operation name
  // - the following components of the path are used as arguments
  const parsedParts = parsePath(req);
  if (parsedParts[0].length === 0) {
    done(new ModofunError(403, 'NoOperation', 'Operation must be specified!'));
    return;
  }
  const [operation, ...args] = parsedParts;

  if (operation && handlers.hasOwnProperty(operation)) {
    // the stack of operation specific middleware
    let operationMiddleware = [];
    // operation handler
    let operationHandler = handlers[operation];

    if (Array.isArray(operationHandler)) {
      // if an array is passed, add operation specific middleware
      // last item in the array should be the operation handler
      operationMiddleware = operationHandler.slice(0, -1);
      operationHandler = operationHandler[operationHandler.length-1];

    } else if (typeof operationHandler !== 'function') {
      // otherwise return internal error
      done(new ModofunError(500, 'InvalidConfig', 'Handler must be a function or array'));
      return;
    }

    // call middleware stack with same req/res context
    runMiddlewareStack(operationMiddleware, req, res, (err) => {
      if (err) {
        done(err);
        return;
      }
      try {
        // call handler function
        if (mode === FUNCTION_MODE) {
          invokeFunctionHandler(operationHandler, args, checkArity, req, res, done);
        } else {
          invokeHTTPHandler(operationHandler, args, req, res, done);
        }
      } catch(err) {
        done(err);
      }
    });

  } else {
    // fail if requested operation cannot be resolved
    done(new ModofunError(404, 'NotFound', `No handler for: ${operation}`));
    return;
  }
}
1083066
def invoke(name, *params)
      op = @info.operations.find { |o| o.name == name.to_s }
      
      raise NoMethodError.new("No such operation #{name}") unless op

      jargs, jtypes = java_args(op.signature, params)
      @server.invoke @object_name, op.name, jargs, jtypes
    end
608021
function wrapper (server, level, ...data) {
  server.log(level, data.length === 1 ? data[0] : data)
}
777892
private Expression joinOperations(Expression result, String operation, Expression next) {
        if (!(result instanceof Operation)) {
            return new Operation(operation, result, next);
        }
        Operation farRight = (Operation) result;
        while (farRight.getRight() instanceof Operation) {
            farRight = (Operation) farRight.getRight();
        }
        if (!farRight.isProtect() && ("+".equals(farRight.getOperation()) || "-".equals(farRight.getOperation()))) {
            farRight.setRight(new Operation(operation, farRight.getRight(), next));
            return result;
        }

        return new Operation(operation, result, next);
    }
862063
function(operation, key, args, callback) {
		var operationArgs = [key].concat(args)
		if (callback) { operationArgs.push(callback) }
		storeAPI[operation].apply(this, operationArgs)
	}
248741
public void performOperation(Object resource, String operation,
            Object[] args) {
        CompensatingTransactionOperationRecorder recorder = operationFactory
                .createRecordingOperation(resource, operation);
        CompensatingTransactionOperationExecutor executor = recorder
                .recordOperation(args);

        executor.performOperation();

        // Don't push the executor until the actual operation passed.
        operationExecutors.push(executor);
    }
1032970
def create_command(self, name, operation, **kwargs):
        
        if not isinstance(operation, six.string_types):
            raise ValueError("Operation must be a string. Got '{}'".format(operation))

        name = ' '.join(name.split())

        client_factory = kwargs.get('client_factory', None)

        def _command_handler(command_args):
            op = CLICommandsLoader._get_op_handler(operation)
            client = client_factory(command_args) if client_factory else None
            result = op(client, **command_args) if client else op(**command_args)
            return result

        def arguments_loader():
            return list(extract_args_from_signature(CLICommandsLoader._get_op_handler(operation),
                                                    excluded_params=self.excluded_command_handler_args))

        def description_loader():
            return extract_full_summary_from_signature(CLICommandsLoader._get_op_handler(operation))

        kwargs['arguments_loader'] = arguments_loader
        kwargs['description_loader'] = description_loader

        cmd = self.command_cls(self.cli_ctx, name, _command_handler, **kwargs)
        return cmd
83382
def action(callback=None, name=None, path=None, methods=Method.GET, resource=None, tags=None,
           summary=None, middleware=None):
    # type: (Callable, Path, Path, Methods, Type[Resource], Tags, str, List[Any]) -> Operation
    
    # Generate action path
    path = path or '{key_field}'
    if name:
        path += name

    def inner(c):
        return Operation(c, path, methods, resource, tags, summary, middleware)
    return inner(callback) if callback else inner
834745
protected void handleOperation(Map<String, String> map, String operation) throws Exception {
        int index=operation.indexOf('.');
        if(index == -1)
            throw new IllegalArgumentException("operation " + operation + " is missing the protocol name");
        String prot_name=operation.substring(0, index);
        Protocol prot=ch.getProtocolStack().findProtocol(prot_name);
        if(prot == null) {
            log.error("protocol %s not found", prot_name);
            return; // less drastic than throwing an exception...
        }

        int args_index=operation.indexOf('[');
        String method_name;
        if(args_index != -1)
            method_name=operation.substring(index +1, args_index).trim();
        else
            method_name=operation.substring(index+1).trim();

        String[] args=null;
        if(args_index != -1) {
            int end_index=operation.indexOf(']');
            if(end_index == -1)
                throw new IllegalArgumentException("] not found");
            List<String> str_args=Util.parseCommaDelimitedStrings(operation.substring(args_index + 1, end_index));
            Object[] strings=str_args.toArray();
            args=new String[strings.length];
            for(int i=0; i < strings.length; i++)
                args[i]=(String)strings[i];
        }

        Method method=findMethod(prot, method_name, args);
        MethodCall call=new MethodCall(method);
        Object[] converted_args=null;
        if(args != null) {
            converted_args=new Object[args.length];
            Class<?>[] types=method.getParameterTypes();
            for(int i=0; i < args.length; i++)
                converted_args[i]=Util.convert(args[i], types[i]);
        }
        Object retval=call.invoke(prot, converted_args);
        if(retval != null)
            map.put(prot_name + "." + method_name, retval.toString());
    }