One-off code generation using append.
        
        If keyword args are provided, initialized using 
        :meth:`with_id_processor`.
492968
def append_once(cls, code, **kwargs):
        
        if kwargs:
            g = cls.with_id_processor()
            g._append_context(kwargs)
        else:
            g = cls()
        g.append(code)
        return g.code
155618
def generate_method_definition(func):
    
    indent = 4

    # initial definition
    method_definition = (" " * indent) + "def " + func["name"]

    # Here we just create a queue and put all the parameters
    # into the queue in the order that they were given,
    params_required = [
        param for param in func["arguments"] if param["is_required"]
    ]
    params_optional = [
        param for param in func["arguments"]
        if not param["is_required"]
    ]

    # Open the parameter definitions
    method_definition += "(self, "

    for param in params_required:
        # Put the parameter into the queue

        method_definition += param["name"]
        method_definition += ", "

    for param in params_optional:
        method_definition += param["name"]

        # Default methods not required
        method_definition += "=None, "

    # Peel off the final ", " and close off the parameter definition
    method_definition = method_definition.rstrip(", ") + "):\n"

    indent += 4

    # re-indent
    method_definition += " " * indent

    # Begin with description.

    method_definition += '"""' + func["description"]

    # re-indent
    method_definition += "\n\n" + " " * indent

    # Go through each parameter and insert description & type hint
    for param in params_required + params_optional:
        # Add the type
        method_definition += ":param " + DTYPE_MAPPING[param["type"].lower()]

        # Add the name
        method_definition += " " + param["name"] + ": "

        # Add the description
        method_definition += param["description"]

        # Add optionality & reindent
        method_definition += "\n" if param[
            "is_required"] else " (Optional)\n"

        method_definition += " " * indent

    open_index = func["returns"].find('(')
    close_index = func["returns"].find(
        ')', (open_index if open_index > -1 else 0))

    func["returns"] = func["returns"].replace("\t", " " * 4)
    return_string = func["returns"].replace("\n", "")

    if open_index < close_index and func["returns"][
                                    open_index + 1:close_index] in DTYPE_MAPPING:
        method_definition += ":rtype: " + DTYPE_MAPPING[
            func["returns"][open_index + 1:close_index]]

        func["returns"] = func["returns"].replace(
            func["returns"][open_index:close_index + 1], "")

        method_definition += "\n" + " " * indent

    method_definition += ":return: " + return_string

    for i in range(0, len(return_string) + 1, 80 - (indent + 2)):
        method_definition += return_string[i:i + (
                80 - (indent + 2))] + "\n" + " " * indent

    # Close it off & reindent
    method_definition += '"""' + "\n" + " " * indent

    # Create the params map
    params_map = "__params_map = {"

    # Save the indent
    params_indent, num_params = len(
        params_map), len(params_required) + len(params_optional)

    # Append the map to the method_definition
    method_definition += params_map

    # Go through the required parameters first
    for i, param in enumerate(params_required + params_optional):

        # append the methods to the map
        method_definition += "'" + param["name"] + "': " + param["name"]

        if not param["is_required"]:
            method_definition + " if " + param[
                "name"] + "is not None else None"

        # add commas or ending bracket if needed & reindent correctly
        method_definition += ",\n" + " " * indent + ' ' * params_indent if i + 1 < num_params else ""

    method_definition += '}\n\n' + ' ' * indent

    method_definition += "return self.make_request(SERVER_ADDRESS, '" + func["name"] + "', " \
                         + params_map.rstrip(" = {") + ", timeout=self.timeout)\n\n"

    return method_definition
961094
def pythonise(id, encoding='ascii'):
    """"""
    replace = {'-': '_', ':': '_', '/': '_'}
    func = lambda id, pair: id.replace(pair[0], pair[1])
    id = reduce(func, replace.iteritems(), id)
    id = '_%s' % id if id[0] in string.digits else id
    return id.encode(encoding)
1023256
def _compilecode(function, name, impl, args, varargs, kwargs):
    

    newcodestr, generatedname, impl_name = _generatecode(
        function=function, name=name, impl=impl,
        args=args, varargs=varargs, kwargs=kwargs
    )

    try:
        __file__ = getfile(function)
    except TypeError:
        __file__ = '<string>'

    # compile newcodestr
    code = compile(newcodestr, __file__, 'single')

    # define the code with the new function
    _globals = {}
    exec_(code, _globals)

    # get new code
    _var = _globals[generatedname]
    newco = get_function_code(_var)

    # get new consts list
    newconsts = list(newco.co_consts)

    if PY3:
        newcode = list(newco.co_code)
    else:
        newcode = [ord(co) for co in newco.co_code]

    consts_values = {impl_name: impl}

    # change LOAD_GLOBAL to LOAD_CONST
    index = 0
    newcodelen = len(newcode)
    while index < newcodelen:
        if newcode[index] == LOAD_GLOBAL:
            oparg = newcode[index + 1] + (newcode[index + 2] << 8)
            name = newco.co_names[oparg]
            if name in consts_values:
                const_value = consts_values[name]
                if const_value in newconsts:
                    pos = newconsts.index(const_value)
                else:
                    pos = len(newconsts)
                    newconsts.append(consts_values[name])
                newcode[index] = LOAD_CONST
                newcode[index + 1] = pos & 0xFF
                newcode[index + 2] = pos >> 8
        index += 1

    codeobj = getcodeobj(newconsts, newcode, newco, get_function_code(function))
    # instanciate a new function
    if function is None or isbuiltin(function):
        result = FunctionType(codeobj, {})

    else:
        result = type(function)(
            codeobj,
            get_function_globals(function),
            function.__name__,
            get_function_defaults(function),
            get_function_closure(function)
        )

    return result
446047
def ids(args):
    
    p = OptionParser(ids.__doc__)
    p.add_option("--until", default=None,
             help="Truncate the name and description at words [default: %default]")
    p.add_option("--description", default=False, action="store_true",
             help="Generate a second column with description [default: %default]")
    p.set_outfile()

    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    until = opts.until
    fw = must_open(opts.outfile, "w")
    for row in must_open(args):
        if row[0] == ">":
            row = row[1:].rstrip()
            if until:
                row = row.split(until)[0]

            atoms = row.split(None, 1)
            if opts.description:
                outrow = "\t".join(atoms)
            else:
                outrow = atoms[0]
            print(outrow, file=fw)

    fw.close()
366602
def _append(self, menu):
        ''''''
        menu.AppendCheckItem(self.id(), self.name, self.description)
        menu.Check(self.id(), self.checked)
1196845
def generate_func(self, as_global=False):
        
        keywords = []
        params_def = []
        params_doc = ""
        original_names = {}

        params = dict(
            (param['name'], param)
            for param in self.params
        )

        # parse the url required params, as sometimes they are skipped in the
        # parameters list of the definition
        for param in self.url_params:
            if param not in params:
                param = {
                    'name': param,
                    'required': True,
                    'description': '',
                    'validator': '',
                }
                params[param['name']] = param
            else:
                params[param]['required'] = True

        # split required and non-required params for the definition
        req_params = []
        nonreq_params = []
        for param in six.itervalues(params):
            if param['required']:
                req_params.append(param)
            else:
                nonreq_params.append(param)

        for param in req_params + nonreq_params:
            params_doc += self.create_param_doc(param) + "\n"
            local_name = param['name']
            # some params collide with python keywords, that's why we do
            # this switch (and undo it inside the function we generate)
            if param['name'] == 'except':
                local_name = 'except_'
            original_names[local_name] = param['name']
            keywords.append(local_name)
            if param['required']:
                params_def.append("%s" % local_name)
            else:
                params_def.append("%s=None" % local_name)

        func_head = 'def {0}(self, {1}):'.format(
            as_global and self.get_global_method_name() or self.name,
            ', '.join(params_def)
        )
        code_body = (
            '   _vars_ = locals()\n'
            '   _url = self._fill_url("{url}", _vars_, {url_params})\n'
            '   _original_names = {original_names}\n'
            '   _kwargs = dict((_original_names[k], _vars_[k])\n'
            '                   for k in {keywords} if _vars_[k])\n'
            '   return self._foreman.do_{http_method}(_url, _kwargs)')
        code_body = code_body.format(
            http_method=self.http_method.lower(),
            url=self.url,
            url_params=self.url_params,
            keywords=keywords,
            original_names=original_names,
        )

        code = [
            func_head,
            '   """',
            self.short_desc,
            '',
            params_doc,
            '   """',
            code_body,
        ]

        code = '\n'.join(code)

        six.exec_(code)

        function = locals()[self.name]
        # to ease debugging, all the funcs have the definitions attached
        setattr(function, 'defs', self)
        return function
699896
def elem_add(self, idx=None, name=None, **kwargs):
        

        idx = self.system.devman.register_element(dev_name=self._name, idx=idx)
        self.system.__dict__[self._group].register_element(self._name, idx)

        self.uid[idx] = self.n
        self.idx.append(idx)

        self.mdl_to.append(list())
        self.mdl_from.append(list())

        # self.n += 1

        if name is None:
            self.name.append(self._name + ' ' + str(self.n))
        else:
            self.name.append(name)

        # check mandatory parameters
        for key in self._mandatory:
            if key not in kwargs.keys():
                self.log(
                    'Mandatory parameter <{:s}.{:s}> missing'.format(
                        self.name[-1], key), ERROR)
                sys.exit(1)

        # set default values
        for key, value in self._data.items():
            self.__dict__[key].append(value)

        # overwrite custom values
        for key, value in kwargs.items():
            if key not in self._data:
                self.log(
                    'Parameter <{:s}.{:s}> is not used.'.format(
                        self.name[-1], key), WARNING)
                continue
            self.__dict__[key][-1] = value

            # check data consistency
            if not value and key in self._zeros:
                if key == 'Sn':
                    default = self.system.mva
                elif key == 'fn':
                    default = self.system.config.freq
                else:
                    default = self._data[key]
                self.__dict__[key][-1] = default
                self.log(
                    'Using default value for <{:s}.{:s}>'.format(
                        self.name[-1], key), WARNING)

        return idx
1091450
def run(self, *args):
        
        params = self.parser.parse_args(args)

        from_uuid = params.from_uuid
        to_uuid = params.to_uuid

        code = self.merge(from_uuid, to_uuid)

        return code
435062
def partial_append_action(fn, argument_keys=None):
    
    if isinstance(argument_keys, str):
        argument_keys = [argument_keys]
    argument_keys = argument_keys or []

    class PartialAppendAction(argparse.Action):
        def __init__(self,
                     option_strings,
                     dest,
                     const=None,
                     default=None,
                     required=False,
                     help=None,
                     type=None,
                     metavar=None,
                     nargs=None,
                     **kwargs):
            super(PartialAppendAction, self).__init__(
                option_strings=option_strings,
                dest=dest,
                nargs=len(argument_keys),
                const=const,
                default=default,
                required=required,
                metavar=metavar,
                type=type,
                help=help, **kwargs)

        def __call__(self, parser, namespace, values, option_string=None):
            items = copy.copy(getattr(namespace, self.dest, None)) or []

            # If no value was set default to empty list
            if values is None:
                values = []
            elif not isinstance(values, list):
                values = [values]

            if len(argument_keys) != len(values):
                raise ValueError("Unexpected number of values")

            # Generate keyword arguments for the input function
            kwargs = dict(list(zip(argument_keys, values)))
            f = functools.partial(fn, **kwargs)
            items.append(f)
            setattr(namespace, self.dest, items)

    return PartialAppendAction
1253620
def append_id(expr, id_col='append_id'):
    
    if hasattr(expr, '_xflow_append_id'):
        return expr._xflow_append_id(id_col)
    else:
        return _append_id(expr, id_col)
12217
def AppendUnique(self, delete_existing=0, **kw):
        
        kw = copy_non_reserved_keywords(kw)
        for key, val in kw.items():
            if SCons.Util.is_List(val):
                val = _delete_duplicates(val, delete_existing)
            if key not in self._dict or self._dict[key] in ('', None):
                self._dict[key] = val
            elif SCons.Util.is_Dict(self._dict[key]) and \
                 SCons.Util.is_Dict(val):
                self._dict[key].update(val)
            elif SCons.Util.is_List(val):
                dk = self._dict[key]
                if key == 'CPPDEFINES':
                    tmp = []
                    for i in val:
                        if SCons.Util.is_List(i):
                            if len(i) >= 2:
                                tmp.append((i[0], i[1]))
                            else:
                                tmp.append((i[0],))
                        elif SCons.Util.is_Tuple(i):
                            tmp.append(i)
                        else:
                            tmp.append((i,))
                    val = tmp
                    # Construct a list of (key, value) tuples.
                    if SCons.Util.is_Dict(dk):
                        tmp = []
                        for (k, v) in dk.items():
                            if v is not None:
                                tmp.append((k, v))
                            else:
                                tmp.append((k,))
                        dk = tmp
                    elif SCons.Util.is_String(dk):
                        dk = [(dk,)]
                    else:
                        tmp = []
                        for i in dk:
                            if SCons.Util.is_List(i):
                                if len(i) >= 2:
                                    tmp.append((i[0], i[1]))
                                else:
                                    tmp.append((i[0],))
                            elif SCons.Util.is_Tuple(i):
                                tmp.append(i)
                            else:
                                tmp.append((i,))
                        dk = tmp
                else:
                    if not SCons.Util.is_List(dk):
                        dk = [dk]
                if delete_existing:
                    dk = [x for x in dk if x not in val]
                else:
                    val = [x for x in val if x not in dk]
                self._dict[key] = dk + val
            else:
                dk = self._dict[key]
                if SCons.Util.is_List(dk):
                    if key == 'CPPDEFINES':
                        tmp = []
                        for i in dk:
                            if SCons.Util.is_List(i):
                                if len(i) >= 2:
                                    tmp.append((i[0], i[1]))
                                else:
                                    tmp.append((i[0],))
                            elif SCons.Util.is_Tuple(i):
                                tmp.append(i)
                            else:
                                tmp.append((i,))
                        dk = tmp
                        # Construct a list of (key, value) tuples.
                        if SCons.Util.is_Dict(val):
                            tmp = []
                            for (k, v) in val.items():
                                if v is not None:
                                    tmp.append((k, v))
                                else:
                                    tmp.append((k,))
                            val = tmp
                        elif SCons.Util.is_String(val):
                            val = [(val,)]
                        if delete_existing:
                            dk = list(filter(lambda x, val=val: x not in val, dk))
                            self._dict[key] = dk + val
                        else:
                            dk = [x for x in dk if x not in val]
                            self._dict[key] = dk + val
                    else:
                        # By elimination, val is not a list.  Since dk is a
                        # list, wrap val in a list first.
                        if delete_existing:
                            dk = list(filter(lambda x, val=val: x not in val, dk))
                            self._dict[key] = dk + [val]
                        else:
                            if not val in dk:
                                self._dict[key] = dk + [val]
                else:
                    if key == 'CPPDEFINES':
                        if SCons.Util.is_String(dk):
                            dk = [dk]
                        elif SCons.Util.is_Dict(dk):
                            tmp = []
                            for (k, v) in dk.items():
                                if v is not None:
                                    tmp.append((k, v))
                                else:
                                    tmp.append((k,))
                            dk = tmp
                        if SCons.Util.is_String(val):
                            if val in dk:
                                val = []
                            else:
                                val = [val]
                        elif SCons.Util.is_Dict(val):
                            tmp = []
                            for i,j in val.items():
                                if j is not None:
                                    tmp.append((i,j))
                                else:
                                    tmp.append(i)
                            val = tmp
                    if delete_existing:
                        dk = [x for x in dk if x not in val]
                    self._dict[key] = dk + val
        self.scanner_map_delete(kw)
605163
function (code, args, done) {
  var pyg = spawn(bin, args.toArray()),
      out = [],
      failed = false;

  pyg.on('error', function() {
    failed = true;
    done.apply(this, arguments);
  })

  pyg.stdout.setEncoding('utf8');
  pyg.stderr.setEncoding('utf8');

  var pusher = function(data) {
    out.push(data.toString());
  }

  pyg.stdout.on('data', pusher);
  pyg.stderr.on('data', pusher);

  pyg.on('exit', function (status) {
    // Return if done already called
    if(failed)
      return

    // pygmentize was successful
    if(status == 0)
      return done(null, out.join(''));

    // pygmentize was unsuccessful (cli error?)
    return done(out.join(''));
  });

  pyg.stdin.write(code);
  pyg.stdin.end();

}
237583
def generate_from_args(self, *args):
        
        return self.generate(**dict(zip(self.variable_args, args)))
526603
void generateRaCode(Definition def)
   {
      if (def.isUseRa())
      {
         generateClassCode(def, "Ra");
         generateClassCode(def, "RaMeta");
      }
      if (def.isGenAdminObject())
      {
         for (int i = 0; i < def.getAdminObjects().size(); i++)
         {
            generateMultiAdminObjectClassCode(def, "AoImpl", i);
            generateMultiAdminObjectClassCode(def, "AoInterface", i);
         }
      }
   }
99083
function(sMethod, args) {
            for (var i in this.ids) {
                for (var j in this.ids[i]) {
                    var oDD = this.ids[i][j];
                    if (! this.isTypeOfDD(oDD)) {
                        continue;
                    }
                    oDD[sMethod].apply(oDD, args);
                }
            }
        }
732421
def append(args):
    
    p = OptionParser(append.__doc__)
    p.add_option("--prepend", help="Prepend string to read names")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    bamfile, = args
    prepend = opts.prepend

    icmd = "samtools view -h {0}".format(bamfile)
    bamfile = bamfile.rsplit(".", 1)[0] + ".append.bam"
    ocmd = "samtools view -b -@ 64 - -o {0}".format(bamfile)
    p = Popen(ocmd, stdin=PIPE)
    for row in popen(icmd):
        if row[0] == '@':
            print(row.strip(), file=p.stdin)
        else:
            s = SamLine(row)
            if prepend:
                s.qname = prepend + "_" + s.qname
            else:
                s.update_readname()
            print(s, file=p.stdin)