// Dispatch writes the template filename, template layout and (any) data to the  client.
// Completes the `Result` interface.
193987
func (r View) Dispatch(ctx context.Context) { // r as Response view.
	if r.Err != nil {
		if r.Code < 400 {
			r.Code = DefaultErrStatusCode
		}
		ctx.StatusCode(r.Code)
		ctx.WriteString(r.Err.Error())
		ctx.StopExecution()
		return
	}

	if r.Code > 0 {
		ctx.StatusCode(r.Code)
	}

	if r.Name != "" {
		r.Name = ensureExt(r.Name)

		if r.Layout != "" {
			r.Layout = ensureExt(r.Layout)
			ctx.ViewLayout(r.Layout)
		}

		if r.Data != nil {
			// In order to respect any c.Ctx.ViewData that may called manually before;
			dataKey := ctx.Application().ConfigurationReadOnly().GetViewDataContextKey()
			if ctx.Values().Get(dataKey) == nil {
				// if no c.Ctx.ViewData set-ed before (the most common scenario) then do a
				// simple set, it's faster.
				ctx.Values().Set(dataKey, r.Data)
			} else {
				// else check if r.Data is map or struct, if struct convert it to map,
				// do a range loop and modify the data one by one.
				// context.Map is actually a map[string]interface{} but we have to make that check:
				if m, ok := r.Data.(map[string]interface{}); ok {
					setViewData(ctx, m)
				} else if m, ok := r.Data.(context.Map); ok {
					setViewData(ctx, m)
				} else if di.IndirectValue(reflect.ValueOf(r.Data)).Kind() == reflect.Struct {
					setViewData(ctx, structs.Map(r))
				}
			}
		}

		ctx.View(r.Name)
	}
}
1079736
func (g *goFileGenerator) Generate(filename, tmpl string, data interface{}) ([]byte, error) {
	funcs := template.FuncMap{
		"import":     g.Import,
		"formatType": g.FormatType,
	}
	for k, v := range g.templateFuncs {
		funcs[k] = v
	}

	t, err := template.New(filename).Delims("<", ">").Funcs(funcs).Parse(tmpl)
	if err != nil {
		return nil, fmt.Errorf("failed to parse template %q: %v", filename, err)
	}

	var buff bytes.Buffer
	if err := t.Execute(&buff, data); err != nil {
		return nil, err
	}

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, filename, buff.Bytes(), parser.ParseComments)
	if err != nil {
		return nil, fmt.Errorf("failed to parse generated code: %v:\n%s", err, buff.String())
	}

	if len(f.Imports) > 0 {
		return nil, fmt.Errorf(
			"plain imports are not allowed with GoFileFromTemplate: use the import function")
	}

	importPaths := make([]string, 0, len(g.imports))
	for path := range g.imports {
		importPaths = append(importPaths, path)
	}
	sort.Strings(importPaths)
	for _, path := range importPaths {
		astutil.AddNamedImport(fset, f, g.imports[path], path)
	}

	buff = bytes.Buffer{}
	if err := format.Node(&buff, fset, f); err != nil {
		return nil, err // TODO wrap error
	}

	return buff.Bytes(), nil
}
144789
func (c *Controller) TemplateOutput(templatePath string) (data []byte, err error) {
	return TemplateOutputArgs(templatePath, c.ViewArgs)
}
23614
func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
	tmpl, err := template.ParseFiles(srcPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to parse template "+srcPath)
	}

	f, err := os.Create(destPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to create  ", "path", destPath)
	}

	err = tmpl.Execute(f, data)
	if err != nil {
		return NewBuildIfError(err, "Failed to Render template "+srcPath)
	}

	err = f.Close()
	if err != nil {
		return NewBuildIfError(err, "Failed to close file stream "+destPath)
	}
	return
}
1301651
func (contract *SNativeContractDescription) Dispatch(st Interface, caller crypto.Address,
	args []byte, gas *uint64, logger *logging.Logger) (output []byte, err error) {

	logger = logger.With(structure.ScopeKey, "Dispatch", "contract_name", contract.Name)

	if len(args) < abi.FunctionIDSize {
		return nil, errors.ErrorCodef(errors.ErrorCodeNativeFunction,
			"SNatives dispatch requires a 4-byte function identifier but arguments are only %v bytes long",
			len(args))
	}

	var id abi.FunctionID
	copy(id[:], args)
	function, err := contract.FunctionByID(id)
	if err != nil {
		return nil, err
	}

	logger.TraceMsg("Dispatching to function",
		"caller", caller,
		"function_name", function.Name)

	remainingArgs := args[abi.FunctionIDSize:]

	// check if we have permission to call this function
	if !HasPermission(st, caller, function.PermFlag) {
		return nil, errors.LacksSNativePermission{Address: caller, SNative: function.Name}
	}

	nativeArgs := reflect.New(function.Arguments).Interface()
	err = abi.UnpackIntoStruct(function.Abi.Inputs, remainingArgs, nativeArgs)
	if err != nil {
		return nil, err
	}

	nativeRets, err := function.F(st, caller, gas, logger, nativeArgs)
	if err != nil {
		return nil, err
	}
	err = st.Error()
	if err != nil {
		return nil, fmt.Errorf("state error in %v: %v", function, err)
	}

	return abi.PackIntoStruct(function.Abi.Outputs, nativeRets)
}
617283
func (c *Context) Render(name string, data interface{}) error {
	return c.weavebox.templateEngine.Render(c.Response(), name, data)
}
1083127
func (d *eventDispatcher) DispatchEvent(e Event) {
	d.RLock()
	defer d.RUnlock()

	// Automatically set the event source.
	if e, ok := e.(*event); ok {
		e.source = d.source
	}

	// Dispatch the event to all listeners.
	for _, l := range d.listeners[e.Type()] {
		l(e)
	}
}
1054243
func (r *Render) compile() {
	for _, ts := range r.templates {
		fileList := make([]string, len(ts.fileList))
		for i, f := range ts.fileList {
			fileList[i] = path.Join(r.opt.Directory, f)
		}
		ts.template = template.New(ts.entry)
		ts.template.Delims(r.opt.Delims.Left, r.opt.Delims.Right)
		for _, funcs := range r.opt.Funcs {
			ts.template.Funcs(funcs)
		}
		ts.template = template.Must(ts.template.ParseFiles(fileList...))
	}
	log.Debugf("Templates have been compiled, count=%d", len(r.templates))
}
996613
func (t *Template) Execute(w io.Writer, data interface{}) error {
	return t.tmpl.Execute(w, data)
}
708645
func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) {
	writer := httpWriter

	// CompressingResponseWriter should be closed after all operations are done
	defer func() {
		if compressWriter, ok := writer.(*CompressingResponseWriter); ok {
			compressWriter.Close()
		}
	}()

	// Instal panic recovery unless told otherwise
	if !c.doNotRecover { // catch all for 500 response
		defer func() {
			if r := recover(); r != nil {
				c.recoverHandleFunc(r, writer)
				return
			}
		}()
	}

	// Find best match Route ; err is non nil if no match was found
	var webService *WebService
	var route *Route
	var err error
	func() {
		c.webServicesLock.RLock()
		defer c.webServicesLock.RUnlock()
		webService, route, err = c.router.SelectRoute(
			c.webServices,
			httpRequest)
	}()

	// Detect if compression is needed
	// assume without compression, test for override
	contentEncodingEnabled := c.contentEncodingEnabled
	if route != nil && route.contentEncodingEnabled != nil {
		contentEncodingEnabled = *route.contentEncodingEnabled
	}
	if contentEncodingEnabled {
		doCompress, encoding := wantsCompressedResponse(httpRequest)
		if doCompress {
			var err error
			writer, err = NewCompressingResponseWriter(httpWriter, encoding)
			if err != nil {
				log.Print("unable to install compressor: ", err)
				httpWriter.WriteHeader(http.StatusInternalServerError)
				return
			}
		}
	}

	if err != nil {
		// a non-200 response has already been written
		// run container filters anyway ; they should not touch the response...
		chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) {
			switch err.(type) {
			case ServiceError:
				ser := err.(ServiceError)
				c.serviceErrorHandleFunc(ser, req, resp)
			}
			// TODO
		}}
		chain.ProcessFilter(NewRequest(httpRequest), NewResponse(writer))
		return
	}
	pathProcessor, routerProcessesPath := c.router.(PathProcessor)
	if !routerProcessesPath {
		pathProcessor = defaultPathProcessor{}
	}
	pathParams := pathProcessor.ExtractParameters(route, webService, httpRequest.URL.Path)
	wrappedRequest, wrappedResponse := route.wrapRequestResponse(writer, httpRequest, pathParams)
	// pass through filters (if any)
	if len(c.containerFilters)+len(webService.filters)+len(route.Filters) > 0 {
		// compose filter chain
		allFilters := []FilterFunction{}
		allFilters = append(allFilters, c.containerFilters...)
		allFilters = append(allFilters, webService.filters...)
		allFilters = append(allFilters, route.Filters...)
		chain := FilterChain{Filters: allFilters, Target: func(req *Request, resp *Response) {
			// handle request by route after passing all filters
			route.Function(wrappedRequest, wrappedResponse)
		}}
		chain.ProcessFilter(wrappedRequest, wrappedResponse)
	} else {
		// no filters, handle request by route
		route.Function(wrappedRequest, wrappedResponse)
	}
}
1322408
func (loader *TemplateLoader) Template(name string) (tmpl Template, err error) {
	runtimeLoader := loader.runtimeLoader.Load().(*templateRuntime)
	return runtimeLoader.TemplateLang(name, "")
}
615706
func (c Client) Generate(dir string) error {
	globAPIDef = c.APIDef

	// generate helper
	if err := commons.GenerateFile(nil, "./templates/python/client_utils_python.tmpl", "client_utils_python", filepath.Join(dir, "client_utils.py"), true); err != nil {
		return err
	}

	// generate http client
	if err := commons.GenerateFile(nil, c.Template.httpClientFile, c.Template.httpClientName, filepath.Join(dir, "http_client.py"), true); err != nil {
		return err
	}

	if err := c.generateServices(dir); err != nil {
		return err
	}

	if err := c.generateSecurity(dir); err != nil {
		return err
	}

	// python classes
	classes, err := GenerateAllClasses(c.APIDef, dir, false)
	if err != nil {
		return err
	}

	// helper for python classes
	if err := commons.GenerateFile(nil, "./templates/python/client_support.tmpl",
		"client_support", filepath.Join(dir, "client_support.py"), true); err != nil {
		return err
	}

	if c.UnmarshallResponse {
		if err := commons.GenerateFile(nil, "./templates/python/unmarshall_error.tmpl",
			"unmarshall_error", filepath.Join(dir, "unmarshall_error.py"), true); err != nil {
			return err
		}
		if err := commons.GenerateFile(nil, "./templates/python/unhandled_api_error.tmpl",
			"unhandled_api_error", filepath.Join(dir, "unhandled_api_error.py"), true); err != nil {
			return err
		}
	}

	sort.Strings(classes)
	c.Classes = classes
	return commons.GenerateFile(c, c.Template.initFile, c.Template.initName, filepath.Join(dir, "__init__.py"), true)
}
119122
func (d *dispatcher) dispatch(e Event) {
	// needed so dispatches of events triggered in the listeners can be received without blocking
	go func() {
		for id, l := range d.listeners(e.TargetID, e.Name) {
			if l(e) {
				d.delListener(e.TargetID, e.Name, id)
			}
		}
	}()
}
151587
func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error {
	var im *imageMount
	var err error
	if c.From != "" {
		im, err = d.getImageMount(c.From)
		if err != nil {
			return errors.Wrapf(err, "invalid from flag value %s", c.From)
		}
	}
	copier := copierFromDispatchRequest(d, errOnSourceDownload, im)
	defer copier.Cleanup()
	copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "COPY")
	if err != nil {
		return err
	}
	copyInstruction.chownStr = c.Chown
	if c.From != "" && copyInstruction.chownStr == "" {
		copyInstruction.preserveOwnership = true
	}
	return d.builder.performCopy(d, copyInstruction)
}
527312
func (s *scheduler) dispatch(e *edge) {
	inc := make([]pipe.Sender, len(s.incoming[e]))
	for i, p := range s.incoming[e] {
		inc[i] = p.Sender
	}
	out := make([]pipe.Receiver, len(s.outgoing[e]))
	for i, p := range s.outgoing[e] {
		out[i] = p.Receiver
	}

	e.hasActiveOutgoing = false
	updates := []pipe.Receiver{}
	for _, p := range out {
		if ok := p.Receive(); ok {
			updates = append(updates, p)
		}
		if !p.Status().Completed {
			e.hasActiveOutgoing = true
		}
	}

	pf := &pipeFactory{s: s, e: e}

	// unpark the edge
	debugSchedulerPreUnpark(e, inc, updates, out)
	e.unpark(inc, updates, out, pf)
	debugSchedulerPostUnpark(e, inc)

postUnpark:
	// set up new requests that didn't complete/were added by this run
	openIncoming := make([]*edgePipe, 0, len(inc))
	for _, r := range s.incoming[e] {
		if !r.Sender.Status().Completed {
			openIncoming = append(openIncoming, r)
		}
	}
	if len(openIncoming) > 0 {
		s.incoming[e] = openIncoming
	} else {
		delete(s.incoming, e)
	}

	openOutgoing := make([]*edgePipe, 0, len(out))
	for _, r := range s.outgoing[e] {
		if !r.Receiver.Status().Completed {
			openOutgoing = append(openOutgoing, r)
		}
	}
	if len(openOutgoing) > 0 {
		s.outgoing[e] = openOutgoing
	} else {
		delete(s.outgoing, e)
	}

	// if keys changed there might be possiblity for merge with other edge
	if e.keysDidChange {
		if k := e.currentIndexKey(); k != nil {
			// skip this if not at least 1 key per dep
			origEdge := e.index.LoadOrStore(k, e)
			if origEdge != nil {
				logrus.Debugf("merging edge %s to %s\n", e.edge.Vertex.Name(), origEdge.edge.Vertex.Name())
				if s.mergeTo(origEdge, e) {
					s.ef.setEdge(e.edge, origEdge)
				}
			}
		}
		e.keysDidChange = false
	}

	// validation to avoid deadlocks/resource leaks:
	// TODO: if these start showing up in error reports they can be changed
	// to error the edge instead. They can only appear from algorithm bugs in
	// unpark(), not for any external input.
	if len(openIncoming) > 0 && len(openOutgoing) == 0 {
		e.markFailed(pf, errors.New("buildkit scheduler error: return leaving incoming open. Please report this with BUILDKIT_SCHEDULER_DEBUG=1"))
		goto postUnpark
	}
	if len(openIncoming) == 0 && len(openOutgoing) > 0 {
		e.markFailed(pf, errors.New("buildkit scheduler error: return leaving outgoing open. Please report this with BUILDKIT_SCHEDULER_DEBUG=1"))
		goto postUnpark
	}
}
128900
func (d *Dispatcher) Dispatch(etype Type, value interface{}) error {
	d.RLock()
	defer d.RUnlock()
	return d.dispatch(etype, value)
}
470045
func (p *PeriodicDispatch) dispatch(job *structs.Job, launchTime time.Time) {
	p.l.Lock()

	nextLaunch, err := job.Periodic.Next(launchTime)
	if err != nil {
		p.logger.Error("failed to parse next periodic launch", "job", job.NamespacedID(), "error", err)
	} else if err := p.heap.Update(job, nextLaunch); err != nil {
		p.logger.Error("failed to update next launch of periodic job", "job", job.NamespacedID(), "error", err)
	}

	// If the job prohibits overlapping and there are running children, we skip
	// the launch.
	if job.Periodic.ProhibitOverlap {
		running, err := p.dispatcher.RunningChildren(job)
		if err != nil {
			p.logger.Error("failed to determine if periodic job has running children", "job", job.NamespacedID(), "error", err)
			p.l.Unlock()
			return
		}

		if running {
			p.logger.Debug("skipping launch of periodic job because job prohibits overlap", "job", job.NamespacedID())
			p.l.Unlock()
			return
		}
	}

	p.logger.Debug(" launching job", "job", job.NamespacedID(), "launch_time", launchTime)
	p.l.Unlock()
	p.createEval(job, launchTime)
}