// Executed top-down
514805
func renderer(w http.ResponseWriter, r *http.Request, v Renderer) error {
	rv := reflect.ValueOf(v)
	if rv.Kind() == reflect.Ptr {
		rv = rv.Elem()
	}

	// We call it top-down.
	if err := v.Render(w, r); err != nil {
		return err
	}

	// We're done if the Renderer isn't a struct object
	if rv.Kind() != reflect.Struct {
		return nil
	}

	// For structs, we call Render on each field that implements Renderer
	for i := 0; i < rv.NumField(); i++ {
		f := rv.Field(i)
		if f.Type().Implements(rendererType) {

			if isNil(f) {
				continue
			}

			fv := f.Interface().(Renderer)
			if err := renderer(w, r, fv); err != nil {
				return err
			}

		}
	}

	return nil
}
931528
func (o TopImagesOptions) Run() error {
	infos := o.imagesTop()
	Print(o.Out, ImageColumns, infos)
	return nil
}
707816
func (i *DefaultInterpreter) Execute(
	expression string,
	ctx *Context) (interface{}, error) {
	funcs := template.FuncMap{}
	for k, v := range i.Funcs {
		funcs[k] = v
	}
	var res interface{}
	resultEvaluated := false
	funcs["set"] = func(r interface{}) interface{} {
		res = r
		resultEvaluated = true
		return r
	}
	funcs["eval"] = func(intrpr, expr string) (interface{}, error) {
		return ctx.EvalExpr(intrpr, expr, ctx)
	}
	templName := fmt.Sprintf("<<%s>>", ctx.LongName)
	left := i.LeftDelim
	right := i.RightDelim
	if left == "" {
		left = "{{"
	}
	if right == "" {
		right = "}}"
	}
	if i.AutoEnclose &&
		!(strings.HasPrefix(expression, left) &&
			strings.HasSuffix(expression, right)) {
		expression = fmt.Sprintf("%s%s%s", left, expression, right)
	}
	t, err := template.
		New(templName).
		Delims(left, right).
		Funcs(funcs).
		Parse(expression)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	err = t.Execute(&buf, ctx)
	if err != nil {
		return nil, err
	}
	if resultEvaluated {
		return res, nil
	}
	return buf.String(), nil
}
201962
func (ts *TiDBStatement) Execute(ctx context.Context, args ...interface{}) (rs ResultSet, err error) {
	tidbRecordset, err := ts.ctx.session.ExecutePreparedStmt(ctx, ts.id, args...)
	if err != nil {
		return nil, err
	}
	if tidbRecordset == nil {
		return
	}
	rs = &tidbResultSet{
		recordSet: tidbRecordset,
	}
	return
}
410317
func (rc *runCommands) Execute(state State) (*State, error) {
	logger.Tracef("run commands: %s", rc)
	if err := rc.callbacks.SetExecutingStatus("running commands"); err != nil {
		return nil, errors.Trace(err)
	}

	response, err := rc.runner.RunCommands(rc.args.Commands)
	switch err {
	case context.ErrRequeueAndReboot:
		logger.Warningf("cannot requeue external commands")
		fallthrough
	case context.ErrReboot:
		rc.sendResponse(response, nil)
		err = ErrNeedsReboot
	default:
		rc.sendResponse(response, err)
	}
	return nil, err
}
739331
func (oa *OrderedAggregate) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	qr, err := oa.execute(vcursor, bindVars, wantfields)
	if err != nil {
		return nil, err
	}
	return qr.Truncate(oa.TruncateColumnCount), nil
}
500537
func (a ActionFunc) Execute(ctx context.Context, state *Peco, e termbox.Event) {
	a(ctx, state, e)
}
1035403
func (w *ControllersWriter) Execute(data []*ControllerTemplateData) error {
	if len(data) == 0 {
		return nil
	}
	for _, d := range data {
		if err := w.ExecuteTemplate("controller", ctrlT, nil, d); err != nil {
			return err
		}
		if err := w.ExecuteTemplate("mount", mountT, nil, d); err != nil {
			return err
		}
		if len(d.Origins) > 0 {
			if err := w.ExecuteTemplate("handleCORS", handleCORST, nil, d); err != nil {
				return err
			}
		}
		fn := template.FuncMap{
			"newCoerceData":  newCoerceData,
			"finalizeCode":   w.Finalizer.Code,
			"arrayAttribute": arrayAttribute,
			"validationCode": w.Validator.Code,
			"valueTypeOf":    valueTypeOf,
			"fromString":     fromString,
		}
		if err := w.ExecuteTemplate("unmarshal", unmarshalT, fn, d); err != nil {
			return err
		}
	}
	return nil
}
752284
func (c *CmdImport) Execute(args []string) error {
	c.fullPkgName = c.Args.Package
	fmt.Printf("Processing %q\n", c.Args.Package)

	objects, err := c.getObjects()
	if err != nil {
		return err
	}

	c.getCurrentPckgName()
	return c.render(objects)
}
222517
func (command *DocsCommand) Execute() error {
	log.Debug("Generating api docs in %s", command.Format)
	apiDef := new(raml.APIDefinition)
	err := raml.ParseFile(command.RamlFile, apiDef)
	if err != nil {
		return err
	}
	return codegen.GenerateDocs(apiDef, command.Format, command.OutputFile)
}
1072142
func (p *FetchJvnCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	c.Conf.Debug = p.debug
	c.Conf.Quiet = p.quiet
	c.Conf.DebugSQL = p.debugSQL
	c.Conf.DBPath = p.dbpath
	c.Conf.DBType = p.dbtype
	//  c.Conf.DumpPath = p.dumpPath
	c.Conf.HTTPProxy = p.httpProxy

	log.SetLogger(p.logDir, c.Conf.Quiet, c.Conf.Debug, p.logJSON)
	if !c.Conf.Validate() {
		return subcommands.ExitUsageError
	}

	years := []int{}
	thisYear := time.Now().Year()

	switch {
	case p.latest:
		years = append(years, c.Latest)
	case p.last2Y:
		for i := 0; i < 2; i++ {
			years = append(years, thisYear-i)
		}
		years = append(years, c.Latest)
	case p.years:
		if len(f.Args()) == 0 {
			log.Errorf("Specify years to fetch (from 1998 to %d)", thisYear)
			return subcommands.ExitUsageError
		}
		for _, arg := range f.Args() {
			year, err := strconv.Atoi(arg)
			if err != nil || year < 1998 || time.Now().Year() < year {
				log.Errorf("Specify years to fetch (from 1998 to %d), arg: %s", thisYear, arg)
				return subcommands.ExitUsageError
			}
			found := false
			for _, y := range years {
				if y == year {
					found = true
					break
				}
			}
			if !found {
				years = append(years, year)
			}
		}
		years = append(years, c.Latest)
	default:
		log.Errorf("specify -latest, -last2y or -years")
		return subcommands.ExitUsageError
	}

	driver, locked, err := db.NewDB(c.Conf.DBType, c.Conf.DBPath, c.Conf.DebugSQL)
	if err != nil {
		if locked {
			log.Errorf("Failed to Open DB. Close DB connection before fetching: %s", err)
			return subcommands.ExitFailure
		}
		log.Errorf("%s", err)
		return subcommands.ExitFailure
	}
	defer driver.CloseDB()

	metas, err := jvn.FetchLatestFeedMeta(driver, years)
	if err != nil {
		log.Errorf("%s", err)
		return subcommands.ExitFailure
	}

	if len(metas) == 0 {
		log.Errorf("No meta files fetched")
		return subcommands.ExitFailure
	}

	//TODO use meta.Status()
	needUpdates := []models.FeedMeta{}
	for _, m := range metas {
		if m.Newly() {
			needUpdates = append(needUpdates, m)
			log.Infof("Newly     : %s", m.URL)
		} else if m.OutDated() {
			needUpdates = append(needUpdates, m)
			log.Infof("Outdated  : %s", m.URL)
		} else {
			log.Infof("Up to date: %s", m.URL)
		}
	}

	if len(needUpdates) == 0 {
		log.Infof("Already up to date")
		return subcommands.ExitSuccess
	}

	log.Infof("Fetcling CVE information from JVN.")
	cves, err := jvn.FetchConvert(needUpdates)
	if err != nil {
		log.Errorf("Failed to fetch JVN: %s", err)
		return subcommands.ExitFailure
	}
	log.Infof("Fetched %d CVEs", len(cves))

	log.Infof("Inserting JVN into DB (%s).", driver.Name())
	if err := driver.InsertJvn(cves); err != nil {
		log.Fatalf("Failed to insert. dbpath: %s, err: %s", c.Conf.DBPath, err)
		return subcommands.ExitFailure
	}

	if err := jvn.UpdateMeta(driver, needUpdates); err != nil {
		log.Fatalf("Failed to Update meta. dbpath: %s, err: %s", c.Conf.DBPath, err)
		return subcommands.ExitFailure
	}
	return subcommands.ExitSuccess
}
320079
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.WithError(err).Error("Monitor failed")
		os.Exit(-1)
	}
}
187509
func (rl *resignLeadership) Execute(state State) (*State, error) {
	// TODO(fwereade): this hits a lot of interestingly intersecting problems.
	//
	// 1) we can't yet create a sufficiently dumbed-down hook context for a
	//    leader-deposed hook to run as specced. (This is the proximate issue,
	//    and is sufficient to prevent us from implementing this op right.)
	// 2) we want to write a state-file change, so this has to be an operation
	//    (or, at least, it has to be serialized with all other operations).
	//      * note that the change we write must *not* include the RunHook
	//        operation for leader-deposed -- we want to run this at high
	//        priority, in any possible state, and not to disturn what's
	//        there other than to note that we no longer think we're leader.
	// 3) the hook execution itself *might* not need to be serialized with
	//    other operations, which is moot until we consider that:
	// 4) we want to invoke this behaviour from elsewhere (ie when we don't
	//    have an api connection available), but:
	// 5) we can't get around the serialization requirement in (2).
	//
	// So. I *think* that the right approach is to implement a no-api uniter
	// variant, that we run *instead of* the normal uniter when the API is
	// unavailable, and replace with a real uniter when appropriate; this
	// implies that we need to take care not to allow the implementations to
	// diverge, but implementing them both as "uniters" is probably the best
	// way to encourage logic-sharing and prevent that problem.
	//
	// In the short term, though, we can just run leader-deposed as soon as we
	// can build the right environment. Not sure whether this particular type
	// will still be justified, or whether it'll just be a plain old RunHook --
	// I *think* it will stay, because the state-writing behaviour will stay
	// very different (ie just write `.Leader = false` and don't step on pre-
	// queued hooks).
	logger.Warningf("we should run a leader-deposed hook here, but we can't yet")
	return nil, nil
}
1373095
func (cmd *headersCmd) Execute(args []string) error {
	// Setup the global config options and ensure they are valid.
	if err := setupGlobalConfig(); err != nil {
		return err
	}

	// Load the block database.
	db, err := loadBlockDB()
	if err != nil {
		return err
	}
	defer db.Close()

	// NOTE: This code will only work for ffldb.  Ideally the package using
	// the database would keep a metadata index of its own.
	blockIdxName := []byte("ffldb-blockidx")
	if !headersCfg.Bulk {
		err = db.View(func(tx database.Tx) error {
			totalHdrs := 0
			blockIdxBucket := tx.Metadata().Bucket(blockIdxName)
			blockIdxBucket.ForEach(func(k, v []byte) error {
				totalHdrs++
				return nil
			})
			log.Infof("Loading headers for %d blocks...", totalHdrs)
			numLoaded := 0
			startTime := time.Now()
			blockIdxBucket.ForEach(func(k, v []byte) error {
				var hash chainhash.Hash
				copy(hash[:], k)
				_, err := tx.FetchBlockHeader(&hash)
				if err != nil {
					return err
				}
				numLoaded++
				return nil
			})
			log.Infof("Loaded %d headers in %v", numLoaded,
				time.Since(startTime))
			return nil
		})
		return err
	}

	// Bulk load headers.
	err = db.View(func(tx database.Tx) error {
		blockIdxBucket := tx.Metadata().Bucket(blockIdxName)
		hashes := make([]chainhash.Hash, 0, 500000)
		blockIdxBucket.ForEach(func(k, v []byte) error {
			var hash chainhash.Hash
			copy(hash[:], k)
			hashes = append(hashes, hash)
			return nil
		})

		log.Infof("Loading headers for %d blocks...", len(hashes))
		startTime := time.Now()
		hdrs, err := tx.FetchBlockHeaders(hashes)
		if err != nil {
			return err
		}
		log.Infof("Loaded %d headers in %v", len(hdrs),
			time.Since(startTime))
		return nil
	})
	return err
}
430892
func (dl *dialLimiter) executeDial(j *dialJob) {
	defer dl.finishedDial(j)
	if j.cancelled() {
		return
	}

	dctx, cancel := context.WithTimeout(j.ctx, j.dialTimeout())
	defer cancel()

	con, err := dl.dialFunc(dctx, j.peer, j.addr)
	select {
	case j.resp <- dialResult{Conn: con, Addr: j.addr, Err: err}:
	case <-j.ctx.Done():
		if err == nil {
			con.Close()
		}
	}
}
1272355
func (env *Env) Execute(tpl string, out io.Writer, ctx map[string]Value) error {
	return execute(tpl, out, ctx, env)
}
602901
func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error {
	for i, child := range node.Children {
		step := b.Step()
		if err := step.Resolve(child); err != nil {
			return err
		}
		glog.V(4).Infof("step: %s", step.Original)
		if e.LogFn != nil {
			// original may have unescaped %, so perform fmt escaping
			e.LogFn(strings.Replace(step.Original, "%", "%%", -1))
		}
		noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]})

		if err := b.Run(step, e, noRunsRemaining); err != nil {
			return err
		}
	}

	return nil
}