Use the File SWAG Backend
174361
def file(ctx, data_dir, data_file):
    """"""
    if not ctx.file:
        ctx.data_file = data_file

    if not ctx.data_dir:
        ctx.data_dir = data_dir

    ctx.type = 'file'
813561
function readApi(file, fn) {
  var ext = path.extname(file);
  if ('.js' === ext || '.ts' === ext) {
    readJsDoc(file, fn);
  } else if ('.yml' === ext) {
    readYml(file, fn);
  } else if ('.coffee' === ext) {
    readCoffee(file, fn);
  } else {
    throw new Error('Unsupported extension \'' + ext + '\'');
  }
}
482
function useMain (mdFile, swagger) {
  const mainOpts = {
    position: argv.position,
    title: argv.title
  }
  opts.yaml ? mainOpts.yaml = true : mainOpts.json = true

  fs.readFile(mdFile, { encoding: 'utf8' }, function (err, md) {
    assert.ifError(err)
    const compiled = remark()
      .use(main(swagger, mainOpts))
      .process(md)

    const rs = fromString(compiled)
    const ws = argv.w ? fs.createWriteStream(mdFile) : stdout
    pump(rs, ws, handleErr)
  })
}
189762
function(callback) {

			var fileLoop = function(currentDir,templateDirectories,cb) {
				var callback_has_been_called = false
				fs.readdir(currentDir,function(err,files) {
					if (err) {
						return console.log('Unable to find files in path',currentDir)
					}
					var num = files.length

					var finishFile = function(i) {
						if (!(--num)) {
							if (!callback_has_been_called) {
								callback_has_been_called = true
								return cb()
							}
						} else {
							buildFileData(i+1)
						}
					}

					var buildFileData = function(i) {
						var file = files[i]
						var filepath = currentDir + '/' + file

						fs.stat(filepath,function(err2,stats) {
							if (err2) {
								return console.log('Unable to find file',filepath)
							}

							if (stats && stats.isDirectory()) {
								var pugatizerPath = '    puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = {}\r\n'
								pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
								fs.appendFileSync(outputFile,pugatizerPath)
								fileLoop(filepath,templateDirectories,function() {
									finishFile(i)
								})
							} else if (stats && stats.isFile()) {
								var ext = path.extname(filepath)
								if (ext == '.pug') {
									var pugatizerPath = '    puglatizer' + currentDir.replace(templateDirectories,'').replace(/\//g,'"]["') + '"]["' + file.replace('.pug','') + '"] = '
									pugatizerPath = pugatizerPath.replace('puglatizer"]','puglatizer')
									buildTemplateFromFile(filepath,options,function(err,template) {
										pugatizerPath += minify.js(template.toString()) + ';\r\n\r\n'
										fs.appendFileSync(outputFile,pugatizerPath)
										finishFile(i)
									})
								} else {
									finishFile(i)
								}
							} else {
								finishFile(i)
							}
						})
					}

					if (!num) {
						return console.log('Unable to find files in path',currentDir)
					} else {
						buildFileData(0)
					}

				})

			}
			
			fileLoop(templateDirectories,templateDirectories,function() {
				return callback()
			})
		}
693485
def pin_to_ipfs(
    manifest: Manifest, *, backend: BaseIPFSBackend, prettify: Optional[bool] = False
) -> List[Dict[str, str]]:
    
    contents = format_manifest(manifest, prettify=prettify)

    with tempfile.NamedTemporaryFile() as temp:
        temp.write(to_bytes(text=contents))
        temp.seek(0)
        return backend.pin_assets(Path(temp.name))
1053132
function statFile(filePath, callback) {
  fs.stat(filePath, function(err, stats) {

    // Resource does not exist
    if (err && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
      const error = new Error('Resource does not exist');
      error.httpCode = 404;

      callback(error);

    // Not a file
    } else if (!stats.isFile()) {
      const error = new Error('Resource is not a file');
      error.httpCode = 400;

      callback(error);

    // Server error
    } else if (err) {
      const error = new Error('Server error');
      error.httpCode = 500;

      callback(error);

    // Success. Get the stats.
    } else {
      callback(null, stats);
    }
  });
}
386524
def add_swagger(app, json_route, html_route, **kwargs):
    
    spec = getattr(app, SWAGGER_ATTR_NAME)
    if spec:
        spec = spec.swagger_definition(**kwargs)
    else:
        spec = {}
    encoded_spec = json.dumps(spec).encode("UTF-8")

    @app.route(json_route)
    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={"Access-Control-Allow-Origin": "*"},
            content_type="application/json",
        )

    # add the statics
    static_root = get_swagger_static_root()
    swagger_body = generate_swagger_html(
        STATIC_PATH, json_route
    ).encode("utf-8")

    @app.route(html_route)
    def swagger_ui():
        return Response(swagger_body, content_type="text/html")

    # the blueprint work is the easiest way to integrate a static
    # directory into flask.
    blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,
                          static_folder=static_root)
    app.register_blueprint(blueprint)
1306604
function(handlebars, directory, filepath, opts, done) {
		var regex = (typeof opts.match === 'string') ? new RegExp(opts.match) : opts.match || /\.(html|hbs)$/,
			isValidTemplate = regex.test(filepath);

		if (!isValidTemplate) {
			return done(null);
		}

		fs.readFile(filepath, 'utf8', function(err, data) {
			if (!err) {
				var ext = path.extname(filepath);
				var templateName = path.relative(directory, filepath)
				.slice(0, -(ext.length)).replace(/[ -]/g, '_').replace(/\\/g, '/');
				if (typeof opts.name === 'function') templateName = opts.name(templateName);
				handlebars.registerPartial(templateName, data);
				return done(undefined, templateName);
			}

			done(err);
		});
	}
173429
function File(file, options) {
  Item.call(this, file, options);
  this.initFile(file);
  return file;
}
1132223
def template(client, src, dest, paths, opt):
    """"""
    key_map = cli_hash(opt.key_map)
    obj = {}
    for path in paths:
        response = client.read(path)
        if not response:
            raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
        if is_aws(response['data']) and 'sts' not in path:
            renew_secret(client, response, opt)

        for s_k, s_v in response['data'].items():
            o_key = s_k
            if s_k in key_map:
                o_key = key_map[s_k]

            k_name = secret_key_name(path, o_key, opt) \
                .lower() \
                .replace('-', '_')
            obj[k_name] = s_v

    template_obj = blend_vars(obj, opt)
    output = render(grok_template_file(src),
                    template_obj)
    write_raw_file(output, abspath(dest))
220668
function globFile (file) {
    return stat(file).then(({ err, stats }) => {
      if (err) throw err
      if (stats.isDirectory()) {
        // TODO what if file is already slash-terminated?
        switch (file) {
          case './':
            return globPromise('./*.js')
          case 'bin':
            return globPromise('bin/*')
          default:
            return globPromise(`${file}/**/*.js`)
        }
      } else {
        return Promise.resolve(file)
      }
    })
  }
471178
async function collecticonsBundle (params) {
  const {
    dirPath,
    destFile
  } = params;

  await validateDirPath(dirPath);

  const resultFiles = await collecticonsCompile({
    dirPath,
    styleFormats: ['css'],
    styleDest: './styles',
    fontDest: './',
    fontTypes: ['woff', 'woff2'],
    previewDest: './',
    noFileOutput: true
  });

  if (resultFiles === null) return;

  // Create zip.
  let zip = new JSZip();

  // Add generated files.
  resultFiles.forEach(file => {
    zip.file(file.path, file.contents);
  });

  // Add the icons.
  const dir = await fs.readdir(dirPath);
  const svgs = await Promise.all(dir.map(async file => {
    return file.endsWith('.svg')
      ? (
        {
          path: `icons/${file}`,
          contents: await fs.readFile(path.resolve(dirPath, file))
        }
      )
      : null;
  }));

  svgs.forEach(file => {
    zip.file(file.path, file.contents);
  });

  await fs.ensureDir(path.dirname(destFile));
  await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary');
}
494645
def parse_swag_config_options(config):
    """"""
    options = {}
    for key, val in config.items():
        if key.startswith('swag.backend.'):
            options[key[12:]] = val
        if key.startswith('swag.'):
            options[key[5:]] = val

    if options.get('type') == 's3':
        return S3OptionsSchema(strict=True).load(options).data
    elif options.get('type') == 'dynamodb':
        return DynamoDBOptionsSchema(strict=True).load(options).data
    else:
        return FileOptionsSchema(strict=True).load(options).data
807991
def _get_backend(args):
    """"""
    if args.backend == 'gatttool':
        backend = GatttoolBackend
    elif args.backend == 'bluepy':
        backend = BluepyBackend
    elif args.backend == 'pygatt':
        backend = PygattBackend
    else:
        raise Exception('unknown backend: {}'.format(args.backend))
    return backend
979791
def backend_from_fname(name):
    """"""
    ext = splitext(name)[1]

    try:
        mime = EXTS_TO_MIMETYPES[ext]

    except KeyError:
        try:
            f = open(name, 'rb')

        except IOError as e:
            # The file may not exist, we are being asked to determine it's type
            # from it's name. Other errors are unexpected.
            if e.errno != errno.ENOENT:
                raise

            # We will have to fall back upon the default backend.
            msg = "No handler for %r, defaulting to %r" % (ext, DEFAULT_MIME)
            if 'FULLTEXT_TESTING' in os.environ:
                warn(msg)
            else:
                LOGGER.debug(msg)

            mod_name = MIMETYPE_TO_BACKENDS[DEFAULT_MIME]

        else:
            with f:
                return backend_from_fobj(f)

    else:
        mod_name = MIMETYPE_TO_BACKENDS[mime]

    mod = import_mod(mod_name)
    return mod
840993
function(site, uuid, env, newBackup) {

    app.status('Pulling files.');

    if (firstTime()) {
      return pullFilesArchive(site, env, newBackup)
      .then(function() {
        return pullFilesRsync(uuid, env);
      });
    }
    else {
      return pullFilesRsync(uuid, env);
    }
  }
360725
async function embellish({ content, filename, packageData, basePath } /*: EmbelishOptions */) /*: Promise<string> */ {
  if (filename) {
    const packageFile = path.resolve(path.dirname(filename), 'package.json');

    return embellish({
      content: await readFileContent(filename),
      basePath: path.dirname(packageFile),
      packageData: await Package.readFromFile(packageFile)
    });
  }

  if (!content || !basePath) {
    throw new Error('Unable to embelish content unless content is provided');
  }

  const ast = parse(content);
  await insertLicense(ast, packageData, basePath);
  await insertBadges(ast, packageData, basePath);
  return Promise.resolve(toMarkdown(ast));
}