Creates a code chunk representing an arrow function.
767821
public static Expression arrowFunction(JsDoc parameters, Statement body) {
    return FunctionDeclaration.createArrowFunction(parameters, body);
  }
674581
function generateDoc (name, code) {
  // get block comment from code
  const match = /\/\*\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//.exec(code)

  if (!match) {
    return null
  }

  // get text content inside block comment
  const comment = match[0].replace('/**', '')
    .replace('*/', '')
    .replace(/\n\s*\* ?/g, '\n')
    .replace(/\r/g, '')

  const lines = comment.split('\n')
  let line = ''

  // get next line
  function next () {
    line = lines.shift()
  }

  // returns true if current line is empty
  function empty () {
    return !line || !line.trim()
  }

  // returns true if there still is a current line
  function exists () {
    return line !== undefined
  }

  // returns true if current line is a header like 'Syntax:'
  function isHeader () {
    return /^(Name|Syntax|Description|Examples|See also)/i.test(line)
  }

  // returns true if the current line starts with an annotation like @param
  function isAnnotation () {
    return /^@/.test(line)
  }

  function skipEmptyLines () {
    while (exists() && empty()) next()
  }

  function stripLeadingSpaces (lines) {
    let spaces = null
    lines.forEach(function (line) {
      const match = /^ +/.exec(line)
      const s = match && match[0] && match[0].length
      if (s > 0 && (spaces === null || s < spaces)) {
        spaces = s
      }
    })

    if (spaces) {
      lines.forEach(function (line, index) {
        lines[index] = line.substring(spaces)
      })
    }
  }

  function parseDescription () {
    let description = ''

    while (exists() && !isHeader() && !isAnnotation()) {
      description += line + '\n'

      next()
    }

    // remove trailing returns
    while (description.charAt(description.length - 1) === '\n') {
      description = description.substring(0, description.length - 1)
    }

    doc.description = description
  }

  function parseSyntax () {
    if (/^syntax/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        doc.syntax.push(line)
        next()
      }
      stripLeadingSpaces(doc.syntax)

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseWhere () {
    if (/^where/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        doc.where.push(line)
        next()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseExamples () {
    if (/^example/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && (empty() || line.charAt(0) === ' ')) {
        doc.examples.push(line)
        next()
      }
      stripLeadingSpaces(doc.examples)

      if (doc.examples.length > 0 && doc.examples[doc.examples.length - 1].trim() === '') {
        doc.examples.pop()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function parseSeeAlso () {
    if (/^see also/i.test(line)) {
      next()
      skipEmptyLines()

      while (exists() && !empty()) {
        const names = line.split(',')
        doc.seeAlso = doc.seeAlso.concat(names.map(function (name) {
          return name.trim()
        }))
        next()
      }

      skipEmptyLines()

      return true
    }
    return false
  }

  function trim (text) {
    return text.trim()
  }

  // replace characters like '<' with HTML entities like '&lt;'
  function escapeTags (text) {
    return text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
  }

  function parseParameters () {
    let count = 0
    let match
    do {
      match = /\s*@param\s*\{(.*)}\s*\[?(\w*)]?\s*(.*)?$/.exec(line)
      if (match) {
        next()

        count++
        const annotation = {
          name: match[2] || '',
          description: (match[3] || '').trim(),
          types: match[1].split('|').map(trim).map(escapeTags)
        }
        doc.parameters.push(annotation)

        // TODO: this is an ugly hack to extract the default value
        const index = annotation.description.indexOf(']')
        let defaultValue = null
        if (index !== -1) {
          defaultValue = annotation.description.substring(1, index).trim()
          annotation.description = annotation.description.substring(index + 1).trim()
        }

        // multi line description (must be non-empty and not start with @param or @return)
        while (exists() && !empty() && !/^\s*@/.test(line)) {
          const lineTrim = line.trim()
          const separator = (lineTrim[0] === '-' ? '</br>' : ' ')
          annotation.description += separator + lineTrim
          next()
        }

        if (defaultValue !== null) {
          annotation.description += ' Default value: ' + defaultValue + '.'
        }
      }
    } while (match)

    return count > 0
  }

  function parseReturns () {
    const match = /\s*@returns?\s*\{(.*)}\s*(.*)?$/.exec(line)
    if (match) {
      next()

      doc.returns = {
        description: match[2] || '',
        types: match[1].split('|').map(trim).map(escapeTags)
      }

      // multi line description
      while (exists() && !empty() && !/^\s*@/.test(line)) {
        doc.returns.description += ' ' + line.trim()
        next()
      }

      return true
    }
    return false
  }

  // initialize doc
  let doc = {
    name: name,
    description: '',
    syntax: [],
    where: [],
    examples: [],
    seeAlso: [],
    parameters: [],
    returns: null
  }

  next()
  skipEmptyLines()
  parseDescription()

  do {
    skipEmptyLines()

    const handled = parseSyntax() ||
        parseWhere() ||
        parseExamples() ||
        parseSeeAlso() ||
        parseParameters() ||
        parseReturns()

    if (!handled) {
      // skip this line, no one knows what to do with it
      next()
    }
  } while (exists())

  return doc
}
49029
function getFunctionDefinitions(variable) {
            const functionDefinitions = [];

            variable.defs.forEach(def => {
                const { type, node } = def;

                // FunctionDeclarations
                if (type === "FunctionName") {
                    functionDefinitions.push(node);
                }

                // FunctionExpressions
                if (type === "Variable" && node.init &&
                    (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
                    functionDefinitions.push(node.init);
                }
            });
            return functionDefinitions;
        }
627434
def to_code(self, from_function=False):
        """"""

        num_fastnames = sum(1 for op, arg in self.code if isopcode(op) and op in haslocal)
        is_function = self.newlocals or num_fastnames > 0 or len(self.args) > 0
        nested = is_function and from_function

        co_flags = {op[0] for op in self.code}

        is_generator = self.force_generator or (YIELD_VALUE in co_flags or YIELD_FROM in co_flags)
        no_free = (not self.freevars) and (not co_flags & hasfree)

        if version_info >= (3, 5):
            is_native_coroutine = bool(self.force_coroutine or (co_flags & coroutine_opcodes))
            assert not (is_native_coroutine and self.force_iterable_coroutine)

        co_flags =\
            (not(STORE_NAME in co_flags or LOAD_NAME in co_flags or DELETE_NAME in co_flags)) |\
            (self.newlocals and CO_NEWLOCALS) |\
            (self.varargs and CO_VARARGS) |\
            (self.varkwargs and CO_VARKEYWORDS) |\
            (is_generator and CO_GENERATOR) |\
            (no_free and CO_NOFREE) |\
            (nested and CO_NESTED)

        if version_info >= (3, 5):
            co_flags |= (is_native_coroutine and CO_COROUTINE) |\
                        (self.force_iterable_coroutine and CO_ITERABLE_COROUTINE) |\
                        (self.future_generator_stop and CO_FUTURE_GENERATOR_STOP)

        co_consts = [self.docstring]
        co_names = []
        co_varnames = list(self.args)
        co_freevars = tuple(self.freevars)

        # Find all cellvars beforehand for two reasons
        # Need the number of them to construct the numeric arg for ops in hasfree
        # Need to put args which are cells in the beginning of co_cellvars
        cellvars = {arg for op, arg in self.code
                    if isopcode(op) and op in hasfree
                    and arg not in co_freevars}
        co_cellvars = [jumps for jumps in self.args if jumps in cellvars]

        def index(seq, item, eq=True, can_append=True):
            for i, x in enumerate(seq):
                if x == item if eq else x is item:
                    return i
            if can_append:
                seq.append(item)
                return len(seq) - 1
            else:
                raise IndexError("Item not found")

        jumps = []
        label_pos = {}
        lastlineno = self.firstlineno
        lastlinepos = 0
        co_code = bytearray()
        co_lnotab = bytearray()

        for i, (op, arg) in enumerate(self.code):
            if isinstance(op, Label):
                label_pos[op] = len(co_code)
            elif op is SetLineno:
                incr_lineno = arg - lastlineno
                incr_pos = len(co_code) - lastlinepos
                lastlineno = arg
                lastlinepos += incr_pos
                if incr_lineno != 0 or incr_pos != 0:
                    while incr_pos > 255:
                        co_lnotab += b"\xFF\0"
                        incr_pos -= 255
                    while incr_lineno > 255:
                        co_lnotab += (0xFF00|incr_pos).to_bytes(2, "little")
                        incr_pos = 0
                        incr_lineno -= 255
                    if incr_pos or incr_lineno:
                        co_lnotab += bytes((incr_pos, incr_lineno))
            elif op == opcode.EXTENDED_ARG:
                self.code[i + 1][1] |= 1 << 32
            elif op not in hasarg:
                co_code.append(op)
            else:
                if op in hasconst:
                    if isinstance(arg, Code) and\
                            i + 2 < len(self.code) and self.code[i + 2][0] in hascode:
                        arg = arg.to_code(from_function=is_function)
                        assert arg is not None
                    arg = index(co_consts, arg, 0)
                elif op in hasname:
                    arg = index(co_names, arg)
                elif op in hasjump:
                    jumps.append((len(co_code), arg))
                    co_code += op.to_bytes(3, "little")
                    continue
                elif op in haslocal:
                    arg = index(co_varnames, arg)
                elif op in hascompare:
                    arg = index(cmp_op, arg, can_append=False)
                elif op in hasfree:
                    try:
                        arg = index(co_freevars, arg, can_append=False) + len(cellvars)
                    except IndexError:
                        arg = index(co_cellvars, arg)
                if arg > 0xFFFF:
                    co_code += (opcode.EXTENDED_ARG | ((arg & 0xFFFF0000) >> 8)).to_bytes(3, "little")
                co_code += (op | (arg << 8)).to_bytes(3, "little")

        for pos, label in jumps:
            jump = label_pos[label]
            if co_code[pos] in hasjrel:
                jump -= pos + 3
            if jump > 0xFFFF:
                raise NotImplementedError("Extended jumps not implemented")
            co_code[pos + 1] = jump & 0xFF
            co_code[pos + 2] = jump >> 8

        co_argcount = len(self.args) - self.varargs - self.varkwargs - self.kwonly
        co_stacksize = self._compute_stacksize()

        return CodeType(co_argcount, self.kwonly, len(co_varnames), co_stacksize, co_flags,
                        bytes(co_code), tuple(co_consts), tuple(co_names), tuple(co_varnames),
                        self.filename, self.name, self.firstlineno, bytes(co_lnotab), co_freevars,
                        tuple(co_cellvars))
552259
def build_code(self, lang, body):
        """"""
        self.out.append("```" + lang)
        self.build_markdown(lang, body)
        self.out.append("```")
895338
function createDeclaration(prop, value, node) {
		let decl = postcss.decl({
			prop: prop,
			value: value,
			source: node.source
		});

		return decl;
	}
869208
function makeFunctionLongform(fixer, node) {
            const firstKeyToken = node.computed
                ? sourceCode.getTokenBefore(node.key, isOpeningBracketToken)
                : sourceCode.getFirstToken(node.key)
            const lastKeyToken = node.computed
                ? sourceCode.getTokenAfter(node.key, isClosingBracketToken)
                : sourceCode.getLastToken(node.key)
            const keyText = sourceCode.text.slice(
                firstKeyToken.range[0],
                lastKeyToken.range[1]
            )
            let functionHeader = "function"

            if (node.value.async) {
                functionHeader = `async ${functionHeader}`
            }
            if (node.value.generator) {
                functionHeader = `${functionHeader}*`
            }

            return fixer.replaceTextRange(
                [node.range[0], lastKeyToken.range[1]],
                `${keyText}: ${functionHeader}`
            )
        }
21677
def codegen(cc):
    

    import inspect

    def format_desc(obj, indent):
        linelen = 75 - indent
        if isinstance(obj, six.string_types):
            raw = obj
        else:
            try:
                raw = obj.qualifiers['description'].value
            except KeyError:
                return ''
        txt = ''
        beg = 0
        end = 0
        while beg < len(raw):
            beg = end
            end += linelen
            while beg < len(raw) and raw[beg].isspace():
                beg = beg+1
            while end < len(raw) and end > beg and not raw[end].isspace():
                end = end-1
            if beg == end: # a long URL
                while end < len(raw) and not raw[end].isspace():
                    end += 1
            line = raw[beg:end]
            line = line.replace('\n', ' ')
            line = line.replace('\r', '')
            txt += '\n%s%s'% (''.ljust(indent), line)
        return txt

    #################
    def map_value(obj, val):
        rv = str(val)
        if 'ValueMap' not in obj.qualifiers:
            return rv
        if 'Values' not in obj.qualifiers:
            return rv
        vals = [str(x) for x in obj.qualifiers['Values'].value]
        maps = [str(x) for x in obj.qualifiers['ValueMap'].value]
        d = dict(zip(maps, vals))
        try:
            tmp = d[str(val)]
            rv = ''
            for ch in tmp:
                rv += ch.isalnum() and ch or '_'
        except KeyError:
            pass
        return rv

    #################
    def type_hint(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                tx = "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                tx = "pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if hasattr(obj, 'value') and obj.value is not None:
            defval = str(obj.value)
        else:
            defval = ''
        if not tx.startswith('pywbem.'):
            if tx == 'boolean':
                tx = 'bool(%s)' % defval
            elif tx == 'datetime':
                tx = 'pywbem.CIMDateTime()'
            elif tx == 'string':
                tx = "''"
            else:
                tx = 'pywbem.%s(%s)' % (tx.capitalize(), defval)
        if 'valuemap' in obj.qualifiers:
            if defval:
                defval = map_value(obj, defval)
            else:
                defval = '<VAL>'
            tx = 'self.Values.%s%s.%s' % \
                    (method_name and '%s.'%method_name or '',
                     obj.name, defval)
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        return tx
    #################
    def type_str(obj, method_name=None):
        if hasattr(obj, 'type'):
            tx = obj.type
            if 'embeddedinstance' in obj.qualifiers:
                return "pywbem.CIMInstance(classname='%s', ...)" % \
                        obj.qualifiers['embeddedinstance'].value
            elif tx == 'reference':
                return "REF (pywbem.CIMInstanceName(classname='%s', ...)" % \
                        obj.reference_class
        else:
            tx = obj.return_type
        if tx == 'boolean':
            tx = 'bool'
        elif tx == 'datetime':
            tx = 'pywbem.CIMDateTime'
        elif tx == 'string':
            tx = 'unicode'
        else:
            tx = 'pywbem.%s' % tx.capitalize()
        if hasattr(obj, 'is_array') and obj.is_array:
            tx = '[%s,]' % tx
        if 'valuemap' in obj.qualifiers:
            tx += ' self.Values.%s%s' % \
                    (method_name and '%s.' % method_name or '', obj.name)
        return tx
    #################
    def is_required(obj):
        if 'required' in obj.qualifiers and obj.qualifiers['required'].value:
            return '(Required)'
        return ''
    #################
    def build_val_map(obj):
        vm = obj.qualifiers['valuemap'].value
        if 'values' in obj.qualifiers:
            vals = obj.qualifiers['values'].value
        else:
            vals = vm
        tmap = zip(vals, vm)
        map = []
        for t in tmap:
            nname = ''
            for ch in t[0]:
                if ch.isalnum():
                    nname += ch
                else:
                    nname += '_'
            if hasattr(obj, 'return_type'):
                tp = obj.return_type
            else:
                tp = obj.type
            if tp == 'string':
                val = "'%s'" % t[1]
            else:
                try:
                    int(t[1])
                    val = 'pywbem.%s(%s)' % (tp.capitalize(), t[1])
                except ValueError:
                    val = t[1]
                    nname = "# "+nname
            map.append((nname, val))
        return map

    valuemaps = {}

    for obj in cc.properties.values() + cc.methods.values():
        if 'valuemap' in obj.qualifiers:
            valuemaps[obj.name] = {'<vms>':build_val_map(obj)}

    for meth in cc.methods.values():
        for parm in meth.parameters.values():
            if 'valuemap' in parm.qualifiers:
                if meth.name not in valuemaps:
                    valuemaps[meth.name] = {}
                valuemaps[meth.name][parm.name] = build_val_map(parm)

    mappings = {'classname':cc.classname,
                'classname_l':cc.classname.lower()}
    isAssoc = 'association' in cc.qualifiers

    code = '''"""Python Provider for %(classname)s

Instruments the CIM class %(classname)s

"""

import pywbem

class %(classname)sProvider(pywbem.CIMProvider):
    """Instrument the CIM class %(classname)s \n''' % mappings
    code += format_desc(cc, 4)
    code += '''
    """'''


    args = inspect.getargspec(CIMProvider.get_instance)[0]
    args = ', '.join(args)
    code += '''

    def __init__ (self, env):
        logger = env.get_logger()
        logger.log_debug('Initializing provider %%s from %%s' \\
                %% (self.__class__.__name__, __file__))
        # If you will be filtering instances yourself according to
        # property_list, role, result_role, and result_class_name
        # parameters, set self.filter_results to False
        # self.filter_results = False

    def get_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.get_instance()' \\
                %% self.__class__.__name__)
        ''' % (args, CIMProvider.get_instance.__doc__)
    keyProps = [p for p in cc.properties.values() \
                if 'key' in p.qualifiers]
    code += '''
        ux = model.update_existing

        # TODO fetch system resource matching the following keys:'''
    for kp in keyProps:
        code += '''
        #   model['%s']''' % kp.name
    code += '\n'
    props = cc.properties.values()
    props.sort()
    for prop in props:
        if 'key' in prop.qualifiers:
            continue
        #line = "#ux(%s=%s) # TODO (type = %s) %s" % \
        #        (prop.name, type_hint(prop), type_str(prop), is_required(prop))
        line = "#ux(%s=%s) # TODO %s" % \
                (prop.name, type_hint(prop), is_required(prop))
        code += '''
        %s''' % line

    args = inspect.getargspec(CIMProvider.enum_instances)[0]
    args = ', '.join(args)
    code += '''
        return model

    def enum_instances(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.enum_instances()' \\
                %% self.__class__.__name__)

        while False: # TODO more instances?
            # TODO fetch system resource
            # Key properties''' % (args, CIMProvider.enum_instances.__doc__)
    for kp in keyProps:
        if kp.name == 'CreationClassName':
            line = "model['%s'] = '%s'" % (kp.name, cc.classname)
        else:
            line = "#model['%s'] = # TODO (type = %s)" % \
                    (kp.name, type_str(kp))
        code += '''
            %s''' % line
    code += '''
            if keys_only:
                yield model
            else:
                try:
                    yield self.get_instance(env, model, cim_class)
                except pywbem.CIMError as exc:
                    num, msg = exc.args
                    if num not in (pywbem.CIM_ERR_NOT_FOUND,
                                   pywbem.CIM_ERR_ACCESS_DENIED):
                        raise\n'''

    args = inspect.getargspec(CIMProvider.set_instance)[0]
    args = ', '.join(args)
    code += '''
    def set_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.set_instance()' \\
                %% self.__class__.__name__)
        # TODO create or modify the instance
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        return instance''' % (args, CIMProvider.set_instance.__doc__)

    args = inspect.getargspec(CIMProvider.delete_instance)[0]
    args = ', '.join(args)
    code += '''

    def delete_instance(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.delete_instance()' \\
                %% self.__class__.__name__)

        # TODO delete the resource
        raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
        ''' % (args, CIMProvider.delete_instance.__doc__)

    for method in cc.methods.values():
        inParms = [p for p in method.parameters.values() if \
                    'in' in p.qualifiers and p.qualifiers['in'].value]
        outParms = [p for p in method.parameters.values() if \
                    'out' in p.qualifiers and p.qualifiers['out'].value]
        code += '''
    def cim_method_%s(self, env, object_name, method''' % method.name.lower()
        for p in inParms:
            code += ''',\n%sparam_%s''' % (''.rjust(len(method.name)+20),
                                           p.name.lower())
        code += '''):
        """Implements %s.%s()\n''' % (cc.classname, method.name)
        code += format_desc(method, 8)

        code += '''
        Keyword arguments:
        env -- Provider Environment (pycimmb.ProviderEnvironment)
        object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
            specifying the object on which the method %s()
            should be invoked.
        method -- A pywbem.CIMMethod representing the method meta-data''' \
                % method.name

        for p in inParms:
            code += '''
        param_%s --  The input parameter %s (type %s) %s''' \
                    % (p.name.lower(), p.name, type_str(p, method.name),
                       is_required(p))
            code += format_desc(p, 12)

        code += '''

        Returns a two-tuple containing the return value (type %s)
        and a dictionary with the out-parameters

        Output parameters:''' % type_str(method)

        if not outParms:
            code += ' none'
        else:
            for p in outParms:
                code += '''
        %s -- (type %s) %s''' % (p.name, type_str(p, method.name),
                                 is_required(p))
                code += format_desc(p, 12)

        code += '''

        Possible Errors:
        CIM_ERR_ACCESS_DENIED
        CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
            unrecognized or otherwise incorrect parameters)
        CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
            exist in the specified namespace)
        CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
            the invocation request)
        CIM_ERR_FAILED (some other unspecified error occurred)

        """

        logger = env.get_logger()
        logger.log_debug('Entering %%s.cim_method_%s()' \\
                %% self.__class__.__name__)

        # TODO do something
        raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
        out_params = {}''' % method.name.lower()

        for p in outParms:
            code += '''
        #out_params['%s'] = %s # TODO''' % \
                (p.name.lower(), type_hint(p, method.name))

        code += '''
        rval = None # TODO (type %s)
        return (rval, out_params)
        ''' % type_str(method)

    if isAssoc:
        args = inspect.getargspec(CIMProvider.references)[0]
        args = format_desc(', '.join(args), 19).strip()
        code += '''
    def references(%s):
        """%s"""

        logger = env.get_logger()
        logger.log_debug('Entering %%s.references()' \\
                %% self.__class__.__name__)
        ch = env.get_cimom_handle()
        # This is a common pattern.  YMMV''' % \
                (args, CIMProvider.references.__doc__)
        refprops = []
        for prop in cc.properties.values():
            if prop.reference_class is not None:
                refprops.append((prop.name, prop.reference_class))
        for refprop in refprops:
            code += '''
        if (not role or role.lower() == '%(refpropnamel)s') and \\
           pywbem.is_subclass(ch, object_name.namespace,
                       sub=object_name.classname,
                       super='%(rolecname)s'):
            model['%(refpropname)s'] = object_name
            yield model # TODO: Add other REF properties.
                        # Yield association instances where
                        # object_name is %(refpropnamel)s.
                        # Only appropriate if object_name.classname
                        # is '%(rolecname)s' or a subclass.\n''' \
                               % {'refpropname':refprop[0],
                                  'refpropnamel':refprop[0].lower(),
                                  'rolecname':refprop[1]}

    if valuemaps:
        code += '''
    class Values(object):'''
        for group, maps in valuemaps.items():
            code += '''
        class %s(object):''' % group
            if '<vms>' in maps:
                for value, vm in maps['<vms>']:
                    if value in maps:
                        value = value+'_'
                    code += '''
            %s = %s''' % (value, vm)
            for pname, vms in maps.items():
                if pname == '<vms>':
                    continue
                code += '''
            class %s(object):''' % pname
                for value, vm in vms:
                    code += '''
                %s = %s''' % (value, vm)
            code += '\n'

    code += '''
## end of class %(classname)sProvider

def get_providers(env):
    %(classname_l)s_prov = %(classname)sProvider(env)
    return {'%(classname)s': %(classname_l)s_prov}
''' % mappings

    owtypes = ['1', 'Instance']
    pegtypes = ['2', 'Instance']
    if isAssoc:
        owtypes[0] += ',3'
        owtypes[1] += ', Associator'
        pegtypes[0] += ',3'
        pegtypes[1] += ', Associator'
    if cc.methods:
        owtypes[0] += ',6'
        owtypes[1] += ', Method'
        pegtypes[0] += ',5'
        pegtypes[1] += ', Method'
    mof = '''
// OpenWBEM Provider registration for %(classname)s
instance of OpenWBEM_PyProviderRegistration
{
    InstanceID = "<org:product:%(classname)s:unique_id>"; // TODO
    NamespaceNames = {"root/cimv2"}; // TODO
    ClassName = "%(classname)s";
    ProviderTypes = {%(owtypeNums)s};  // %(owtypeStrs)s
    ModulePath = "/usr/lib/pycim/%(classname)sProvider.py";  // TODO
};

// Pegasus Provider registration for %(classname)s
instance of PG_ProviderModule
{
    Name = "/usr/lib/pycim/%(classname)sProvider.py";
    InterfaceType = "Python";
    InterfaceVersion = "1.0.0";
    Location = "/usr/lib/pycim/%(classname)sProvider.py";
    UserContext = 2; // Requestor
    Vendor = "TODO"; // TODO
    Version = "1.0";
};
instance of PG_Provider
{
    Name = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
};
instance of PG_ProviderCapabilities
{
    CapabilityID = "%(classname)s";
    ProviderModuleName = "/usr/lib/pycim/%(classname)sProvider.py";
    ProviderName = "%(classname)s";
    ClassName = "%(classname)s";
    Namespaces = {"root/cimv2"}; // TODO
    ProviderType = {%(pegtypeNum)s}; // %(pegtypeStr)s
};\n''' % {'classname': cc.classname,
           'owtypeNums': owtypes[0],
           'owtypeStrs': owtypes[1],
           'pegtypeNum': pegtypes[0],
           'pegtypeStr': pegtypes[1]}


    return code, mof
968039
function createChunk(type, data) {
	const length = typeof data != 'undefined' ? data.length : 0;
	const chunk = Buffer.alloc(4 + 4 + length + 4);

	chunk.writeUInt32BE(length, 0);
	chunk.fill(type, 4, 8, 'utf8');
	if (typeof data != 'undefined') {
		chunk.fill(data, 8, chunk.length - 4);
	}
	chunk.writeUInt32BE(crc32(chunk.slice(4, -4)), chunk.length - 4);

	return chunk;
}
31054
def _construct_first_indent(self, pos):
        
        cols = []
        void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
        available_width = self._indent

        if self._tree.depth(pos) > 0:
            connector = self._construct_connector(pos)
            if connector is not None:
                width = connector.pack()[0]
                if width > available_width:
                    raise NoSpaceError()
                available_width -= width
                if self._tree.next_sibling_position(pos) is not None:
                    barw = urwid.SolidFill(self._arrow_vbar_char)
                    below = urwid.AttrMap(barw, self._arrow_vbar_att or
                                          self._arrow_att)
                else:
                    below = void
                # pile up connector and bar
                spacer = urwid.Pile([('pack', connector), below])
                cols.append((width, spacer))

            #arrow tip
            awidth, at = self._construct_arrow_tip(pos)
            if at is not None:
                if awidth > available_width:
                    raise NoSpaceError()
                available_width -= awidth
                at_spacer = urwid.Pile([('pack', at), void])
                cols.append((awidth, at_spacer))

            # bar between connector and arrow tip
            if available_width > 0:
                barw = urwid.SolidFill(self._arrow_hbar_char)
                bar = urwid.AttrMap(
                    barw, self._arrow_hbar_att or self._arrow_att)
                hb_spacer = urwid.Pile([(1, bar), void])
                cols.insert(1, (available_width, hb_spacer))
        return cols
784712
def _generate_ndarray_function_code(handle, name, func_name, signature_only=False):
    """"""
    real_name = ctypes.c_char_p()
    desc = ctypes.c_char_p()
    num_args = mx_uint()
    arg_names = ctypes.POINTER(ctypes.c_char_p)()
    arg_types = ctypes.POINTER(ctypes.c_char_p)()
    arg_descs = ctypes.POINTER(ctypes.c_char_p)()
    key_var_num_args = ctypes.c_char_p()
    ret_type = ctypes.c_char_p()

    check_call(_LIB.MXSymbolGetAtomicSymbolInfo(
        handle, ctypes.byref(real_name), ctypes.byref(desc),
        ctypes.byref(num_args),
        ctypes.byref(arg_names),
        ctypes.byref(arg_types),
        ctypes.byref(arg_descs),
        ctypes.byref(key_var_num_args),
        ctypes.byref(ret_type)))
    narg = int(num_args.value)
    arg_names = [py_str(arg_names[i]) for i in range(narg)]
    arg_types = [py_str(arg_types[i]) for i in range(narg)]
    key_var_num_args = py_str(key_var_num_args.value)
    ret_type = py_str(ret_type.value) if ret_type.value is not None else ''
    doc_str = _build_doc(name,
                         py_str(desc.value),
                         arg_names,
                         arg_types,
                         [py_str(arg_descs[i]) for i in range(narg)],
                         key_var_num_args,
                         ret_type)

    dtype_name = None
    arr_name = None
    ndsignature = []
    signature = []
    ndarg_names = []
    kwarg_names = []
    for i in range(narg):
        name, atype = arg_names[i], arg_types[i]
        if name == 'dtype':
            dtype_name = name
            signature.append('%s=_Null'%name)
        elif atype.startswith('NDArray') or atype.startswith('Symbol'):
            assert not arr_name, \
                "Op can only have one argument with variable " \
                "size and it must be the last argument."
            if atype.endswith('[]'):
                ndsignature.append('*%s'%name)
                arr_name = name
            else:
                ndsignature.append('%s=None'%name)
                ndarg_names.append(name)
        else:
            signature.append('%s=_Null'%name)
            kwarg_names.append(name)
    signature.append('out=None')
    signature.append('name=None')
    signature.append('**kwargs')
    signature = ndsignature + signature

    code = []
    if arr_name:
        code.append("""
def %s(*%s, **kwargs):"""%(func_name, arr_name))
        if not signature_only:
            code.append("""
    ndargs = []
    for i in {}:
        assert isinstance(i, NDArrayBase), \\
            "Positional arguments must have NDArray type, " \\
            "but got %s"%str(i)
        ndargs.append(i)""".format(arr_name))
            if dtype_name is not None:
                code.append("""
    if '%s' in kwargs:
        kwargs['%s'] = _np.dtype(kwargs['%s']).name"""%(
            dtype_name, dtype_name, dtype_name))
            code.append("""
    _ = kwargs.pop('name', None)
    out = kwargs.pop('out', None)
    keys = list(kwargs.keys())
    vals = list(kwargs.values())""")
    else:
        code.append("""
def %s(%s):"""%(func_name, ', '.join(signature)))
        if not signature_only:
            code.append("""
    ndargs = []
    keys = list(kwargs.keys())
    vals = list(kwargs.values())""")
            # NDArray args
            for name in ndarg_names: # pylint: disable=redefined-argument-from-local
                code.append("""
    if {name} is not None:
        assert isinstance({name}, NDArrayBase), \\
            "Argument {name} must have NDArray type, but got %s"%str({name})
        ndargs.append({name})""".format(name=name))
            # kwargs
            for name in kwarg_names: # pylint: disable=redefined-argument-from-local
                code.append("""
    if %s is not _Null:
        keys.append('%s')
        vals.append(%s)"""%(name, name, name))
            # dtype
            if dtype_name is not None:
                code.append("""
    if %s is not _Null:
        keys.append('%s')
        vals.append(_np.dtype(%s).name)"""%(dtype_name, dtype_name, dtype_name))

    if not signature_only:
        code.append("""
    return _imperative_invoke(%d, ndargs, keys, vals, out)"""%(
        handle.value))
    else:
        code.append("""
    return (0,)""")

    doc_str_lines = _os.linesep+''.join(['    '+s if s.strip() else s
                                         for s in 'r"""{doc_str}"""'.format(doc_str=doc_str)
                                         .splitlines(True)])
    code.insert(1, doc_str_lines)
    return ''.join(code), doc_str
151590
function generateCode(filepath) {
    var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd';


    // support 4 types of output as follows:
    // amd/commonjs/global/umd
    var choice = {
        amd: {
            prefix: 'define([\'module\', \'exports\'], function (module, exports) {',
            suffix: '});'
        },
        commonjs: {
            prefix: '',
            suffix: ''
        },
        global: {
            prefix: '(function (module, exports) {',
            suffix: '})(this, this.exports = this.exports || {});'
        },
        umd: {
            prefix: '\n                (function (global, factory) {\n                    typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n                    typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n                    (factory(global, global.exports = global.exports || {}));\n                }(this, (function (module, exports) {\n            ',
            suffix: '})));'

        }
    };

    var _ref = choice[mode] || choice.amd,
        prefix = _ref.prefix,
        suffix = _ref.suffix;
    //const content = readFileSync(filepath, 'utf8');
    //const result = parseComponent(content);


    var result = getBlocks(filepath);
    var templateCode = result.template.code;
    var styleCode = result.styles.map(function (style) {
        return (0, _style2.default)(style.code);
    }).join('\n');
    var scriptCode = result.script.code;

    var code = '\n        ' + prefix + '\n            /* append style */\n            ' + styleCode + '\n\n            /* get render function */\n            var _module1 = {\n                exports: {}\n            };\n            (function (module, exports) {\n                ' + (0, _template2.default)(templateCode) + '\n            })(_module1, _module1.exports);\n\n            /* get script output data */\n            var _module2 = {\n                exports: {}\n            };\n            (function (module, exports) {\n                ' + (0, _script2.default)(scriptCode) + '\n            })(_module2, _module2.exports);\n\n            var obj = _module2.exports.default || _module2.exports;\n            obj.render = _module1.exports.render;\n            obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n            module.exports = obj;\n        ' + suffix + '\n    ';

    return (0, _jsBeautify.js_beautify)(code);
}
1285210
private static ChunkOutput writeChunkOutput(
      Compiler compiler, Flags flags, List<JSModule> chunks) {
    ArrayList<File> outputFiles = new ArrayList<>();
    ChunkOutput output = new ChunkOutput();

    Map<String, String> parsedModuleWrappers =
        parseModuleWrappers(Arrays.asList(getStringArray(flags, "chunkWrapper")), chunks);

    for (JSModule c : chunks) {
      if (flags.createSourceMap != null && !flags.createSourceMap.equals(false)) {
        compiler.resetAndIntitializeSourceMap();
      }

      File file = new File();
      file.path = flags.chunkOutputPathPrefix + c.getName() + ".js";

      String code = compiler.toSource(c);

      int lastSeparatorIndex = file.path.lastIndexOf('/');
      if (lastSeparatorIndex < 0) {
        lastSeparatorIndex = file.path.lastIndexOf('\\');
      }
      String baseName = file.path.substring(Math.max(0, lastSeparatorIndex));
      String wrapper = parsedModuleWrappers.get(c.getName()).replace("%basename%", baseName);
      StringBuilder out = new StringBuilder();
      int pos = wrapper.indexOf("%s");
      if (pos != -1) {
        String prefix = "";

        if (pos > 0) {
          prefix = wrapper.substring(0, pos);
          out.append(prefix);
        }

        out.append(code);

        int suffixStart = pos + "%s".length();
        if (suffixStart != wrapper.length()) {
          // Something after placeholder?
          out.append(wrapper, suffixStart, wrapper.length());
        }
        // Make sure we always end output with a line feed.
        out.append('\n');

        // If we have a source map, adjust its offsets to match
        // the code WITHIN the wrapper.
        if (compiler != null && compiler.getSourceMap() != null) {
          compiler.getSourceMap().setWrapperPrefix(prefix);
        }

      } else {
        out.append(code);
        out.append('\n');
      }

      file.src = out.toString();

      if (flags.createSourceMap != null && !flags.createSourceMap.equals(false)) {
        StringBuilder b = new StringBuilder();
        try {
          compiler.getSourceMap().appendTo(b, file.path);
        } catch (IOException e) {
          // ignore
        }
        file.sourceMap = b.toString();
      }
      outputFiles.add(file);
    }

    output.compiledFiles = outputFiles.toArray(new File[0]);
    return output;
  }
503380
function createElementScript() {
  return gulp
    .src(`./${config.src.path}/${config.src.entrypoint}`)
    .pipe(
      modifyFile(content => {
        /**
         * Strip the imports and exports out of the parse code and return them.
         *
         * @param {Program} parsedCode
         *   The parsed code.
         * @returns {{imports:Map<number,Object>, exports:Map<number,Object>}}
         */
        const stripImportsAndExports = parsedCode => {
          // Get info about the code.
          const codeIndexesToRemove = [];
          const imports = new Map();
          const exports = new Map();
          for (const [nodeIndex, node] of parsedCode.body.entries()) {
            switch (node.type) {
              case 'ImportDeclaration':
                for (const specifiers of node.specifiers) {
                  let importedName;
                  if (specifiers.type === 'ImportDefaultSpecifier') {
                    importedName = specifiers.local.name;
                  } else if (specifiers.type === 'ImportSpecifier') {
                    importedName = specifiers.imported.name;
                  }

                  if (
                    importedName != null &&
                    importedName.toLowerCase().startsWith('catalyst')
                  ) {
                    imports.set(nodeIndex, node);
                    codeIndexesToRemove.push(nodeIndex);
                  } else {
                    throw new Error(
                      `Cannot automatically process import "${importedName}."`
                    );
                  }
                }
                break;

              case 'ExportDefaultDeclaration':
              case 'ExportNamedDeclaration':
                exports.set(nodeIndex, parsedCode.body[nodeIndex]);
                codeIndexesToRemove.push(nodeIndex);
                break;

              // Different type? Do nothing.
              default:
            }
          }

          // Remove imports and exports.
          parsedCode.body = parsedCode.body.filter(
            (e, i) => !codeIndexesToRemove.includes(i)
          );

          return {
            imports: imports,
            exports: exports
          };
        };

        /**
         * Replace catalyst element's imports with globally accessible object import.
         *
         * @param {Program} parsedCode
         *   The parsed code with the imports already stripped out.
         * @param {Map<number,Object>} imports
         *   The imports that have been stripped out of the parsed code.
         */
        const processImports = (parsedCode, imports) => {
          for (const [importDefIndex, importDef] of imports) {
            for (const specifier of Object.values(importDef.specifiers)) {
              const localName = specifier.local.name;
              const importedName = specifier.imported
                ? specifier.imported.name
                : localName;

              if (importedName.toLowerCase().startsWith('catalyst')) {
                parsedCode.body.splice(
                  importDefIndex,
                  0,
                  esprima.parseScript(
                    `let ${localName} = window.CatalystElements.${importedName};`
                  )
                );
              } else {
                throw new Error(
                  `Cannot automatically process import "${importedName}."`
                );
              }
            }
          }
        };

        /**
         * Replace exports with globally accessible object exports.
         *
         * @param {Program} parsedCode
         *   The parsed code with the exports already stripped out.
         * @param {Map<number,Object>} exports
         *   The exports that have been stripped out of the parsed code.
         */
        const processExports = (parsedCode, exports) => {
          const exportNamesUsed = [];

          // Replace exports with globally accessible object exports.
          for (const [exportDefIndex, exportDef] of exports) {
            if (exportDef.declaration === null) {
              for (const specifier of Object.values(exportDef.specifiers)) {
                const localName = specifier.local.name;
                const exportedName = specifier.imported
                  ? specifier.imported.name
                  : localName;

                if (!exportNamesUsed.includes(exportedName)) {
                  parsedCode.body.splice(
                    exportDefIndex,
                    0,
                    esprima.parseScript(
                      `window.CatalystElements.${exportedName} = ${localName};`
                    )
                  );
                  exportNamesUsed.push(exportedName);
                }
              }
            } else if (exportDef.declaration.type === 'Identifier') {
              if (!exportNamesUsed.includes(exportDef.declaration.name)) {
                parsedCode.body.splice(
                  exportDefIndex,
                  0,
                  esprima.parseScript(
                    `window.CatalystElements.${exportDef.declaration.name} = ${
                      exportDef.declaration.name
                    };`
                  )
                );
                exportNamesUsed.push(exportDef.declaration.name);
              }
            } else {
              console.error(
                `Cannot automatically process declaration in ${exportDef.type}.`
              );
            }
          }
        };

        // Parse the code.
        const parsedCode = esprima.parseModule(content);

        // Run functions defined above.
        const { imports, exports } = stripImportsAndExports(parsedCode);
        processImports(parsedCode, imports);
        processExports(parsedCode, exports);

        // Generate the updated code.
        return (
          'window.CatalystElements = window.CatalystElements || {};\n' +
          `${escodegen.generate(parsedCode)}`
        );
      })
    )
    .pipe(
      rename(path => {
        path.basename = config.element.tag;
        path.extname = `.script${path.extname}`;
      })
    )
    .pipe(gulp.dest(`./${config.temp.path}`));
}
107886
def make_code(self):
        """"""
        from copy import deepcopy

        #Get the size of the underlying matrix
        matrix_size = tables.version_size[self.version]

        #Create a template matrix we will build the codes with
        row = [' ' for x in range(matrix_size)]
        template = [deepcopy(row) for x in range(matrix_size)]

        #Add mandatory information to the template
        self.add_detection_pattern(template)
        self.add_position_pattern(template)
        self.add_version_pattern(template)

        #Create the various types of masks of the template
        self.masks = self.make_masks(template)

        self.best_mask = self.choose_best_mask()
        self.code = self.masks[self.best_mask]
358879
def create_cells(self, blocks):
        """"""
        cells = []
        for block in blocks:
            if (block['type'] == self.code) and (block['IO'] == 'input'):
                code_cell = self.create_code_cell(block)
                cells.append(code_cell)

            elif (block['type'] == self.code and
                  block['IO'] == 'output' and
                  cells[-1].cell_type == 'code'):
                cells[-1].outputs = self.create_outputs(block)

            elif block['type'] == self.markdown:
                markdown_cell = self.create_markdown_cell(block)
                cells.append(markdown_cell)

            else:
                raise NotImplementedError("{} is not supported as a cell"
                                          "type".format(block['type']))

        return cells
1191899
function (node) {
      let property;
      switch (node.type) {
        case 'ReturnStatement':
          property = 'argument';
          break;
        case 'ArrowFunctionExpression':
          property = 'body';
          break;
        default:
          return false;
      }

      const returnsJSX =
        node[property] &&
        node[property].type === 'JSXElement'
      ;
      const returnsReactCreateElement =
        node[property] &&
        node[property].callee &&
        node[property].callee.property &&
        node[property].callee.property.name === 'createElement'
      ;

      return Boolean(returnsJSX || returnsReactCreateElement);
    }