generate method spec with parent module/class
490488
function GENERATE_METHOD(name, spec, parent) {
  name = name.replace(/!+$/, '');
  return GENERATE_DOC(spec.description + '\n'
    + '@method ' + name + '\n'
    + (parent ? ('@for ' + parent + '\n') : '@for common\n')
    + _.reduce(spec.params, function(memo, paramSpec, paramName) {
        return memo + '@param {' + GENERATE_TYPE(paramSpec.type) + '} ' + paramName + ' ' + paramSpec.description + '\n'; 
      }, '')
    + ( !_.isEmpty(spec.return) ? ('@return {' + GENERATE_TYPE(spec.return.type) + '} ' + spec.return.description + '\n') : ''));
}
654144
def append_to_existing_spec(class_or_module, dry_run, rails_mode, spec_path)
      existing_spec = File.read(spec_path)
      lacking_methods = class_or_module.method_list.
        select { |m| m.visibility == :public }.
        reject { |m| existing_spec.match(m.name) }

      if lacking_methods.empty?
        puts "#{spec_path} skipped."
      else
        # These names are used in ERB template, don't delete.
        # rubocop:disable Lint/UselessAssignment
        methods_to_generate = lacking_methods
        c = class_or_module
        # rubocop:enable Lint/UselessAssignment

        erb = RSpecKickstarter::ERBFactory.new(@delta_template).get_instance_for_appending(rails_mode, spec_path)
        additional_spec = erb.result(binding)

        last_end_not_found = true
        code = existing_spec.split("\n").reverse.reject { |line|
          before_modified = last_end_not_found
          last_end_not_found = line.gsub(/#.+$/, '').strip != 'end' if before_modified
          before_modified
        }.reverse.join("\n") + "\n" + additional_spec + "\nend\n"

        if dry_run
          puts "----- #{spec_path} -----"
          puts code
        else
          File.open(spec_path, 'w') { |f| f.write(code) }
        end
        puts "#{spec_path} modified."
      end
    end
34200
def method_wrapper(m):
    """"""

    if m.is_simple:
        def simple_method(self):
            """TODO: no docstring!"""
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, unwrap(self)))

        return simple_method

    elif m.input_transform is not None:
        def transform_method(self, *args, **kwargs):
            """TODO: no docstring!"""
            request = m.input_transform(self, *args, **kwargs)
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, request))

        return transform_method

    elif m.static:
        def static_method(cls, *args, **kwargs):
            """TODO: no docstring!"""
            request = make_static_request(m, *args, **kwargs)
            return apply_transform(
                cls.__stub__(__server__), m.output_transform,
                grpc_call(cls.__stub__(__server__), m, request))

        return static_method

    else:
        def request_method(self, *args, **kwargs):
            """TODO: no docstring!"""
            request = make_request(self, m, *args, **kwargs)
            return apply_transform(
                self.__service__, m.output_transform,
                grpc_call(self.__service__, m, request))

        return request_method
248259
def statusable_methods
      # Include generated methods with a module, not right in class.
      @statusable_methods ||= Module.new.tap do |m|
        m.const_set :ClassMethods, Module.new
        include m
        extend m::ClassMethods
      end
    end
31402
def _validate_method_decoration(meta, class_):
        
        # TODO(xion): employ some code inspection tricks to serve ClassErrors
        # as if they were thrown at the offending class's/method's definition

        super_mro = class_.__mro__[1:]
        own_methods = ((name, member)
                       for name, member in class_.__dict__.items()
                       if is_method(member))

        # check that ``@override`` modifier is present where it should be
        # and absent where it shouldn't (e.g. ``@final`` methods)
        for name, method in own_methods:
            shadowed_method, base_class = next(
                ((getattr(base, name), base)
                 for base in super_mro if hasattr(base, name)),
                (None, None)
            )
            if meta._is_override(method):
                # ``@override`` is legal only when the method actually shadows
                # a method from a superclass, and that metod is not ``@final``
                if not shadowed_method:
                    raise ClassError("unnecessary @override on %s.%s" % (
                        class_.__name__, name), class_=class_)
                if meta._is_final(shadowed_method):
                    raise ClassError(
                        "illegal @override on a @final method %s.%s" % (
                            base_class.__name__, name), class_=class_)

                # if @override had parameter supplied, verify if it was
                # the same class as the base of shadowed method
                override_base = meta._get_override_base(method)
                if override_base and base_class is not override_base:
                    if is_class(override_base):
                        raise ClassError(
                            "incorrect override base: expected %s, got %s" % (
                                base_class.__name__, override_base.__name__))
                    else:
                        raise ClassError(
                            "invalid override base specified: %s" % (
                                override_base,))

                setattr(class_, name, method.method)
            else:
                if shadowed_method and name not in meta.OVERRIDE_EXEMPTIONS:
                    if meta._is_final(shadowed_method):
                        msg = "%s.%s is hiding a @final method %s.%s" % (
                            class_.__name__, name, base_class.__name__, name)
                    else:
                        msg = ("overridden method %s.%s "
                               "must be marked with @override" % (
                                class_.__name__, name))
                    raise ClassError(msg, class_=class_)
1097712
function transpileDerivedExchangeClass (contents) {

    let exchangeClassDeclarationMatches = contents.match (/^module\.exports\s*=\s*class\s+([\S]+)\s+extends\s+([\S]+)\s+{([\s\S]+?)^};*/m)

    // log.green (file, exchangeClassDeclarationMatches[3])

    let className = exchangeClassDeclarationMatches[1]
    let baseClass = exchangeClassDeclarationMatches[2]

    let methods = exchangeClassDeclarationMatches[3].trim ().split (/\n\s*\n/)

    let python2 = []
    let python3 = []
    let php = []

    let methodNames = []

    // run through all methods
    for (let i = 0; i < methods.length; i++) {
        // parse the method signature
        let part = methods[i].trim ()
        let lines = part.split ("\n")
        let signature = lines[0].trim ()
        let methodSignatureRegex = /(async |)([\S]+)\s\(([^)]*)\)\s*{/ // signature line
        let matches = methodSignatureRegex.exec (signature)

        if (!matches) {
            log.red (methods[i])
            log.yellow.bright ("\nMake sure your methods don't have empty lines!\n")
        }

        // async or not
        let keyword = matches[1]
        // try {
        //     keyword = matches[1]
        // } catch (e) {
        //     log.red (e)
        //     log.green (methods[i])
        //     log.yellow (exchangeClassDeclarationMatches[3].trim ().split (/\n\s*\n/))
        //     process.exit ()
        // }

        // method name
        let method = matches[2]

        methodNames.push (method)

        method = unCamelCase (method)

        // method arguments
        let args = matches[3].trim ()

        // extract argument names and local variables
        args = args.length ? args.split (',').map (x => x.trim ()) : []

        // get names of all method arguments for later substitutions
        let variables = args.map (arg => arg.split ('=').map (x => x.trim ()) [0])

        // add $ to each argument name in PHP method signature
        let phpArgs = args.join (', $').trim ().replace (/undefined/g, 'null').replace ('{}', 'array ()')
        phpArgs = phpArgs.length ? ('$' + phpArgs) : ''

        // remove excessive spacing from argument defaults in Python method signature
        let pythonArgs = args.map (x => x.replace (' = ', '='))
                                .join (', ')
                                .replace (/undefined/g, 'None')
                                .replace (/false/g, 'False')
                                .replace (/true/g, 'True')

        // method body without the signature (first line)
        // and without the closing bracket (last line)
        let js = lines.slice (1, -1).join ("\n")

        // transpile everything
        let { python3Body, python2Body, phpBody } = transpileJavaScriptToPythonAndPHP ({ js, className, variables, removeEmptyLines: true })

        // compile the final Python code for the method signature
        let pythonString = 'def ' + method + '(self' + (pythonArgs.length ? ', ' + pythonArgs : '') + '):'

        // compile signature + body for Python 2
        python2.push ('');
        python2.push ('    ' + pythonString);
        python2.push (python2Body);

        // compile signature + body for Python 3
        python3.push ('');
        python3.push ('    ' + keyword + pythonString);
        python3.push (python3Body);

        // compile signature + body for PHP
        php.push ('');
        php.push ('    public function ' + method + ' (' + phpArgs + ') {');
        php.push (phpBody);
        php.push ('    }')

    }

    return {

        // altogether in PHP, Python 2 and 3
        python2: createPythonClass (className, baseClass, python2, methodNames),
        python3: createPythonClass (className, baseClass, python3, methodNames, true),
        php:     createPHPClass    (className, baseClass, php,     methodNames),

        className,
        baseClass,
    }
}
1218310
function createStandardConfig(moduleFormat, productive) {
  return {
    input: 'src/main/js-spec.ts',

    output: {
      file: productive
        ? `dist/js-spec.${moduleFormat}.production.js`
        : `dist/js-spec.${moduleFormat}.development.js`,

      format: moduleFormat,
      name: 'jsSpec', 
      sourcemap: productive ? false : 'inline',

      globals: {
        'js-spec': 'jsSpec',
      }
    },

    external: [],

    plugins: [
      resolve({
        jsnext: true,
        main: true,
        browser: true,
      }),
      // tslint({
      //}),
      replace({
        exclude: 'node_modules/**',

        values: {
          'process.env.NODE_ENV': productive ? "'production'" : "'development'"
        }
      }),
      typescript({
        exclude: 'node_modules/**',
      }),
      productive && (moduleFormat === 'esm' ? terser() : uglifyJS()),
      productive && gzip()
    ],
  }
}
843142
void generateMBeanCode(Definition def)
   {
      if (def.isSupportOutbound())
      {
         generateClassCode(def, "MbeanInterface", "mbean");
         generateClassCode(def, "MbeanImpl", "mbean");
         generatePackageInfo(def, "main", "mbean");
      }
   }
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
516714
def handle_method(signature_node, module, object_name, cache):
    
    *class_names, attr_name = object_name.split(".")  # Handle nested classes
    class_ = module
    for class_name in class_names:
        class_ = getattr(class_, class_name, None)
        if class_ is None:
            return
    attr = getattr(class_, attr_name)
    try:
        inspected_attr = cache[class_][attr_name]
        defining_class = inspected_attr.defining_class
    except KeyError:
        # TODO: This is a hack to handle bad interaction between enum and inspect
        defining_class = class_
    if defining_class is not class_:
        reftarget = "{}.{}".format(defining_class.__module__, defining_class.__name__)
        xref_node = addnodes.pending_xref(
            "", refdomain="py", refexplicit=True, reftype="class", reftarget=reftarget
        )
        name_node = nodes.literal(
            "", "{}".format(defining_class.__name__), classes=["descclassname"]
        )
        xref_node.append(name_node)
        desc_annotation = list(signature_node.traverse(addnodes.desc_annotation))
        index = len(desc_annotation)
        class_annotation = addnodes.desc_addname()
        class_annotation.extend([nodes.Text("("), xref_node, nodes.Text(").")])
        class_annotation["xml:space"] = "preserve"
        signature_node.insert(index, class_annotation)
    else:
        is_overridden = False
        for class_ in defining_class.__mro__[1:]:
            if hasattr(class_, attr_name):
                is_overridden = True
        if is_overridden:
            emphasis = nodes.emphasis(
                "overridden ", "overridden ", classes=["property"]
            )
            signature_node.insert(0, emphasis)
    if getattr(attr, "__isabstractmethod__", False):
        emphasis = nodes.emphasis("abstract", "abstract", classes=["property"])
        signature_node.insert(0, emphasis)
1100630
private Map<String, String> collectModuleSpecificProps(DefaultInputModule module) {
    Map<String, String> moduleSpecificProps = new HashMap<>();
    AbstractProjectOrModule parent = hierarchy.parent(module);
    if (parent == null) {
      moduleSpecificProps.putAll(module.properties());
    } else {
      Map<String, String> parentProps = parent.properties();
      for (Map.Entry<String, String> entry : module.properties().entrySet()) {
        if (!parentProps.containsKey(entry.getKey()) || !parentProps.get(entry.getKey()).equals(entry.getValue())) {
          moduleSpecificProps.put(entry.getKey(), entry.getValue());
        }
      }
    }
    return moduleSpecificProps;
  }
569108
def class2md(self, cls, depth=2):
        

        section = "#" * depth
        subsection = "#" * (depth + 2)
        clsname = cls.__name__
        modname = cls.__module__
        header = clsname
        path = self.get_src_path(cls)
        doc = self.doc2md(cls)

        try:
            init = self.func2md(cls.__init__, clsname=clsname)
        except (ValueError, TypeError):
            # this happens if __init__ is outside the repo
            init = ""

        variables = []
        for name, obj in getmembers(cls, lambda a: not (inspect.isroutine(a) or inspect.ismethod(a))):
            if not name.startswith("_") and type(obj) == property:
                comments = self.doc2md(obj) or inspect.getcomments(obj)
                comments = "\n %s" % comments if comments else ""
                variables.append("\n%s %s.%s%s\n" % (subsection, clsname, name, comments))

        handlers = []
        for name, obj in getmembers(cls, inspect.ismethoddescriptor):
            if not name.startswith("_") and hasattr(obj, "__module__") and obj.__module__ == modname:
                handlers.append("\n%s %s.%s\n *Handler*" % (subsection, clsname, name))

        methods = []
        for name, obj in getmembers(cls, inspect.ismethod):
            if not name.startswith("_") and hasattr(obj,
                                                    "__module__") and obj.__module__ == modname and name not in handlers:
                methods.append(self.func2md(obj, clsname=clsname, depth=depth + 1))

        string = CLASS_TEMPLATE.format(section=section,
                                       header=header,
                                       path=path,
                                       doc=doc if doc else "",
                                       init=init,
                                       variables="".join(variables),
                                       handlers="".join(handlers),
                                       methods="".join(methods))
        return string
551983
def autodoc_module(module):
    
    doc = getattr(module, '__doc__')
    if doc is None:
        doc = ''
    members = []
    for name, member in inspect.getmembers(module):
        if ((not name.startswith('_')) and
                (inspect.getmodule(member) is module)):
            members.append((name, member))
    members = sorted(members, key=_number_of_line)
    if members:
        lines = ['\n\nModule :mod:`~%s` implements the following members:\n'
                 % module.__name__]
        for (name, member) in members:
            if inspect.isfunction(member):
                type_ = 'func'
            elif inspect.isclass(member):
                type_ = 'class'
            else:
                type_ = 'obj'
            lines.append('      * :%s:`~%s` %s'
                         % (type_, name, objecttools.description(member)))
        doc = doc + '\n\n' + '\n'.join(lines) + '\n\n' + 80*'_'
        module.__doc__ = doc
61354
protected static function _generateMethod($method, $callParent = false)
    {
        $result = join(' ', Reflection::getModifierNames($method->getModifiers()));
        $result = preg_replace('/abstract\s*/', '', $result);
        $name = $method->getName();
        $parameters = static::_generateSignature($method);
        $type = static::_generateReturnType($method);
        $body = "{$result} function {$name}({$parameters}) {$type}{";
        if ($callParent) {
            $parameters = static::_generateParameters($method);
            $return = 'return ';
            if ($method->isConstructor() || $method->isDestructor()) {
                $return = '';
            }
            $body .= "{$return}parent::{$name}({$parameters});";
        }
        return $body . "}";
    }
107487
def _module_parents(module_name):
        '''
        
        '''
        spl = module_name.split('.')
        for i in range(len(spl), 0, -1):
            yield '.'.join(spl[0:i])
        if module_name:
            yield ''
637545
def obj_classes_from_module(module):
    """"""
    for name in dir(module):
        if not name.startswith('_'):
            cls = getattr(module, name)
            if getattr(cls, 'classID', None):
                yield (name, cls)
1202730
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {

		ModifyType updateResultType = detectModifyType(method, method.jql.operationType);

		// if true, field must be associate to ben attributes
		TypeName returnType = method.getReturnClass();

		if (updateResultType == null) {
			throw (new InvalidMethodSignException(method));
		}

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);
		ParameterSpec parameterSpec;
		for (Pair<String, TypeName> item : method.getParameters()) {
			parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
			methodBuilder.addParameter(parameterSpec);
		}
		methodBuilder.returns(returnType);

		// generate inner code
		updateResultType.generate(classBuilder, methodBuilder, method, returnType);

		MethodSpec methodSpec = methodBuilder.build();
		classBuilder.addMethod(methodSpec);

		if (method.contentProviderEntryPathEnabled) {
			// delete-select, update-select can be used with content provider
			// insert-select no

			// if (method.jql.containsSelectOperation && updateResultType==) {
			// AssertKripton.failWithInvalidMethodSignException(true, method, "
			// SQL with inner SELECT can not be used in content provider");
			// }

			generateModifierForContentProvider(BaseProcessor.elementUtils, classBuilder, method, updateResultType);

		}

	}