// fetchFalse fetches and checks remaining bytes of false keyword.
766668
func (r *Lexer) fetchFalse() {
	r.pos += 5
	if r.pos > len(r.Data) ||
		r.Data[r.pos-4] != 'a' ||
		r.Data[r.pos-3] != 'l' ||
		r.Data[r.pos-2] != 's' ||
		r.Data[r.pos-1] != 'e' ||
		(r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) {

		r.pos -= 5
		r.errSyntax()
	}
}
1186550
func GetFact(fact string, file string, log *logrus.Entry) ([]byte, gjson.Result, error) {
	j, err := JSON(file, log)
	if err != nil {
		return nil, gjson.Result{}, err
	}

	found := gjson.GetBytes(j, fact)
	if !found.Exists() {
		return nil, gjson.Result{}, nil
	}

	return j, found, nil
}
280063
func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) {
	scopedBucket, err := fetchReadScopeBucket(ns, scope)
	if err != nil {
		return 0, err
	}

	metaBucket := scopedBucket.NestedReadBucket(metaBucketName)

	val := metaBucket.Get(lastAccountName)
	if len(val) != 4 {
		str := fmt.Sprintf("malformed metadata '%s' stored in database",
			lastAccountName)
		return 0, managerError(ErrDatabase, str, nil)
	}

	account := binary.LittleEndian.Uint32(val[0:4])
	return account, nil
}
811992
func (c *CacheLazyFill) fetchEntityFromAPI(entityType, guid string) (*entity, error) {
	var md struct {
		Entity *entity `json:"entity"`
	}
	err := c.makeRequestAndDecodeJSON(fmt.Sprintf("/v2/%s/%s", entityType, guid), &md)
	if err != nil {
		return nil, err
	}
	return md.Entity, nil
}
220322
func (f *Fetcher) FetchImages(al *apps.Apps) error {
	return al.Walk(func(app *apps.App) error {
		d, err := DistFromImageString(app.Image)
		if err != nil {
			return err
		}
		h, err := f.FetchImage(d, app.Image, app.Asc)
		if err != nil {
			return err
		}
		app.ImageID = *h
		return nil
	})
}
930452
func (f *fileFetcher) getVerifiedFile(aciPath string, a *asc) (*os.File, error) {
	var aciFile *os.File // closed on error
	var errClose error   // error signaling to close aciFile

	f.maybeOverrideAsc(aciPath, a)
	ascFile, err := a.Get()
	if err != nil {
		return nil, errwrap.Wrap(errors.New("error opening signature file"), err)
	}
	defer ascFile.Close()

	aciFile, err = os.Open(aciPath)
	if err != nil {
		return nil, errwrap.Wrap(errors.New("error opening ACI file"), err)
	}

	defer func() {
		if errClose != nil {
			aciFile.Close()
		}
	}()

	validator, errClose := newValidator(aciFile)
	if errClose != nil {
		return nil, errClose
	}

	entity, errClose := validator.ValidateWithSignature(f.Ks, ascFile)
	if errClose != nil {
		return nil, errwrap.Wrap(fmt.Errorf("image %q verification failed", validator.ImageName()), errClose)
	}
	printIdentities(entity)

	return aciFile, nil
}
843543
func (b *BitcoindFeeEstimator) fetchEstimate(confTarget uint32) (SatPerKWeight, error) {
	// First, we'll send an "estimatesmartfee" command as a raw request,
	// since it isn't supported by btcd but is available in bitcoind.
	target, err := json.Marshal(uint64(confTarget))
	if err != nil {
		return 0, err
	}
	// TODO: Allow selection of economical/conservative modifiers.
	resp, err := b.bitcoindConn.RawRequest(
		"estimatesmartfee", []json.RawMessage{target},
	)
	if err != nil {
		return 0, err
	}

	// Next, we'll parse the response to get the BTC per KB.
	feeEstimate := struct {
		FeeRate float64 `json:"feerate"`
	}{}
	err = json.Unmarshal(resp, &feeEstimate)
	if err != nil {
		return 0, err
	}

	// Next, we'll convert the returned value to satoshis, as it's currently
	// returned in BTC.
	satPerKB, err := btcutil.NewAmount(feeEstimate.FeeRate)
	if err != nil {
		return 0, err
	}

	// Since we use fee rates in sat/kw internally, we'll convert the
	// estimated fee rate from its sat/kb representation to sat/kw.
	satPerKw := SatPerKVByte(satPerKB).FeePerKWeight()

	// Finally, we'll enforce our fee floor.
	if satPerKw < b.minFeePerKW {
		walletLog.Debugf("Estimated fee rate of %v sat/kw is too low, "+
			"using fee floor of %v sat/kw instead", satPerKw,
			b.minFeePerKW)

		satPerKw = b.minFeePerKW
	}

	walletLog.Debugf("Returning %v sat/kw for conf target of %v",
		int64(satPerKw), confTarget)

	return satPerKw, nil
}
393294
func (item *MoreLikeThisQueryItem) FetchSourceContext(fsc *FetchSourceContext) *MoreLikeThisQueryItem {
	item.fsc = fsc
	return item
}
549980
func (s *oracleVolumeSource) fetchVolumeAttachmentStatus(name, desiredStatus string) (bool, error) {
	details, err := s.api.StorageAttachmentDetails(name)
	if err != nil {
		return false, errors.Trace(err)
	}
	return string(details.State) == desiredStatus, nil
}
237052
func FetchFeedFiles(reqs []FetchRequest) (results []FetchResult, err error) {
	reqChan := make(chan FetchRequest, len(reqs))
	resChan := make(chan FetchResult, len(reqs))
	errChan := make(chan error, len(reqs))
	defer close(reqChan)
	defer close(resChan)
	defer close(errChan)

	for _, r := range reqs {
		log.Infof("Fetching... %s", r.URL)
	}

	go func() {
		for _, r := range reqs {
			reqChan <- r
		}
	}()

	concurrency := len(reqs)
	tasks := util.GenWorkers(concurrency)
	for range reqs {
		tasks <- func() {
			select {
			case req := <-reqChan:
				body, err := fetchFile(req, 20/len(reqs))
				if err != nil {
					errChan <- err
					return
				}
				resChan <- FetchResult{
					Year: req.Year,
					URL:  req.URL,
					Body: body,
				}
			}
			return
		}
	}

	errs := []error{}
	timeout := time.After(10 * 60 * time.Second)
	for range reqs {
		select {
		case res := <-resChan:
			results = append(results, res)
			log.Infof("Fetched... %s", res.URL)
		case err := <-errChan:
			errs = append(errs, err)
		case <-timeout:
			return results, fmt.Errorf("Timeout Fetching")
		}
	}
	if 0 < len(errs) {
		return results, fmt.Errorf("%s", errs)
	}
	return results, nil
}
748380
func (s *DriveService) Fetch(ctx context.Context, title string) (body io.ReadCloser, size uint32, err error) {
	file, err := s.Get(ctx, title)
	if err != nil {
		return
	}
	// TODO: maybe in the case of no download link, remove the file.
	// The file should have malformed or converted to a Docs file
	// unwantedly.
	// TODO(mpl): I do not think the above comment is accurate. It
	// looks like at least one case we do not get a DownloadUrl is when
	// the UI would make you pick a conversion format first (spreadsheet,
	// doc, etc). -> we should see if the API offers the possibility to do
	// that conversion. and we could pass the type(s) we want (pdf, xls, doc...)
	// as arguments (in an options struct) to Fetch.
	if file.DownloadUrl == "" {
		err = errNoDownload
		return
	}

	req, _ := http.NewRequest("GET", file.DownloadUrl, nil)
	req.WithContext(ctx)
	var resp *http.Response
	if resp, err = s.client.Transport.RoundTrip(req); err != nil {
		return
	}
	if file.FileSize > math.MaxUint32 || file.FileSize < 0 {
		err = errors.New("file too big")
	}
	return resp.Body, uint32(file.FileSize), err
}
313161
func (r *Lexer) fetchNumber() {
	hasE := false
	afterE := false
	hasDot := false

	r.pos++
	for i, c := range r.Data[r.pos:] {
		switch {
		case c >= '0' && c <= '9':
			afterE = false
		case c == '.' && !hasDot:
			hasDot = true
		case (c == 'e' || c == 'E') && !hasE:
			hasE = true
			hasDot = true
			afterE = true
		case (c == '+' || c == '-') && afterE:
			afterE = false
		default:
			r.pos += i
			if !isTokenEnd(c) {
				r.errSyntax()
			} else {
				r.token.byteValue = r.Data[r.start:r.pos]
			}
			return
		}
	}

	r.pos = len(r.Data)
	r.token.byteValue = r.Data[r.start:]
}
70817
func (this *SiestaClient) Fetch(topic string, partition int32, offset int64) ([]*Message, error) {
	Tracef(this, "Fetching %s %d from %d", topic, partition, offset)
	response, err := this.connector.Fetch(topic, partition, offset)
	if err != nil {
		return nil, err
	}

	messages := make([]*Message, 0)

	timestamp := time.Now().UnixNano() / int64(time.Millisecond)
	collector := func(topic string, partition int32, offset int64, key []byte, value []byte) error {
		decodedKey, err := this.config.KeyDecoder.Decode(key)
		if err != nil {
			//TODO: what if we fail to decode the key: fail-fast or fail-safe strategy?
			Error(this, err.Error())
			return err
		}
		decodedValue, err := this.config.ValueDecoder.Decode(value)
		if err != nil {
			//TODO: what if we fail to decode the value: fail-fast or fail-safe strategy?
			Error(this, err.Error())
			return err
		}

		if this.config.Debug {
			decodedKey = []int64{timestamp}
		}

		messages = append(messages, &Message{
			Key:                 key,
			Value:               value,
			DecodedKey:          decodedKey,
			DecodedValue:        decodedValue,
			Topic:               topic,
			Partition:           partition,
			Offset:              offset,
			HighwaterMarkOffset: response.Data[topic][partition].HighwaterMarkOffset,
		})
		return nil
	}

	return messages, response.CollectMessages(collector)
}
1104707
func (fn FetcherFunc) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) {
	return fn(ctx, desc)
}
329809
func Fetch(urlstring string, options ...Option) (*Set, error) {
	u, err := url.Parse(urlstring)
	if err != nil {
		return nil, errors.Wrap(err, `failed to parse url`)
	}

	switch u.Scheme {
	case "http", "https":
		return FetchHTTP(urlstring, options...)
	case "file":
		f, err := os.Open(u.Path)
		if err != nil {
			return nil, errors.Wrap(err, `failed to open jwk file`)
		}
		defer f.Close()

		buf, err := ioutil.ReadAll(f)
		if err != nil {
			return nil, errors.Wrap(err, `failed read content from jwk file`)
		}
		return ParseBytes(buf)
	}
	return nil, errors.Errorf(`invalid url scheme %s`, u.Scheme)
}
1264747
func (s *AuthService) GetSnapshot(c context.Context, rev int64) (*Snapshot, error) {
	// Fetch.
	var out struct {
		Snapshot struct {
			Rev          int64  `json:"auth_db_rev"`
			SHA256       string `json:"sha256"`
			Created      int64  `json:"created_ts"`
			DeflatedBody string `json:"deflated_body"`
		} `json:"snapshot"`
	}
	req := internal.Request{
		Method: "GET",
		URL:    fmt.Sprintf("%s/auth_service/api/v1/authdb/revisions/%d", s.URL, rev),
		Scopes: oauthScopes,
		Out:    &out,
	}
	if err := req.Do(c); err != nil {
		return nil, err
	}
	if out.Snapshot.Rev != rev {
		return nil, fmt.Errorf(
			"auth: unexpected revision %d of AuthDB snapshot, expecting %d", out.Snapshot.Rev, rev)
	}

	// Decode base64.
	deflated, err := base64.StdEncoding.DecodeString(out.Snapshot.DeflatedBody)
	if err != nil {
		return nil, err
	}

	// Inflate and calculate SHA256 of inflated blob.
	r, err := zlib.NewReader(bytes.NewReader(deflated))
	if err != nil {
		return nil, err
	}
	defer r.Close()
	blob := bytes.Buffer{}
	hash := sha256.New()
	if _, err := io.Copy(io.MultiWriter(&blob, hash), r); err != nil {
		return nil, err
	}

	// Make sure SHA256 is correct.
	digest := hex.EncodeToString(hash.Sum(nil))
	if digest != out.Snapshot.SHA256 {
		return nil, fmt.Errorf("auth: wrong SHA256 digest of AuthDB snapshot at rev %d", rev)
	}

	// Unmarshal.
	msg := protocol.ReplicationPushRequest{}
	if err := proto.Unmarshal(blob.Bytes(), &msg); err != nil {
		return nil, err
	}
	revMsg := msg.GetRevision()
	if revMsg == nil || revMsg.GetAuthDbRev() != rev {
		return nil, fmt.Errorf("auth: bad 'revision' field in proto message (%v)", revMsg)
	}

	// Log some stats.
	logging.Infof(
		c, "auth: fetched AuthDB snapshot at rev %d (inflated size is %.1f Kb, deflated size is %.1f Kb)",
		rev, float32(len(blob.Bytes()))/1024, float32(len(deflated))/1024)
	logging.Infof(
		c, "auth: AuthDB snapshot generated by %s (using components.auth v%s)",
		revMsg.GetPrimaryId(), msg.GetAuthCodeVersion())

	// Validate AuthDB (bad identity names, group dependency cycles, etc).
	authDB := msg.GetAuthDb()
	if authDB == nil {
		return nil, fmt.Errorf("auth: 'auth_db' field is missing in proto message (%v)", msg)
	}
	if err := validateAuthDB(authDB); err != nil {
		return nil, err
	}
	return &Snapshot{
		AuthDB:         authDB,
		AuthServiceURL: s.URL,
		Rev:            rev,
		Created:        time.Unix(0, out.Snapshot.Created*1000),
	}, nil
}
946369
func fetchUID(args []string, c *Conn, m mailstore.Message, peekOnly bool) string {
	return fmt.Sprintf("UID %d", m.UID())
}