Parse an arbitrary block of python code to get the value of a named argument
        from inside a function call
761635
def value_of_named_argument_in_function(argument_name, function_name, search_str,
                                        resolve_varname=False):
    
    try:
        search_str = unicode(search_str)
    except NameError:
        pass
    readline = StringIO(search_str).readline
    try:
        token_generator = tokenize.generate_tokens(readline)
        tokens = [SimplifiedToken(toknum, tokval) for toknum, tokval, _, _, _ in token_generator]
    except tokenize.TokenError as e:
        raise ValueError('search_str is not parse-able python code: ' + str(e))
    in_function = False
    is_var = False
    for i in range(len(tokens)):
        if (
            not in_function and
            tokens[i].typenum == tokenize.NAME and tokens[i].value == function_name and
            tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '('
        ):
            in_function = True
            continue
        elif (
            in_function and
            tokens[i].typenum == tokenize.NAME and tokens[i].value == argument_name and
            tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '='
        ):
            # value is set to another variable which we are going to attempt to resolve
            if resolve_varname and tokens[i+2].typenum == 1:
                is_var = True
                argument_name = tokens[i+2].value
                break

            # again, for a very specific usecase -- get the whole value and concatenate it
            # this will match something like _version.__version__
            j = 3
            while True:
                if tokens[i+j].value in (',', ')') or tokens[i+j].typenum == 58:
                    break
                j += 1

            return ''.join([t.value for t in tokens[i+2:i+j]]).strip()

    # this is very dumb logic, and only works if the function argument is set to a variable
    # which is set to a string value
    if is_var:
        for i in range(len(tokens)):
            if (
                tokens[i].typenum == tokenize.NAME and tokens[i].value == argument_name and
                tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '='
            ):
                return tokens[i+2].value.strip()

    return None
412334
def callfunc(self, argv=None):
        
        if not self.checked:
            self.check_arguments()
            self.checked = True
        namespace = self.parentparser.parse_args(argv or sys.argv[1:])
        return self.func(**vars(namespace))
1120802
function parseUnnamedCondition( $funcName, &$args, $tpl, &$text, &$text_len, &$cur_pos,
                                    $relatedTemplateName, $startLine, $startColumn, $rootNamespace )
    {
        $cond = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $text, $cur_pos, $cur_pos, $text_len, $rootNamespace );
        if ( !count( $cond ) )
        {
            $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                          $funcName, 'Not enough arguments' );
            return;

        }
        $args['condition'] = $cond;
    }
655792
def get_name_arg(argd, *argnames, default=None):
    
    val = None
    for argname in argnames:
        if argd[argname]:
            val = argd[argname].lower().strip()
            break
    return val if val else default
1198065
def parse_nni_variable(code):
    
    name, call = parse_annotation_function(code, 'variable')

    assert len(call.args) == 1, 'nni.variable contains more than one arguments'
    arg = call.args[0]
    assert type(arg) is ast.Call, 'Value of nni.variable is not a function call'
    assert type(arg.func) is ast.Attribute, 'nni.variable value is not a NNI function'
    assert type(arg.func.value) is ast.Name, 'nni.variable value is not a NNI function'
    assert arg.func.value.id == 'nni', 'nni.variable value is not a NNI function'

    name_str = astor.to_source(name).strip()
    keyword_arg = ast.keyword(arg='name', value=ast.Str(s=name_str))
    arg.keywords.append(keyword_arg)
    if arg.func.attr == 'choice':
        convert_args_to_dict(arg)

    return name, arg
783851
def split_func_name_args_params_handle(tokens):
    """"""
    internal_assert(len(tokens) == 2, "invalid function definition splitting tokens", tokens)
    func_name = tokens[0]
    func_args = []
    func_params = []
    for arg in tokens[1]:
        if len(arg) > 1 and arg[0] in ("*", "**"):
            func_args.append(arg[1])
        elif arg[0] != "*":
            func_args.append(arg[0])
        func_params.append("".join(arg))
    return [
        func_name,
        ", ".join(func_args),
        "(" + ", ".join(func_params) + ")",
    ]
17996
def getse(op, arg=None):
    
    try:
        return _se[op]
    except KeyError:
        # Continue to opcodes with an effect that depends on arg
        pass

    if arg is None:
        raise ValueError("Opcode stack behaviour depends on arg")

    def get_func_tup(arg, nextra):
        if arg > 0xFFFF:
            raise ValueError("Can only split a two-byte argument")
        return (nextra + 1 + (arg & 0xFF) + 2*((arg >> 8) & 0xFF),
                1)

    if op == CALL_FUNCTION:
        return get_func_tup(arg, 0)
    elif op == CALL_FUNCTION_VAR:
        return get_func_tup(arg, 1)
    elif op == CALL_FUNCTION_KW:
        return get_func_tup(arg, 1)
    elif op == CALL_FUNCTION_VAR_KW:
        return get_func_tup(arg, 2)

    elif op == BUILD_TUPLE:
        return arg, 1
    elif op == BUILD_LIST:
        return arg, 1
    elif python_version == '2.7' and op == BUILD_SET:
        return arg, 1
    elif op == UNPACK_SEQUENCE:
        return 1, arg
    elif op == BUILD_SLICE:
        return arg, 1
    elif op == DUP_TOPX:
        return arg, arg*2
    elif op == RAISE_VARARGS:
        return 1+arg, 1
    elif op == MAKE_FUNCTION:
        return 1+arg, 1
    elif op == MAKE_CLOSURE:
        if python_version == '2.4':
            raise ValueError("The stack effect of MAKE_CLOSURE depends on TOS")
        else:
            return 2+arg, 1
    else:
        raise ValueError("The opcode %r isn't recognized or has a special "
                         "flow control" % op)
1345412
def extractArgumentsFromCallStr(callStr):
    
    def isTuple(ele):
        return classname(ele) == 'Tuple'

    paramsStr = callStr.split('(', 1)[-1].rsplit(')', 1)[0].strip()

    root = ast.parse(paramsStr).body[0].value
    eles = root.elts if isTuple(root) else [root]

    # The ast module parses 'a, b' and '(a, b)' identically. Thus, ast.parse()
    # alone can't tell the difference between
    #
    #   ic(a, b)
    #
    # and
    #
    #   ic((a, b))
    #
    # Detect this situation and preserve whole tuples, e.g. '(a, b)', passed to
    # ic() by creating a new, temporary tuple around the original tuple and
    # parsing that.
    if paramsStr[0] == '(' and paramsStr[-1] == ')' and len(eles) > 1:
        newTupleStr = '(' + paramsStr + ", 'ignored')"
        argStrs = extractArgumentsFromCallStr(newTupleStr)[:-1]
        return argStrs

    indices = [
        max(0, e.col_offset - 1) if isTuple(e) else e.col_offset for e in eles]
    argStrs = [s.strip(' ,') for s in splitStringAtIndices(paramsStr, indices)]

    return argStrs
617056
def parse_all_arguments(func):
    
    args = dict()
    if sys.version_info < (3, 0):
        func_args = inspect.getargspec(func)
        if func_args.defaults is not None:
            val = len(func_args.defaults)
            for i, itm in enumerate(func_args.args[-val:]):
                args[itm] = func_args.defaults[i]
    else:
        func_args = inspect.signature(func)
        for itm in list(func_args.parameters)[1:]:
            param = func_args.parameters[itm]
            if param.default is not param.empty:
                args[param.name] = param.default
    return args
475897
def _parse_args(args, cls):
    
    
    d = _create_djset(args, cls)
    
    key_value_pair = args.get('<key>=<value>')
    key = args.get('<key>')
    func = None
    if args.get('add') and key_value_pair:
        fargs = tuple(args.get('<key>=<value>').split('='))
        if fargs[1]:
            func = d.set
    elif args.get('remove') and key:
        func = d.remove
        fargs = (args.get('<key>'),)
    kwargs = {'glob': args.get('--global')}
    if func:
        return func, fargs, kwargs
    else:
        return None, None, None
884923
def getArguments(names, local_dict=None, global_dict=None):
    """"""
    call_frame = sys._getframe(2)

    clear_local_dict = False
    if local_dict is None:
        local_dict = call_frame.f_locals
        clear_local_dict = True
    try:
        frame_globals = call_frame.f_globals
        if global_dict is None:
            global_dict = frame_globals

        # If `call_frame` is the top frame of the interpreter we can't clear its 
        # `local_dict`, because it is actually the `global_dict`.
        clear_local_dict = clear_local_dict and not frame_globals is local_dict

        arguments = []
        for name in names:
            try:
                a = local_dict[name]
            except KeyError:
                a = global_dict[name]
            arguments.append(numpy.asarray(a))
    finally:
        # If we generated local_dict via an explicit reference to f_locals,
        # clear the dict to prevent creating extra ref counts in the caller's scope
        # See https://github.com/pydata/numexpr/issues/310
        if clear_local_dict:
            local_dict.clear()

    return arguments
1255563
def tokenize_ofp_instruction_arg(arg):
    
    arg_re = re.compile("[^,()]*")
    try:
        rest = arg
        result = []
        while len(rest):
            m = arg_re.match(rest)
            if m.end(0) == len(rest):
                result.append(rest)
                return result
            if rest[m.end(0)] == '(':
                this_block, rest = _tokenize_paren_block(
                    rest, m.end(0) + 1)
                result.append(this_block)
            elif rest[m.end(0)] == ',':
                result.append(m.group(0))
                rest = rest[m.end(0):]
            else:  # is ')'
                raise Exception
            if len(rest):
                assert rest[0] == ','
                rest = rest[1:]
        return result
    except Exception:
        raise ryu.exception.OFPInvalidActionString(action_str=arg)
805852
def get_call_exprs(self, line):
        """"""
        line = line.lstrip()
        try:
            tree = self.ast.parse(line)
        except SyntaxError:
            return None
        for node in self.ast.walk(tree):
            if isinstance(node, self.ast.Call):
                offsets = []
                for arg in node.args:
                    # In Python 3.4 the col_offset is calculated wrong. See
                    # https://bugs.python.org/issue21295
                    if isinstance(arg, self.ast.Attribute) and (
                            (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)):
                        offsets.append(arg.col_offset - len(arg.value.id) - 1)
                    else:
                        offsets.append(arg.col_offset)
                if node.keywords:
                    line = line[:node.keywords[0].value.col_offset]
                    line = self.re.sub(r'\w+\s*=\s*$', '', line)
                else:
                    line = self.re.sub(r'\s*\)\s*$', '', line)
                offsets.append(len(line))
                args = []
                for i in range(len(node.args)):
                    args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
                return args
1057766
def get_function(self, name):
        
        p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name))
        if not p:
            raise NameError(name)
        return ValueRef(p, 'function', dict(module=self))
1039962
def _wrap_parse(code, filename):
        
        code = 'async def wrapper():\n' + indent(code, ' ')
        return ast.parse(code, filename=filename).body[0].body[0].value
1161424
function Parse (argv) {
	// Removing node/bin and called script name
	argv = argv.slice(2);

	// Returned object
	var args = {};
	
	var argName, argValue;

	// For each argument
	argv.forEach(function (arg, index) {
		// Seperate argument, for a key/value return
		arg = arg.split('=');

		// Retrieve the argument name
		argName = arg[0];
    
		// Remove "--" or "-"
		if (argName.indexOf('-') === 0) {
			argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
		}
		
		// Associate defined value or initialize it to "true" state
		argValue = (arg.length === 2)
			? parseFloat(arg[1]).toString() === arg[1] // check if argument is valid number
				? +arg[1]
				: arg[1]
			: true;

		// Finally add the argument to the args set
		args[argName] = argValue;
	});

	return args;
}
13592
def parse_call(self):
        
        assert self.pos < len(self.string)
        assert self.string[self.pos] == FUNC_DELIM

        start_pos = self.pos
        self.pos += 1

        ident = self._parse_ident()
        if not ident:
            # No function name.
            self.parts.append(FUNC_DELIM)
            return

        if self.pos >= len(self.string):
            # Identifier terminates string.
            self.parts.append(self.string[start_pos:self.pos])
            return

        if self.string[self.pos] != GROUP_OPEN:
            # Argument list not opened.
            self.parts.append(self.string[start_pos:self.pos])
            return

        # Skip past opening brace and try to parse an argument list.
        self.pos += 1
        args = self.parse_argument_list()
        if self.pos >= len(self.string) or \
           self.string[self.pos] != GROUP_CLOSE:
            # Arguments unclosed.
            self.parts.append(self.string[start_pos:self.pos])
            return

        self.pos += 1  # Move past closing brace.
        self.parts.append(Call(ident, args, self.string[start_pos:self.pos]))