// RunWithPrelude runs a REPL with the default prompt and the given prelude.
979051
func RunWithPrelude(vm *otto.Otto, prelude string) error {
	return RunWithOptions(vm, Options{
		Prelude: prelude,
	})
}
1370288
func (p *Prompt) Run() {
	defer debug.Teardown()
	debug.Log("start prompt")
	p.setUp()
	defer p.tearDown()

	if p.completion.showAtStart {
		p.completion.Update(*p.buf.Document())
	}

	p.renderer.Render(p.buf, p.completion)

	bufCh := make(chan []byte, 128)
	stopReadBufCh := make(chan struct{})
	go p.readBuffer(bufCh, stopReadBufCh)

	exitCh := make(chan int)
	winSizeCh := make(chan *WinSize)
	stopHandleSignalCh := make(chan struct{})
	go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)

	for {
		select {
		case b := <-bufCh:
			if shouldExit, e := p.feed(b); shouldExit {
				p.renderer.BreakLine(p.buf)
				stopReadBufCh <- struct{}{}
				stopHandleSignalCh <- struct{}{}
				return
			} else if e != nil {
				// Stop goroutine to run readBuffer function
				stopReadBufCh <- struct{}{}
				stopHandleSignalCh <- struct{}{}

				// Unset raw mode
				// Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
				debug.AssertNoError(p.in.TearDown())
				p.executor(e.input)

				p.completion.Update(*p.buf.Document())
				p.renderer.Render(p.buf, p.completion)

				// Set raw mode
				debug.AssertNoError(p.in.Setup())
				go p.readBuffer(bufCh, stopReadBufCh)
				go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
			} else {
				p.completion.Update(*p.buf.Document())
				p.renderer.Render(p.buf, p.completion)
			}
		case w := <-winSizeCh:
			p.renderer.UpdateWinSize(w)
			p.renderer.Render(p.buf, p.completion)
		case code := <-exitCh:
			p.renderer.BreakLine(p.buf)
			p.tearDown()
			os.Exit(code)
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}
}
1220281
func (g *Generator) AddPreStartHook(preStartHook rspec.Hook) error {
	g.initConfigHooks()
	g.Config.Hooks.Prestart = append(g.Config.Hooks.Prestart, preStartHook)
	return nil
}
1212229
func (d *Decoder) EscapeWith(r rune) *Decoder {
	d.e = r
	return d
}
281970
func (c *Crawler) Preprocess() (*goquery.Document, error) {
	var err error

	if c.RawHTML == "" {
		if c.RawHTML, err = c.fetchHTML(c.url, c.config.timeout); err != nil {
			return nil, err
		}
	}
	if c.RawHTML == "" {
		return nil, errors.New("cannot process empty HTML content")
	}

	c.RawHTML = c.addSpacesBetweenTags(c.RawHTML)

	reader := strings.NewReader(c.RawHTML)
	document, err := goquery.NewDocumentFromReader(reader)
	if err != nil {
		return nil, err
	}

	cs := c.GetCharset(document)
	//log.Println("-------------------------------------------CHARSET:", cs)
	if "" != cs && "UTF-8" != cs {
		// the net/html parser and goquery require UTF-8 data
		c.RawHTML = UTF8encode(c.RawHTML, cs)
		reader = strings.NewReader(c.RawHTML)
		if document, err = goquery.NewDocumentFromReader(reader); err != nil {
			return nil, err
		}
	}

	return document, nil
}
931301
func (parser *Parser) parsePrelude() (string, error) {
	result := ""

	for parser.tokenParsable() && !parser.tokenEndOfPrelude() {
		token := parser.shiftToken()
		result += token.Value
	}

	result = strings.TrimSpace(result)

	// log.Printf("[parsed] prelude: %s", result)

	return result, parser.err()
}
280269
func (r *RegisterMeteredCharm) RunPre(api DeployStepAPI, bakeryClient *httpbakery.Client, ctx *cmd.Context, deployInfo DeploymentInfo) error {
	if r.IncreaseBudget < 0 {
		return errors.Errorf("invalid budget increase %d", r.IncreaseBudget)
	}
	var err error
	// if the deployInfo specifies an application plan it means
	// that it is to be deployed as part of the bundle and should
	// be deployed using the specified plan: the bundle author
	// clearly marked it as a metered application so there's no need
	// to check.
	if deployInfo.ApplicationPlan != "" {
		r.Plan = deployInfo.ApplicationPlan
		if r.Plan == "default" {
			r.Plan, err = r.getDefaultPlan(bakeryClient, deployInfo.CharmID.URL.String())
			if err != nil {
				return errors.Trace(err)
			}
		}
	} else {
		// otherwise we check if the charm is metered
		metered, err := api.IsMetered(deployInfo.CharmID.URL.String())
		if err != nil {
			return errors.Trace(err)
		}
		if !metered {
			return nil
		}

		info := deployInfo.CharmInfo
		if r.Plan == "" && info.Metrics != nil && !info.Metrics.PlanRequired() {
			return nil
		}

		// if the plan was not specified and this is a charmstore charm we
		// check if the charm has a default plan
		if r.Plan == "" && deployInfo.CharmID.URL.Schema == "cs" {
			r.Plan, err = r.getDefaultPlan(bakeryClient, deployInfo.CharmID.URL.String())
			if err != nil {
				if isNoDefaultPlanError(err) {
					options, err1 := r.getCharmPlans(bakeryClient, deployInfo.CharmID.URL.String())
					if err1 != nil {
						return err1
					}
					charmURL := deployInfo.CharmID.URL.String()
					if len(options) > 0 {
						return errors.Errorf(`%v has no default plan. Try "juju deploy --plan <plan-name> with one of %v"`, charmURL, strings.Join(options, ", "))
					} else {
						return errors.Errorf("no plans available for %v.", charmURL)
					}
				}
				return err
			}
		}
	}

	r.credentials, err = r.registerMetrics(
		deployInfo.ModelUUID,
		deployInfo.CharmID.URL.String(),
		deployInfo.ApplicationName,
		bakeryClient,
	)
	if err != nil {
		if deployInfo.CharmID.URL.Schema == "cs" {
			logger.Infof("failed to obtain plan authorization: %v", err)
			return err
		}
		logger.Debugf("no plan authorization: %v", err)
	}
	return nil
}
814684
func (ra *runAction) Prepare(state State) (*State, error) {
	rnr, err := ra.runnerFactory.NewActionRunner(ra.actionId)
	if cause := errors.Cause(err); charmrunner.IsBadActionError(cause) {
		if err := ra.callbacks.FailAction(ra.actionId, err.Error()); err != nil {
			return nil, err
		}
		return nil, ErrSkipExecute
	} else if cause == charmrunner.ErrActionNotAvailable {
		return nil, ErrSkipExecute
	} else if err != nil {
		return nil, errors.Annotatef(err, "cannot create runner for action %q", ra.actionId)
	}
	actionData, err := rnr.Context().ActionData()
	if err != nil {
		// this should *really* never happen, but let's not panic
		return nil, errors.Trace(err)
	}
	err = rnr.Context().Prepare()
	if err != nil {
		return nil, errors.Trace(err)
	}
	ra.name = actionData.Name
	ra.runner = rnr
	return stateChange{
		Kind:     RunAction,
		Step:     Pending,
		ActionId: &ra.actionId,
		Hook:     state.Hook,
	}.apply(state), nil
}
1191698
func RunWithPrivilege(name string, fn func() error) error {
	return RunWithPrivileges([]string{name}, fn)
}
750263
func (s *Deque) Prepend(item interface{}) bool {
	s.Lock()
	defer s.Unlock()

	if s.capacity < 0 || s.container.Len() < s.capacity {
		s.container.PushFront(item)
		return true
	}

	return false
}
499277
func (s *Selection) Prepend(selector string) *Selection {
	return s.PrependMatcher(compileMatcher(selector))
}
1110343
func (s *Redirect) SetReplaceKeyPrefixWith(v string) *Redirect {
	s.ReplaceKeyPrefixWith = &v
	return s
}
1045342
func (s *PerUserKeyring) PreparePrev(m MetaContext, newSeed PerUserKeySeed,
	newGeneration keybase1.PerUserKeyGeneration) (PerUserKeyPrev, error) {
	s.Lock()
	defer s.Unlock()

	if newSeed.IsBlank() {
		return "", errors.New("attempt to prev with blank per-user-key")
	}

	currentGen := s.currentGenerationLocked()
	if currentGen == 0 {
		return "", errors.New("attempt to prepare per-user-key prev with no keys")
	}
	if currentGen != newGeneration-1 {
		return "", fmt.Errorf("incompatible prev generations %v != %v-1", currentGen, newGeneration)
	}

	symmetricKey, err := newSeed.derivePrevKey()
	if err != nil {
		return "", err
	}

	contents := s.generations[currentGen].seed

	return newPerUserKeyPrev(contents, symmetricKey)
}
685015
func (h Handler) Prepend(cmd common.SetRequest) error {
	_, err := h.doRequest(cmd, common.RequestPrepend)
	return err
}
824041
func RunWithPrompt(vm *otto.Otto, prompt string) error {
	return RunWithOptions(vm, Options{
		Prompt: prompt,
	})
}
2321
func (r *Router) WithPrefix(prefix string) *Router {
	return &Router{rtr: r.rtr, prefix: r.prefix + prefix, instrh: r.instrh}
}
1146594
func REPL(od storage.Store, input *os.File, rl ReadLiner, chanSize, bulkSize, builderSize int, done chan bool) int {
	var tracer io.Writer
	ctx, isTracingToFile, sessionStart := context.Background(), false, time.Now()

	driverPlain := func() storage.Store {
		return od
	}

	driverWithMemoization := func() storage.Store {
		return memoization.New(od)
	}

	driver := driverWithMemoization

	stopTracing := func() {
		if tracer != nil {
			if isTracingToFile {
				fmt.Println("Closing tracing file.")
				tracer.(*os.File).Close()
			}
			tracer, isTracingToFile = nil, false
		}
	}
	defer stopTracing()

	fmt.Printf("Welcome to BadWolf vCli (%d.%d.%d-%s)\n", version.Major, version.Minor, version.Patch, version.Release)
	fmt.Printf("Using driver %s/%s. Type quit; to exit.\n", driver().Name(ctx), driver().Version(ctx))
	fmt.Printf("Session started at %v.\n", sessionStart.Format("2006-01-02T15:04:05.999999-07:00"))
	fmt.Println("Memoization enabled. Type help; to print help.")
	fmt.Println()
	defer func() {
		fmt.Printf("\n\nThanks for all those BQL queries!\nSession duration: %v\n\n", time.Now().Sub(sessionStart))
	}()

	for l := range rl(done) {
		if strings.HasPrefix(l, "quit") {
			done <- true
			break
		}
		if strings.HasPrefix(l, "help") {
			printHelp()
			done <- false
			continue
		}
		if strings.HasPrefix(l, "enable memoization") {
			driver = driverWithMemoization
			fmt.Println("[OK] Partial query memoization is on.")
			done <- false
			continue
		}
		if strings.HasPrefix(l, "disable memoization") {
			driver = driverPlain
			fmt.Println("[OK] Partial query memoization is off.")
			done <- false
			continue
		}
		if strings.HasPrefix(l, "start tracing") {
			args := strings.Split(strings.TrimSpace(l)[:len(l)-1], " ")
			switch len(args) {
			case 2:
				// Start tracing to the console.
				stopTracing()
				tracer, isTracingToFile = os.Stdout, false
				fmt.Println("[WARNING] Tracing is on. This may slow your BQL queries.")
			case 3:
				// Start tracing to file.
				stopTracing()
				f, err := os.Create(args[2])
				if err != nil {
					fmt.Println(err)
				} else {
					tracer, isTracingToFile = f, true
					fmt.Println("[WARNING] Tracing is on. This may slow your BQL queries.")
				}
			default:
				fmt.Println("Invalid syntax\n\tstart tracing [trace_file]")
			}
			done <- false
			continue
		}
		if strings.HasPrefix(l, "stop tracing") {
			stopTracing()
			fmt.Println("Tracing is off.")
			done <- false
			continue
		}
		if strings.HasPrefix(l, "export") {
			now := time.Now()
			args := strings.Split("bw "+strings.TrimSpace(l)[:len(l)-1], " ")
			usage := "Wrong syntax\n\n\tload <graph_names_separated_by_commas> <file_path>\n"
			export.Eval(ctx, usage, args, driver(), bulkSize)
			fmt.Println("[OK] Time spent: ", time.Now().Sub(now))
			done <- false
			continue
		}
		if strings.HasPrefix(l, "load") {
			now := time.Now()
			args := strings.Split("bw "+strings.TrimSpace(l[:len(l)-1]), " ")
			usage := "Wrong syntax\n\n\tload <file_path> <graph_names_separated_by_commas>\n"
			load.Eval(ctx, usage, args, driver(), bulkSize, builderSize)
			fmt.Println("[OK] Time spent: ", time.Now().Sub(now))
			done <- false
			continue
		}
		if strings.HasPrefix(l, "desc") {
			pln, err := planBQL(ctx, l[4:], driver(), chanSize, bulkSize, nil)
			if err != nil {
				fmt.Printf("[ERROR] %s\n\n", err)
			} else {
				if pln != nil {
					fmt.Println(pln.String(ctx))
				}
				fmt.Println("[OK]")
			}
			done <- false
			continue
		}
		if strings.HasPrefix(l, "run") {
			now := time.Now()
			path, cmds, err := runBQLFromFile(ctx, driver(), chanSize, bulkSize, strings.TrimSpace(l[:len(l)-1]), tracer)
			if err != nil {
				fmt.Printf("[ERROR] %s\n\n", err)
			} else {
				fmt.Printf("Loaded %q and run %d BQL commands successfully\n\n", path, cmds)
			}
			fmt.Println("Time spent: ", time.Now().Sub(now))
			done <- false
			continue
		}

		now := time.Now()
		table, err := runBQL(ctx, l, driver(), chanSize, bulkSize, tracer)
		bqlDiff := time.Now().Sub(now)
		if err != nil {
			fmt.Printf("[ERROR] %s\n", err)
			fmt.Println("Time spent: ", time.Now().Sub(now))
			fmt.Println()
		} else {
			if table == nil {
				fmt.Printf("[OK] 0 rows retrieved. BQL time: %v. Display time: %v\n",
					bqlDiff, time.Now().Sub(now)-bqlDiff)
			} else {
				if len(table.Bindings()) > 0 {
					fmt.Println(table.String())
				}
				fmt.Printf("[OK] %d rows retrieved. BQL time: %v. Display time: %v\n",
					table.NumRows(), bqlDiff, time.Now().Sub(now)-bqlDiff)
			}
		}
		done <- false
	}
	return 0
}