// getMDForRead returns an existing md for a read operation. Note that
// mds will not be fetched here.
966089
func (fbo *folderBranchOps) getMDForRead(
	ctx context.Context, lState *kbfssync.LockState, rtype mdReadType) (
	md ImmutableRootMetadata, err error) {
	if rtype != mdReadNeedIdentify && rtype != mdReadNoIdentify {
		panic("Invalid rtype in getMDLockedForRead")
	}

	md = fbo.getTrustedHead(ctx, lState, mdCommit)
	if md != (ImmutableRootMetadata{}) {
		if rtype != mdReadNoIdentify {
			err = fbo.identifyOnce(ctx, md.ReadOnly())
		}
		return md, err
	}

	return ImmutableRootMetadata{}, MDWriteNeededInRequest{}
}
311089
func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
	return openAtIndex(dirpath, snap, false)
}
130434
func (md *MDCacheStandard) GetNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error) {
	key := mdcacheNextMDKey{tlfID, rootSeqno}
	tmp, ok := md.nextMDLRU.Get(key)
	if !ok {
		return nil, nil, 0, NextMDNotCachedError{tlfID, rootSeqno}
	}
	val, ok := tmp.(mdcacheNextMDVal)
	if !ok {
		return nil, nil, 0, errors.Errorf(
			"Bad next MD for %s, seqno=%d", tlfID, rootSeqno)
	}
	return val.nextKbfsRoot, val.nextMerkleNodes, val.nextRootSeqno, nil
}
864899
func ChecksumForReader(rd io.Reader) ([]byte, error) {
	h := sha256.New()
	if _, err := io.Copy(h, rd); err != nil {
		return nil, err
	}
	return h.Sum(nil), nil
}
108762
func (m *MeterBandDSCPRemark) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(r, &meterBand{},
		&m.Rate, &m.BurstSize, &m.PrecLevel, &defaultPad3)
}
1294641
func getReadingByIdHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	vars := mux.Vars(r)
	id := vars["id"]

	switch r.Method {
	case http.MethodGet:
		reading, err := getReadingById(id)
		if err != nil {
			switch err := err.(type) {
			case *errors.ErrDbNotFound:
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			default: //return an error on everything else.
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		encode(reading, w)
	}
}
1314693
func (d *GrovePiDriver) DigitalRead(pin string) (val int, err error) {
	pin = getPin(pin)

	var pinNum int
	pinNum, err = strconv.Atoi(pin)
	if err != nil {
		return
	}

	if dir, ok := d.digitalPins[pinNum]; !ok || dir != "input" {
		d.PinMode(byte(pinNum), "input")
		d.digitalPins[pinNum] = "input"
	}

	val, err = d.readDigital(byte(pinNum))

	return
}
653179
func GetUserMetadata(ctx context.Context) (*UserMetadata, bool) {
	userMD := ctx.Value(userMDKey{})

	switch md := userMD.(type) {
	case *UserMetadata:
		return md, true
	default:
		return nil, false
	}
}
942711
func getMd5(file string) (string, error) {
	of, err := os.Open(file)
	if err != nil {
		return "", err
	}
	defer of.Close()

	hash := md5.New()
	_, err = io.Copy(hash, of)
	if err != nil {
		// fatal error
		return "", err
	}
	return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
993830
func MD5FromReader(r io.Reader) (string, error) {
	h := md5.New()
	if _, err := io.Copy(h, r); err != nil {
		return "", nil
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}
153182
func readThreadList(mdmp *Minidump, buf *minidumpBuf) {
	threadNum := buf.u32()
	if buf.err != nil {
		return
	}

	mdmp.Threads = make([]Thread, threadNum)

	for i := range mdmp.Threads {
		buf.ctx = fmt.Sprintf("reading thread list entry %d", i)
		thread := &mdmp.Threads[i]

		thread.ID = buf.u32()
		thread.SuspendCount = buf.u32()
		thread.PriorityClass = buf.u32()
		thread.Priority = buf.u32()
		thread.TEB = buf.u64()
		if buf.err != nil {
			return
		}

		readMemoryDescriptor(mdmp, buf)                    // thread stack
		_, rawThreadContext := readLocationDescriptor(buf) // thread context
		thread.Context = *((*winutil.CONTEXT)(unsafe.Pointer(&rawThreadContext[0])))
		if buf.err != nil {
			return
		}
	}
}
176528
func (md *MDOpsStandard) GetIDForHandle(
	ctx context.Context, handle *tlfhandle.Handle) (id tlf.ID, err error) {
	mdcache := md.config.MDCache()
	id, err = mdcache.GetIDForHandle(handle)
	switch errors.Cause(err).(type) {
	case NoSuchTlfIDError:
		// Do the server-based lookup below.
	case nil:
		return id, nil
	default:
		return tlf.NullID, err
	}
	id, _, err = md.getForHandle(ctx, handle, kbfsmd.Merged, nil)
	switch errors.Cause(err).(type) {
	case kbfsmd.ServerErrorClassicTLFDoesNotExist:
		// The server thinks we should create an implicit team for this TLF.
		return tlf.NullID, nil
	case nil:
	default:
		return tlf.NullID, err
	}
	err = mdcache.PutIDForHandle(handle, id)
	if err != nil {
		return tlf.NullID, err
	}
	return id, nil
}
1036728
func (md *MDCacheStandard) GetIDForHandle(handle *tlfhandle.Handle) (tlf.ID, error) {
	md.lock.RLock()
	defer md.lock.RUnlock()
	key := handle.GetCanonicalPath()
	tmp, ok := md.idLRU.Get(key)
	if !ok {
		return tlf.NullID, NoSuchTlfIDError{handle}
	}
	id, ok := tmp.(tlf.ID)
	if !ok {
		return tlf.NullID, errors.Errorf("Bad ID for handle %s", key)
	}
	return id, nil
}
477435
func (r *decodingReadSeeker) getReadaheadFactor() int64 {
	mb := int64(1 << 20)
	switch {
	case r.size >= 1000*mb:
		return 16
	case r.size >= 500*mb:
		return 8
	default:
		return 4
	}
}
832203
func (mc MongoClient) getReading(q bson.M) (models.Reading, error) {
	s := mc.getSessionCopy()
	defer s.Close()

	var res models.Reading
	if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).One(&res); err != nil {
		return models.Reading{}, errorMap(err)
	}
	return res, nil
}
1014818
func (mc MongoClient) ReadingsByDeviceAndValueDescriptor(deviceId, valueDescriptor string, limit int) ([]contract.Reading, error) {
	return mapReadings(mc.getReadingsLimit(bson.M{"device": deviceId, "name": valueDescriptor}, limit))
}
863238
func (md *MDServerRemote) RegisterForUpdate(ctx context.Context, id tlf.ID,
	currHead kbfsmd.Revision) (<-chan error, error) {
	arg := keybase1.RegisterForUpdatesArg{
		FolderID:     id.String(),
		CurrRevision: currHead.Number(),
		LogTags:      nil,
	}

	// register
	var c chan error
	conn := md.getConn()
	err := conn.DoCommand(ctx, "register", func(rawClient rpc.GenericClient) error {
		// set up the server to receive updates, since we may
		// get disconnected between retries.
		server := conn.GetServer()
		err := server.Register(keybase1.MetadataUpdateProtocol(md))
		if err != nil {
			if _, ok := err.(rpc.AlreadyRegisteredError); !ok {
				return err
			}
		}
		// TODO: Do something with server.Err() when server is
		// done?
		server.Run()

		// keep re-adding the observer on retries, since
		// disconnects or connection errors clear observers.
		alreadyRegistered := func() bool {
			md.observerMu.Lock()
			defer md.observerMu.Unlock()
			// It's possible for a nil channel to be in
			// `md.observers`, if we are still registered with the
			// server after a previous cancellation.
			existingCh, alreadyRegistered := md.observers[id]
			if existingCh != nil {
				panic(fmt.Sprintf(
					"Attempted double-registration for folder: %s", id))
			}
			c = make(chan error, 1)
			md.observers[id] = c
			return alreadyRegistered
		}()
		if alreadyRegistered {
			return nil
		}
		// Use this instead of md.client since we're already
		// inside a DoCommand().
		c := keybase1.MetadataClient{Cli: rawClient}
		err = c.RegisterForUpdates(ctx, arg)
		if err != nil {
			func() {
				md.observerMu.Lock()
				defer md.observerMu.Unlock()
				// we could've been canceled by a shutdown so look this up
				// again before closing and deleting.
				if updateChan, ok := md.observers[id]; ok {
					close(updateChan)
					delete(md.observers, id)
				}
			}()
		}
		return err
	})
	if err != nil {
		c = nil
	}

	return c, err
}