Generate the reST documentation files for the JavaScript code
974843
def generate_docs(app):
    
    # Figure out the correct directories to use
    config = app.config
    config_dir = app.env.srcdir
    javascript_root = os.path.join(config_dir, config.jsdoc_source_root)
    if javascript_root[-1] != os.path.sep:
        javascript_root += os.path.sep
    if not javascript_root:
        return
    output_root = os.path.join(config_dir, config.jsdoc_output_root)
    execution_dir = os.path.join(config_dir, '..')
    exclude = config.jsdoc_exclude

    # Remove any files generated by earlier builds
    cleanup(output_root)

    # Generate the actual reST files
    jsdoc_toolkit_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit')
    jsdoc_rst_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit-rst-template')
    build_xml_path = os.path.join(jsdoc_rst_dir, 'build.xml')
    command = ['ant', '-f', build_xml_path,
               '-Djsdoc-toolkit.dir=%s' % jsdoc_toolkit_dir,
               '-Djs.src.dir=%s' % javascript_root,
               '-Djs.rst.dir=%s' % output_root]
    if exclude:
        exclude_args = ['--exclude=\\"%s\\"' % path for path in exclude]
        command.append('-Djs.exclude="%s"' % ' '.join(exclude_args))
    try:
        process = Popen(command, cwd=execution_dir)
        process.wait()
    except OSError:
        raise JSDocError('Error running ant; is it installed?')

    # Convert the absolute paths in the file listing to relative ones
    path = os.path.join(output_root, 'files.rst')
    with open(path, 'r') as f:
        content = f.read()
    content = content.replace(javascript_root, '')
    with open(path, 'w') as f:
        f.write(content)
817559
function execute() {

    if (dryRun) {
        console.log(`In ${destDir}, this script would...`);
    } else {
        console.log(`Generating API documentation using TypeDoc...`);
    }

    const packages = path.resolve(rootDir, srcDir);

    glob(packages, {realpath:true}, function(error, srcFiles) {
       
        srcFiles.forEach((srcPath) => {    
            
            var valid = true;

            var packageName = srcPath
                .split(path.sep)
                .pop();

            excludedPackages.forEach((excludedPackageName) => {
                if (packageName === excludedPackageName) {
                    console.log(chalk.yellow(`...skip generating TypeDoc API files for ${packageName}`));
                    valid = false;
                }
            });

            if(valid) {
                dryRun ? console.log(`...generate TypeDoc API files for ${packageName}`) : createAPIFiles(packageName, srcPath);
            }

        });

    });
}
512962
function rawData() {
  return {
    DocumentationGeneration: {
      name: 'DocumentationGeneration',
      submodules: {},
      elements: {},
      classes: {
        'Some.Class.ClassItem': 1,
        'SomeOther.Class.Description': 1
      },
      fors: {},
      namespaces: {},
      tag: 'module',
      file: 'lib/parse-markdown.js',
      line: 4,
      description: '# An H1\nAnd a paragraph'
    },
    CreateDirs: {
      name: 'CreateDirs',
      submodules: {},
      elements: {},
      classes: {
        'Some.Class.ClassItem': 1,
        'SomeOther.Class.Description': 1
      },
      fors: {},
      namespaces: {},
      tag: 'module',
      file: 'lib/create-dirs.js',
      line: 7,
      description: '`some code`'
    }
  };
}
699136
function generate(spec) {
  createProjectDirectory();
  spec = addHttpEndpointNames(spec);
  spec = addSocketEndpointFlag(spec);
  spec = addSocketEmitTypeFlag(spec);
  spec = isProxyEndpointAvailable(spec);
  writeFileSync('server.mustache', spec, 'server.js');
  writeFileSync('package.mustache', spec, 'package.json');
}
250077
public function getJavascripts()
    {
        $self = $this;
        $parse_javascripts = function ($params, $javascripts) use ($self) {
            foreach ($params as $js) {
                if (is_string($js)) {
                    $js = array(
                        'path' => $js,
                    );
                } elseif (isset($js['route'])) {
                    $js = array(
                        'path' => $self->getGenerator()
                                        ->getRouter()
                                        ->generate($js['route'], $js['routeparams']),
                    );
                }

                $javascripts[] = $js;
            }

            return $javascripts;
        };

        // From config.yml
        $javascripts = $parse_javascripts(
            $this->getGenerator()->getFromBundleConfig('javascripts', array()), array()
        );

        // From generator.yml
        $javascripts = $parse_javascripts(
            $this->getVariable('javascripts', array()), $javascripts
        );

        return $javascripts;
    }
1011706
function generate(opt) {

  var jsonPath;

  if (!opt) {
    throw new Error('\'option\' is required.');
  }

  if (!opt.basePath) {
     throw new Error('\'basePath\' is required.');
  }

  descriptor.basePath = "/" + (opt.apiPrefix) ? opt.apiPrefix : '';
  descriptor.apiVersion = (opt.apiVersion) ? opt.apiVersion :
                                             '1.0';
  descriptor.swagger = (opt.swaggerVersion) ? opt.swaggerVersion :
                                              '1.0';

  if(opt.info) {
    descriptor.info = opt.info;
  }

  opt.apiVersion = descriptor.apiVersion;
  opt.swagger = descriptor.swaggerVersion;

  if (!opt.fullSwaggerJSONPath) {

    jsonPath = url.parse(opt.basePath + opt.swaggerJSON).path
    console.log(
      chalk.blue('Swagger info: '),
      chalk.gray('-----------------------------------------------')
    );
    console.log(
      chalk.blue('basePath + swaggerJSON: '),
      chalk.yellow(opt.basePath + opt.swaggerJSON)
    );
    console.log(
      chalk.blue('parsed path to json file: '),
      chalk.yellow(jsonPath)
    );
    if(jsonPath.lastIndexOf('//') !== -1) {
      console.log(
        chalk.red('veriry provided options, there is an unused `//` in the json path')
      );
    }
    console.log(
      chalk.blue('Swagger info: '),
      chalk.gray('-----------------------------------------------')
    );

    opt.fullSwaggerJSONPath = jsonPath;
  }

  if (opt.apis) {
    opt.apis.forEach(function (api) {
      readYml(api, function (err) {
        if (err) {
          throw err;
        }
      });
    });
  }
}
342206
function codegen(compiled, options) {
  const { code } = generate(t.file(t.program(compiled)), Object.assign({}, defaults, options));

  return code;
}
611894
def gen_code_api(self):
        """"""

        # edit config file

        conf_editor = Editor(self.conf_fpath)

        # insert code path for searching
        conf_editor.editline_with_regex(r'^# import os', 'import os')
        conf_editor.editline_with_regex(r'^# import sys', 'import sys')
        conf_editor.editline_with_regex(
            r'^# sys\.path\.insert',
            'sys.path.insert(0, "{}")'.format(self.code_fdpath))
        conf_editor.editline_with_regex(
            r"""html_theme = 'alabaster'""",
            'html_theme = \'default\''.format(self.code_fdpath))

        conf_editor.finish_writing()

        # sphinx-apidoc to generate rst from source code

        # force regenerate
        subprocess.call(self._sphinx_apidoc_cmd)

        pass
384022
function generateMetadataNoteDocument (options) {
  if (!options) {
    throw new Error('Missing required input: options')
  }
  if (!options.title) {
    throw new Error('Missing required input: options.title')
  }
  if (!options.offTitle) {
    throw new Error('Missing required input: options.offTitle')
  }
  if (!options.personalIdNumber) {
    throw new Error('Missing required input: options.personalIdNumber')
  }
  if (!options.schoolName) {
    throw new Error('Missing required input: options.schoolName')
  }
  if (!options.schoolOrgNumber) {
    throw new Error('Missing required input: options.schoolOrgNumber')
  }
  if (!options.file) {
    throw new Error('Missing required input: options.file')
  }
  if (!options.fileTitle) {
    throw new Error('Missing required input: options.fileTitle')
  }
  if (!options.caseNumber) {
    throw new Error('Missing required input: options.caseNumber')
  }

  var schoolGroup = getSchoolStudentAccessGroup(options)
  var meta = {
    'clientService': 'DocumentService',
    'clientMethod': 'CreateDocument',
    'args': {
      'parameter': {
        'AccessCode': '13', // Codetable: Accesscode
        'AccessGroup': schoolGroup, // Codetable: Tilgangsgruppe navn
        'Category': 'Internt notat / e-post MED oppfølging (N)', // Codetable: Document category
        'Contacts': [
          {
            'DocumentContactParameter': [
              {
                'Role': 'Avsender',
                'ReferenceNumber': options.schoolOrgNumber
              },
              {
                'ReferenceNumber': options.schoolOrgNumber, // Personnummer / orgnr
                'Role': 'Mottaker' // 5: Avsender 6: Mottaker Codetable: Activity - Contact Role
              }
            ]
          }
        ],
        'Files': [
          {
            'CreateFileParameter': {
              'Base64Data': options.file, // Must be base64 encoded
              'Category': 'Brev', // Codetable: File category
              'Format': 'PDF', // Codetable: File format
              'Status': 'F', // Codetable: FileStatus
              'Title': options.fileTitle,
              'VersionFormat': 'A' // Codetable: File status
            }
          }
        ],
        'Paragraph': 'Offl §13 jfr Fvl §13.1', // Codetable: Paragraph
        'ResponsibleEnterpriseNumber': options.schoolOrgNumber, // Recnr ansvarlig virksomhet
        'ResponsiblePersonRecno': config.minelev.main_responsiblePersonRecno,
        'Status': 'J', // Codetable: Document status
        'Title': options.offTitle,
        'UnofficialTitle': options.title,
        'Archive': 'Saksdokument', // Codetable: Document archive
        'CaseNumber': options.caseNumber,
        'SendersReference': ''
      }
    }
  }
  return meta
}
769987
function writeGeneratedFileList(htmlFiles) {
  const fileList = htmlFiles.map(filename => {
    return {
      title: filename,
      path: `${devsitePath}${filename}`
    };
  });
  const generatedTocYAML = yaml.safeDump({ toc: fileList });
  return fs
    .writeFile(`${docPath}/_toc_autogenerated.yaml`, generatedTocYAML)
    .then(() => htmlFiles);
}
471555
function generateLayers () {
			grunt.log.write("Generating layers...");

			var config = lang.extend({}, requireConfig, {
				isPrepareStage: true,
				optimize: "none",
				optimizeCss: "none",
				appDir: buildDir,
				dir: tempDir,
				baseUrl: "./",
				logLevel: 2, // WARN
				removeCombined: false,
				skipDirOptimize: true,
				keepBuildDir: false,
				skipSemiColonInsertion: true,
				pragmas: {
					prepare: true,
					build: true
				},
				// Pragmas for rjs plugins:
				pragmasOnSave: {
					prepareSave: true
				},
				// main (root) modules:
				modules: modules.map(function (module) { return { name: module }; }),
				onBuildWrite: function (moduleName, modulePath, contents) {
					// put moduleName into some layer basing on its path
					layers.some(function (layer) {
						var relPath = path.relative(path.resolve(config.dir), modulePath);
						var layerDir = layer.dir;
						if (!Array.isArray(layerDir)) {
							layerDir = [layerDir];
						}
						layerDir.forEach(function(dir) {
							if (relPath.indexOf(dir) === 0) {
								if (options.ignoreModules) {
									if (options.ignoreModules.some(function (m) {
										return m === moduleName;
									})) {
										return;
									}
								}
								layer.modules[moduleName] = true;
							}
						});
					});
					if (moduleName.indexOf('xhtmpl!') === 0) {
						modulesToDelete.push(path.join(outputDir, modulePath.slice('xhtmpl!'.length)));

						// Manually save pre-compiled template back into buildDir as
						// we're currently saving into tempDir (that's why we can't rely on returning content)

						// NOTE: manually remove leading semicolon
						// TODO: the code should be removed after migrating on 2.1.9 (with skipSemiColonInsertion support)
						if (contents.charAt(contents.length-1) === ";") {
							contents = contents.slice(0, contents.length-1);
						}
						file.saveFile(path.join(buildDir, modulePath.slice('xhtmpl!'.length)), contents);
					}
					//return contents;
					return "// this is a stub for finding layer's dependencies: moduleName=" + moduleName;
				}
			});

			requirejs.optimize(
				config,
				lang.safeCallback(function () {
					// create layer modules using 'layers' structure created in onBuildWrite:
					// every 'layer module' is an empty RJS module with imports (via define([..])) of all modules inside this layer
					layers.forEach(function (layer) {
						var modules = Object.keys(layer.modules).sort(),
							content = "define([\n\t\"" + modules.join("\",\n\t\"") + "\"\n], function () {});";
						file.saveFile(path.join(buildDir, layer.name) + ".js", content);
					});

					grunt.log.writeln('OK'.green);

					// Go to next step
					optimizeModules();
				}),
				lang.errorCallback
			);
		}
757797
function spawnJSDoc(paths) {
  return new Promise((resolve, reject) => {
    let output = '';
    let errors = '';
    const cwd = path.join(__dirname, '..');
    const child = spawn(jsdoc, ['-c', jsdocConfig].concat(paths), {cwd: cwd});

    child.stdout.on('data', data => {
      output += String(data);
    });

    child.stderr.on('data', data => {
      errors += String(data);
    });

    child.on('exit', code => {
      if (code) {
        reject(new Error(errors || 'JSDoc failed with no output'));
        return;
      }

      let info;
      try {
        info = parseOutput(output);
      } catch (err) {
        reject(err);
        return;
      }
      resolve(info);
    });
  });
}
165740
function buildDocs() {
  return Promise.resolve()
    .then(() => new Promise((resolve, reject) => {
      Metalsmith(__dirname)
        .source('./source/docs')
        .destination('./docs')
        .clean(true)
        .use(Markdown())
        .metadata({
          version: __version
        })
        .use(Layouts({
          engine: 'handlebars',
          directory: './source/layouts',
          rename: false
        }))
        // Update {{version}} in content since it's not processed with Handlebars
        .use((files, metalsmith, done) => {
          Object.keys(files).forEach((key) => {
            let file = files[key];

            file.contents = new Buffer(
              file.contents
                .toString()
                .replace(/\{\{version\}\}/g, __version)
            );
          });

          done();
        })
        .build((err) => {
          if(err) {
            reject(err);
            return;
          }
          console.log(Chalk.green('Docs generated! 📚'));

          resolve();
        });
    }));
}
200884
function includeJsFiles() {
        if (cog.getOption('include_only_external')) {
            return extLibFiles().concat(generatedJsFiles());
        }
        if (cog.getOption('compile_typescript')) {
            return extLibFiles().concat(generatedJsFiles());
        }
        return extLibFiles().concat(srcFiles()).concat(generatedJsFiles());
    }
490133
function generatePrismicDocuments(config) {
  return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
    .then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
    .then(res => {
      util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
      if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
      const documents = prismic.reduce(res.results, false, config);

      // Populate config metadata with retrieved documents.
      if (!config.metadata) config.metadata = { $data: {} };
      _.merge(config.metadata.$data, documents);

      for (let docType in documents) {
        const c = _.get(config, `collections.${docType}`);

        if (c && c.permalink) {
          const subdir = `.prismic/${docType}`;
          const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
          c.pattern = path.join(subdir, `**/*`);

          documents[docType].forEach(doc => {
            const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
            const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
            fs.mkdirsSync(dir);
            fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
          });
        }
      }

      return;
    });
}
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}
54701
function generateResourceListing(options) {
  var controllers = options.controllers;
  var opts = options.options || {};

  var listing = {
    openapi: '3.0.0',
    info: buildInfo(opts),
    servers: opts.servers || buildDefaultServers(),
    tags: buildTags(opts, controllers),
    paths: buildPaths(opts, controllers),
    components: buildComponents(opts, controllers)
  };

  mergeIn(listing.paths, opts.paths);

  if (opts.security) {
    listing.security = opts.security;
  }
  if (opts.externalDocs) {
    listing.externalDocs = opts.externalDocs;
  }

  return listing;
}