Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml
        represents an externally exposed port.
963619
def get_route_templates(self):
        
        def _get_published_ports(service_config):
            result = []
            for port in service_config.get('ports', []):
                protocol = 'TCP'
                if isinstance(port, string_types) and '/' in port:
                    port, protocol = port.split('/')
                if isinstance(port, string_types) and ':' in port:
                    host, container = port.split(':')
                else:
                    host = port
                result.append({'port': host, 'protocol': protocol.lower()})
            return result

        templates = []
        for name, service_config in self._services.items():
            state = service_config.get(self.CONFIG_KEY, {}).get('state', 'present')
            force = service_config.get(self.CONFIG_KEY, {}).get('force', False)
            published_ports = _get_published_ports(service_config)

            if state != 'present':
                continue

            for port in published_ports:
                route_name = "%s-%s" % (name, port['port'])
                labels = dict(
                    app=self._namespace_name,
                    service=name
                )
                template = CommentedMap()
                template['apiVersion'] = self.DEFAULT_API_VERSION
                template['kind'] = 'Route'
                template['force'] = force
                template['metadata'] = CommentedMap([
                    ('name', route_name),
                    ('namespace', self._namespace_name),
                    ('labels', labels.copy())
                ])
                template['spec'] = CommentedMap([
                    ('to', CommentedMap([
                        ('kind', 'Service'),
                        ('name', name)
                    ])),
                    ('port', CommentedMap([
                        ('targetPort', 'port-{}-{}'.format(port['port'], port['protocol']))
                    ]))
                ])

                if service_config.get(self.CONFIG_KEY, {}).get('routes'):
                    for route in service_config[self.CONFIG_KEY]['routes']:
                        if str(route.get('port')) == str(port['port']):
                            for key, value in route.items():
                                if key not in ('force', 'port'):
                                    self.copy_attribute(template['spec'], key, value)

                templates.append(template)

        return templates
659093
def load_extended_config_yaml
      Dir.glob("#{ENV['HOME']}/.ftl/templates/*.yml").each do |file|
        yaml = YAML.load_file(file)
        name = File.basename(file).gsub(".yml", '')
        @options[:templates][name.to_sym]=@options[:templates][:defaults]
        @options[:templates][name.to_sym].merge!(yaml)
      end
    end
891084
def generate_docker_compose(self):
        
        example = {}
        example['app'] = {}
        example['app']['environment'] = []
        for key in sorted(list(self.spec.keys())):
            if self.spec[key]['type'] in (dict, list):
                value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'"
            else:
                value = f"{self.spec[key].get('example', '')}"
            example['app']['environment'].append(f"{self.env_prefix}_{key.upper()}={value}")
        print(yaml.dump(example, default_flow_style=False))
559126
private String render(io.wcm.caravan.hal.docs.impl.model.Service service, Map<String, Object> model,
      Template template) throws IOException {
    Map<String, Object> mergedModel = ImmutableMap.<String, Object>builder()
        .putAll(model)
        .put("docsContext", ImmutableMap.<String, Object>builder()
            .put("baseUrl", DocsPath.get(service.getServiceId()) + "/")
            .put("resourcesPath", HalDocsBundleTracker.DOCS_RESOURCES_URI_PREFIX)
            .build())
        .build();
    return template.apply(mergedModel);
  }
15545
def generate_app
      copy_templates
      app = File.read File.expand_path("../templates/app.erb", __FILE__)
      erb = ERB.new app, 0, '-'

      File.open "#{@destination}/#{@app_name}.rb", "w" do |f|
        f.write erb.result(binding)
      end

      route = File.read File.expand_path("../templates/app/routes/home.erb", __FILE__)
      erb = ERB.new route, 0, '-'

      File.open "#{@destination}/app/routes/home.rb", "w" do |f|
        f.write erb.result(binding)
      end

      FileUtils.rm "#{@destination}/app/routes/home.erb"
    end
186680
def create_stack_template(  self,
                                lambda_arn,
                                lambda_name,
                                api_key_required,
                                iam_authorization,
                                authorizer,
                                cors_options=None,
                                description=None,
                                endpoint_configuration=None
                            ):
        

        auth_type = "NONE"
        if iam_authorization and authorizer:
            logger.warn("Both IAM Authorization and Authorizer are specified, this is not possible. "
                        "Setting Auth method to IAM Authorization")
            authorizer = None
            auth_type = "AWS_IAM"
        elif iam_authorization:
            auth_type = "AWS_IAM"
        elif authorizer:
            auth_type = authorizer.get("type", "CUSTOM")

        # build a fresh template
        self.cf_template = troposphere.Template()
        self.cf_template.add_description('Automatically generated with Zappa')
        self.cf_api_resources = []
        self.cf_parameters = {}

        restapi = self.create_api_gateway_routes(
                                            lambda_arn,
                                            api_name=lambda_name,
                                            api_key_required=api_key_required,
                                            authorization_type=auth_type,
                                            authorizer=authorizer,
                                            cors_options=cors_options,
                                            description=description,
                                            endpoint_configuration=endpoint_configuration
                                        )
        return self.cf_template
249781
def build():
    
    test_files()
    with open('content.rst') as f:
        content = publish_parts(f.read(), writer_name='html')
        title = content['title']
        body =  content['html_body'].replace('\n',' ')

    with open('template.jinja', 'r') as f:
        loader = FileSystemLoader(getcwd())
        env= Environment(loader=loader)
        template = env.get_template('template.jinja')
        page =  template.render(title=title,
                                content=body)

    with open('index.html', 'w') as f:
        f.write(page)
367416
def _generate_routes(self, namespace):
        

        # Hack: needed for _docf()
        self.cur_namespace = namespace
        # list of auth_types supported in this base class.
        # this is passed with the new -w flag
        if self.args.auth_type is not None:
            self.supported_auth_types = [auth_type.strip().lower() for auth_type in self.args.auth_type.split(',')]

        check_route_name_conflict(namespace)

        for route in namespace.routes:
            # compatibility mode : included routes are passed by whitelist
            # actual auth attr inluded in the route is ignored in this mode.
            if self.supported_auth_types is None:
                self._generate_route_helper(namespace, route)
                if route.attrs.get('style') == 'download':
                    self._generate_route_helper(namespace, route, True)
            else:
                route_auth_attr = None
                if route.attrs is not None:
                    route_auth_attr = route.attrs.get('auth')
                if route_auth_attr is None:
                    continue
                route_auth_modes = [mode.strip().lower() for mode in route_auth_attr.split(',')]
                for base_auth_type in self.supported_auth_types:
                    if base_auth_type in route_auth_modes:
                        self._generate_route_helper(namespace, route)
                        if route.attrs.get('style') == 'download':
                            self._generate_route_helper(namespace, route, True)
                        break
251358
function generateRouter(path, modelName, generateMethod, ts, cb) {
    var extension = (ts) ? 'ts' : 'js';
    var router = ft.loadTemplateSync('router.' + extension);
    router = router.replace(/{controllerName}/g, modelName + 'Controller');

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'routes', function () {
            router = router.replace(/{controllerPath}/g, '\'../controllers/' + modelName + 'Controller.' + extension + '\'');
            ft.writeFile(path + '/routes/' + modelName + 'Routes.' + extension, router, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            router = router.replace(/{controllerPath}/g, '\'./' + modelName + 'Controller.' + extension + '\'');
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Routes.' + extension, router, null, cb);
        });
    }
}
646608
def build_routes(iface, **settings):
    '''
    
    '''

    template = 'rh6_route_eth.jinja'
    try:
        if int(__grains__['osrelease'][0]) < 6:
            template = 'route_eth.jinja'
    except ValueError:
        pass
    log.debug('Template name: %s', template)

    opts = _parse_routes(iface, settings)
    log.debug('Opts: \n %s', opts)
    try:
        template = JINJA.get_template(template)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', template)
        return ''
    opts6 = []
    opts4 = []
    for route in opts['routes']:
        ipaddr = route['ipaddr']
        if salt.utils.validate.net.ipv6_addr(ipaddr):
            opts6.append(route)
        else:
            opts4.append(route)
    log.debug("IPv4 routes:\n%s", opts4)
    log.debug("IPv6 routes:\n%s", opts6)

    routecfg = template.render(routes=opts4, iface=iface)
    routecfg6 = template.render(routes=opts6, iface=iface)

    if settings['test']:
        routes = _read_temp(routecfg)
        routes.extend(_read_temp(routecfg6))
        return routes

    _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}')
    _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}')

    path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface))
    path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface))

    routes = _read_file(path)
    routes.extend(_read_file(path6))
    return routes
267418
def to_yaml
      require 'yaml'
      trackers_export = @trackers.reduce({}) do |export, tracker|
        export[tracker.title] = tracker.to_yaml_object; export
      end
      YAML.dump(trackers_export)
    end
607106
def container
      @opf_path = opf_path
      tmplfile = File.expand_path('./xml/container.xml.erb', ReVIEW::Template::TEMPLATE_DIR)
      tmpl = ReVIEW::Template.load(tmplfile)
      tmpl.result(binding)
    end
1185220
def _generate_route_m(self, route, namespace, route_args, extra_args,
                          task_type_name, func_suffix):
        """"""
        user_args = list(route_args)

        transport_args = [
            ('route', 'route'),
            ('arg', 'arg' if not is_void_type(route.arg_data_type) else 'nil'),
        ]

        for name, value, typ in extra_args:
            user_args.append((name, typ))
            transport_args.append((name, value))

        with self.block_func(
                func='{}{}'.format(fmt_route_func(route), func_suffix),
                args=fmt_func_args_declaration(user_args),
                return_type='{} *'.format(task_type_name)):
            self.emit('DBRoute *route = {}.{};'.format(
                fmt_route_obj_class(namespace.name),
                fmt_route_var(namespace.name, route)))
            if is_union_type(route.arg_data_type):
                self.emit('{} *arg = {};'.format(
                    fmt_class_prefix(route.arg_data_type),
                    fmt_var(route.arg_data_type.name)))
            elif not is_void_type(route.arg_data_type):
                init_call = fmt_func_call(
                    caller=fmt_alloc_call(
                        caller=fmt_class_prefix(route.arg_data_type)),
                    callee=self._cstor_name_from_fields_names(route_args),
                    args=fmt_func_args([(f[0], f[0]) for f in route_args]))
                self.emit('{} *arg = {};'.format(
                    fmt_class_prefix(route.arg_data_type), init_call))
            request_call = fmt_func_call(
                caller='self.client',
                callee='request{}'.format(
                    fmt_camel_upper(route.attrs.get('style'))),
                args=fmt_func_args(transport_args))
            self.emit('return {};'.format(request_call))
        self.emit()
710269
def build_lane_from_yaml(path):
    
    # Open
    with open(path, 'rb') as yaml_definition:
        definition = yaml.load(yaml_definition)

    # Validate schema
    try:
        validate_schema(definition)
    except SchemaError as exc:
        raise LaneSchemaError(**exc.__dict__)

    def build(lb_def, branch=False):
        """Function to recursively build the `sparklanes.Lane` object from a YAML definition"""
        init_kwargs = {k: lb_def[k] for k in (a for a in ('run_parallel', 'name') if a in lb_def)}
        lane_or_branch = Lane(**init_kwargs) if not branch else Branch(**init_kwargs)

        for task in lb_def['tasks']:
            if 'branch' in task:
                branch_def = task['branch']
                lane_or_branch.add(build(branch_def, True))
            else:
                sep = task['class'].rfind('.')
                if sep == -1:
                    raise LaneImportError('Class must include its parent module')
                mdl = task['class'][:sep]
                cls_ = task['class'][sep + 1:]

                try:
                    cls = getattr(import_module(mdl), cls_)
                except ImportError:
                    raise LaneImportError('Could not find module %s' % mdl)
                except AttributeError:
                    raise LaneImportError('Could not find class %s' % cls_)

                args = task['args'] if 'args' in task else []
                args = [args] if not isinstance(args, list) else args
                kwargs = task['kwargs'] if 'kwargs' in task else {}
                lane_or_branch.add(cls, *args, **kwargs)

        return lane_or_branch

    return build(definition['lane'])
562898
protected void generateRoutes()
    {
        try {

//			Optional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//			
//			typeLevelWrapAnnotation.ifPresent( a -> {
//				 
//				io.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();
//
//				Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//
//				for (int i = 0; i < wrapperClasses.length; i++)
//				{
//					Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//
//					String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//
//					handlerWrapperMap.put(wrapperClass, wrapperName);
//				}
//				
//			});
//			
//			for(Method m : this.controllerClass.getDeclaredMethods())
//			{
//			
//				Optional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//				
//				methodLevelWrapAnnotation.ifPresent( a -> {
//					 
//					io.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();
//	
//					Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//	
//					for (int i = 0; i < wrapperClasses.length; i++)
//					{
//						Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//	
//						String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//	
//						handlerWrapperMap.put(wrapperClass, wrapperName);
//					}
//					
//				});
//
//			}
//			
//			log.info("handlerWrapperMap: " + handlerWrapperMap);

            TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));

            ClassName extractorClass = ClassName.get("io.sinistral.proteus.server", "Extractors");

            ClassName injectClass = ClassName.get("com.google.inject", "Inject");


            MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);

            String className = this.controllerClass.getSimpleName().toLowerCase() + "Controller";

            typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);

            ClassName wrapperClass = ClassName.get("io.undertow.server", "HandlerWrapper");
            ClassName stringClass = ClassName.get("java.lang", "String");
            ClassName mapClass = ClassName.get("java.util", "Map");

            TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);

            TypeName annotatedMapOfWrappers = mapOfWrappers
                    .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember("value", "$S", "registeredHandlerWrappers").build());

            typeBuilder.addField(mapOfWrappers, "registeredHandlerWrappers", Modifier.PROTECTED, Modifier.FINAL);


            constructor.addParameter(this.controllerClass, className);
            constructor.addParameter(annotatedMapOfWrappers, "registeredHandlerWrappers");

            constructor.addStatement("this.$N = $N", className, className);
            constructor.addStatement("this.$N = $N", "registeredHandlerWrappers", "registeredHandlerWrappers");

            addClassMethodHandlers(typeBuilder, this.controllerClass);

            typeBuilder.addMethod(constructor.build());

            JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, "*").build();

            StringBuilder sb = new StringBuilder();

            javaFile.writeTo(sb);

            this.sourceString = sb.toString();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
281827
def _generate_client_h(self, api):
        """"""
        self.emit_raw(stone_warning)

        self.emit('#import <Foundation/Foundation.h>')

        import_classes = [
            fmt_routes_class(ns.name, self.args.auth_type)
            for ns in api.namespaces.values()
            if ns.routes and self.namespace_to_has_routes[ns]
        ]
        import_classes.append('DBRequestErrors')
        import_classes.append('DBTasks')

        self._generate_imports_m(import_classes)
        self.emit()
        self.emit('NS_ASSUME_NONNULL_BEGIN')
        self.emit()
        self.emit('@protocol {};'.format(self.args.transport_client_name))
        self.emit()

        self.emit(comment_prefix)
        description_str = (
            'Base client object that contains an instance field for '
            'each namespace, each of which contains references to all routes within '
            'that namespace. Fully-implemented API clients will inherit this class.'
        )
        self.emit_wrapped_text(description_str, prefix=comment_prefix)
        self.emit(comment_prefix)
        with self.block_h(
                self.args.class_name,
                protected=[
                    ('transportClient',
                     'id<{}>'.format(self.args.transport_client_name))
                ]):
            self.emit()
            for namespace in api.namespaces.values():
                if namespace.routes and self.namespace_to_has_routes[namespace]:
                    class_doc = 'Routes within the `{}` namespace.'.format(
                        fmt_var(namespace.name))
                    self.emit_wrapped_text(class_doc, prefix=comment_prefix)
                    prop = '{}Routes'.format(fmt_var(namespace.name))
                    typ = '{} *'.format(
                        fmt_routes_class(namespace.name, self.args.auth_type))
                    self.emit(fmt_property_str(prop=prop, typ=typ))
                    self.emit()

            client_args = fmt_func_args_declaration(
                [('client',
                  'id<{}>'.format(self.args.transport_client_name))])

            description_str = (
                'Initializes the `{}` object with a networking client.')
            self.emit_wrapped_text(
                description_str.format(self.args.class_name),
                prefix=comment_prefix)
            init_signature = fmt_signature(
                func='initWithTransportClient',
                args=client_args,
                return_type='instancetype')
            self.emit('{};'.format(init_signature))
            self.emit()

        self.emit()
        self.emit('NS_ASSUME_NONNULL_END')
1098756
def _setup_services(self):
        
        self.pool = mitogen.service.Pool(
            router=self.router,
            services=[
                mitogen.service.FileService(router=self.router),
                mitogen.service.PushFileService(router=self.router),
                ansible_mitogen.services.ContextService(self.router),
                ansible_mitogen.services.ModuleDepService(self.router),
            ],
            size=getenv_int('MITOGEN_POOL_SIZE', default=32),
        )
        LOG.debug('Service pool configured: size=%d', self.pool.size)