copy-pasted from swagger-js
971970
function (value, modelsToIgnore) {
    modelsToIgnore = modelsToIgnore || {};

    modelsToIgnore[value.name] = value;

    // Response support
    if (value.examples && _.isPlainObject(value.examples) && value.examples['application/json']) {
      value.definition.example = value.examples['application/json'];

      if (_.isString(value.definition.example)) {
        value.definition.example = jsyaml.safeLoad(value.definition.example);
      }
    } else if (!value.definition.example) {
      value.definition.example = value.examples;
    }

    return schemaToJSON(value.definition, value.models, modelsToIgnore, value.modelPropertyMacro);
  }
8868
@GetMapping(value = "/swagger.yml", produces = "text/yaml")
  public String swagger(Model model, HttpServletResponse response) {
    response.setContentType("text/yaml");
    response.setCharacterEncoding("UTF-8");
    final UriComponents uriComponents =
        ServletUriComponentsBuilder.fromCurrentContextPath().build();
    model.addAttribute("scheme", uriComponents.getScheme());
    String host = uriComponents.getHost();
    if (uriComponents.getPort() >= 0) {
      host += ":" + uriComponents.getPort();
    }
    model.addAttribute("host", host);
    model.addAttribute(
        "entityTypes",
        metaDataService
            .getEntityTypes()
            .filter(e -> !e.isAbstract())
            .map(EntityType::getId)
            .sorted()
            .collect(toList()));
    model.addAttribute("attributeTypes", AttributeType.getOptionsLowercase());
    model.addAttribute("languageCodes", getLanguageCodes().collect(toList()));
    return "view-swagger";
  }
378314
function convertPathToExpress(swaggerPath) {
    // eslint-disable-next-line no-useless-escape
    var reg = /\{([^\}]+)\}/g;  //match all {...}
    swaggerPath = _.replace(swaggerPath, reg, ':$1');
    return swaggerPath;
}
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
840132
def create_swagger_json_handler(app, **kwargs):
    

    spec = get_swagger_spec(app)
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    async def swagger(request):
        return HTTPResponse(
            body_bytes=encoded_spec,
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
763092
function swaggerQueryParamsToSchema(queryModel) {
  const requiredFields = [];
  const transformedProperties = {};
  _.forOwn(queryModel.items.properties, (value, key) => {
    if (value.required) {
      requiredFields.push(key);
    }
    transformedProperties[key] = {
      ...value
    };

    if (!_.isNil(transformedProperties[key].required)) {
      delete transformedProperties[key].required;
    }
  });

  return {
    title: queryModel.title,
    description: queryModel.description,
    additionalProperties: false,
    required: requiredFields,
    properties: transformedProperties
  };
}
932826
function ref_copy(from) {

	//console.log( 'at ref_copy(): from = ' + JSON.stringify(from) );
	//console.log( 'typeof from = ' + (typeof from) );

	var to;

	// Handle arrays
	if( from && (typeof from === 'object') && (from instanceof Array) ) {
		//console.log( '^ from is Array: ' + JSON.stringify(from) );

		to = ARRAY(from).map(ref_copy).valueOf();

	// Convert objects with a property `$ref` as a function shortcut to `Resource.get(url, opts)`;
	} else if( from && (typeof from === 'object') && (from.$ref !== undefined) ) {
		//console.log( '^ from is $ref-object: ' + JSON.stringify(from) );

		var url = from.$ref;
		to = new Resource.Partial();

		ref_copy_self(to, from);

		if(!is.string(to.$ref)) {
			debug.log('Warning! Partial object from '+ url +' does not have property $ref!');
		}

	// Convert normal objects
	} else if( from && (typeof from === 'object') ) {

		to = {};
		//console.log( '^ from is plain object: ' + JSON.stringify(from) );
		ref_copy_self(to, from);

	// Anything else is passed directly back
	} else {
		//console.log( '^ from is other type: ' + JSON.stringify(from) );
		to = from;
	}

	//console.log('..returning ' + JSON.stringify(to) + ' of type ' + (typeof to));
	return to;
}
752242
def _extract_models(cls, apis):
        ''''''
        # TODO: This would probably be much better if the info would be
        # extracted from the classes, rather than from the swagger
        # representation...
        models = set()
        for api in apis:
            for op in api.get('operations', []):
                models.add(op['type'])
                for param in op.get('parameters', []):
                    models.add(param.get('type', 'void'))
                for msg in op['responseMessages']:
                    models.add(msg.get('responseModel', 'void'))
        # Convert from swagger name representation to classes
        models = map(lambda m: Model.name_to_cls[m], models)
        ret = {}
        for model in models:
            if model.native_type:
                continue
            obj = model.schema.copy()
            obj['id'] = model.name
            ret[model.name] = obj
        return ret
192322
function (version) {
  var that = this;
  var createValidators = function (spec, validatorsMap) {
    return _.reduce(validatorsMap, function (result, schemas, schemaName) {
      result[schemaName] = helpers.createJsonValidator(schemas);

      return result;
    }, {});
  };
  var fixSchemaId = function (schemaName) {
    // Swagger 1.2 schema files use one id but use a different id when referencing schema files.  We also use the schema
    // file name to reference the schema in ZSchema.  To fix this so that the JSON Schema validator works properly, we
    // need to set the id to be the name of the schema file.
    var fixed = _.cloneDeep(that.schemas[schemaName]);

    fixed.id = schemaName;

    return fixed;
  };
  var primitives = ['string', 'number', 'boolean', 'integer', 'array'];

  switch (version) {
  case '1.2':
    this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/1.2.md';
    this.primitives = _.union(primitives, ['void', 'File']);
    this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v1.2';

    // Here explicitly to allow browserify to work
    this.schemas = {
      'apiDeclaration.json': require('../schemas/1.2/apiDeclaration.json'),
      'authorizationObject.json': require('../schemas/1.2/authorizationObject.json'),
      'dataType.json': require('../schemas/1.2/dataType.json'),
      'dataTypeBase.json': require('../schemas/1.2/dataTypeBase.json'),
      'infoObject.json': require('../schemas/1.2/infoObject.json'),
      'modelsObject.json': require('../schemas/1.2/modelsObject.json'),
      'oauth2GrantType.json': require('../schemas/1.2/oauth2GrantType.json'),
      'operationObject.json': require('../schemas/1.2/operationObject.json'),
      'parameterObject.json': require('../schemas/1.2/parameterObject.json'),
      'resourceListing.json': require('../schemas/1.2/resourceListing.json'),
      'resourceObject.json': require('../schemas/1.2/resourceObject.json')
    };

    this.validators = createValidators(this, {
      'apiDeclaration.json': _.map([
        'dataTypeBase.json',
        'modelsObject.json',
        'oauth2GrantType.json',
        'authorizationObject.json',
        'parameterObject.json',
        'operationObject.json',
        'apiDeclaration.json'
      ], fixSchemaId),
      'resourceListing.json': _.map([
        'resourceObject.json',
        'infoObject.json',
        'oauth2GrantType.json',
        'authorizationObject.json',
        'resourceListing.json'
      ], fixSchemaId)
    });

    break;

  case '2.0':
    this.docsUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md';
    this.primitives = _.union(primitives, ['file']);
    this.schemasUrl = 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0';

    // Here explicitly to allow browserify to work
    this.schemas = {
      'schema.json': require('../schemas/2.0/schema.json')
    };

    this.validators = createValidators(this, {
      'schema.json': [fixSchemaId('schema.json')]
    });

    break;

  default:
    throw new Error(version + ' is an unsupported Swagger specification version');
  }

  this.version = version;
}
34583
def swagger_doc(action, &block)
      parse = ParserAction.new(action, &block)
      parse.adding_path
    end
770685
function executeCommand(parameters) {
    // If a name has been provided, we create the project directory
    const modelFilePath = path.join(process.cwd(), plugin.config.modelsPath);
    return mkdirpAsync(modelFilePath)
    .then(() => {
      const model = {
        type: 'object',
        properties: {}
      };
      return fs.writeFileAsync(modelFilePath + path.sep + parameters.name + '.json', JSON.stringify(model, null, 2));
    })
    .then(() => {
      let msg = '\n  A new model has been created!\n\n';
      msg += '  Its Swagger specification is available in ' + icli.format.info(modelFilePath + path.sep + parameters.name + '.json') + '\n';
      icli.print(msg);
    });
  }
621361
function loadSpecification(defPath, data) {
  const resolvedPath = path.resolve(defPath);

  const extName = path.extname(resolvedPath);
  const loader = LOADERS[extName];

  // Check whether the definition file is actually a usable file
  if (loader === undefined) {
    throw new Error('Definition file should be .js, .json, .yml or .yaml');
  }

  const swaggerDefinition = loader(data, resolvedPath);
  return swaggerDefinition;
}
879724
function pluck() {
    var properties = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        properties[_i] = arguments[_i];
    }
    var length = properties.length;
    if (length === 0) {
        throw new Error('list of properties cannot be empty.');
    }
    return function (source) { return Object(_map__WEBPACK_IMPORTED_MODULE_0__["map"])(plucker(properties, length))(source); };
}
1010908
async function copyFiles(props) {
	const templatePath = get(props, 'templatePath', 'template')
	const src = path.resolve(__dirname, templatePath)
	const dest = path.resolve(get(props, 'context.name'))
	return await copy(src, dest, {
		rename: (pathname) => {
			return Handlebars.compile(pathname)(props)
		},
		transform: (src) => {
			if (isTemplate(src)) {
				return through(function (chunk, enc, done) {
					const template = Handlebars.compile(chunk.toString())
					done(null, template(props))
				})
			}
		}
	})
		.then(() => {
			return props
		})
		.catch(error => {
			switch (error.code) {
				case 'EEXIST':
					throw new Error(`The project at ${src} already exists.
					Delete it, move it or try another project name.`)
				default:
					throw new Error(error)
			}
		})
}
656504
function copy (source, target) {
    var defer = Q.defer()
    fs.createReadStream(source)
      .on('error', defer.reject.bind(defer))
      .pipe(fs.createWriteStream(target))
      .on('error', defer.reject.bind(defer))
      .on('finish', defer.fulfill.bind(defer))

    return defer.promise
  }
57797
function copyHooks() {
		var src = path.join(__dirname, 'hooks');
		var dest = path.join(process.env.PWD, 'hooks');

		return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json'))
			.then(function () {
				memFsEditor.copyTpl(src, dest, options);

				return pify(memFsEditor.commit.bind(memFsEditor))();
			})
			.then(function () {
				// Make all the scripts executable in the Cordova project
				fs.readdirSync(src).forEach(function (hook) {
					var hookPath = path.join(dest, hook);

					fs.readdirSync(hookPath).forEach(function (script) {
						fs.chmodSync(path.join(hookPath, script), '755');
					});
				});
			});
	}
562753
function (files, callback) {
		//loop on all files and write them
		async.each(files, function (fileObj, mCb) {
			var data = swagger.cloneObj(fileObj.data);
			
			//if tokens, replace all occurences with corresponding values
			if (fileObj.tokens) {
				for (var i in fileObj.tokens) {
					var regexp = new RegExp("%" + i + "%", "g");
					data = data.replace(regexp, fileObj.tokens[i]);
				}
			}
			if (fileObj.purify) {
				data = data.replace(/\\"/g, '"').replace(/["]+/g, '"').replace(/"__dirname/g, '__dirname');
				data = data.replace(/("group": "__empty__")/g, '"group": ""');
				data = data.replace(/("prefix": "(\s?|\s+),)/g, '"prefix": "",');
				data = data.replace(/("l": "__empty__")/g, '"l": ""');
				//"__dirname + \"/lib/mw/_get.js\""
				//"__dirname + "/lib/mw/_get.js""
				//"__dirname + "/lib/mw/_get.js"
				//__dirname + "/lib/mw/_get.js"
			}
			console.log("creating file:", fileObj.file);
			fs.writeFile(fileObj.file, data, "utf8", mCb);
		}, function (error) {
			if (error) {
				return callback({"code": 854, "msg": error.message});
			}
			return callback(null, true);
		});
	}