// Page returns page information for a given page number.
// This is only safe for concurrent use when used by a writable transaction.
485599
func (tx *Tx) Page(id int) (*PageInfo, error) {
	if tx.db == nil {
		return nil, ErrTxClosed
	} else if pgid(id) >= tx.meta.pgid {
		return nil, nil
	}

	// Build the page info.
	p := tx.db.page(pgid(id))
	info := &PageInfo{
		ID:            id,
		Count:         int(p.count),
		OverflowCount: int(p.overflow),
	}

	// Determine the type (or if it's free).
	if tx.db.freelist.freed(pgid(id)) {
		info.Type = "free"
	} else {
		info.Type = p.typ()
	}

	return info, nil
}
1030845
func mainPage(w *rest.ResponseWriter, r *rest.Request) {
	noCache(w)
	http.ServeFile(
		w.ResponseWriter,
		r.Request,
		staticRoot()+"/index.html")
}
1179382
func (c *PageCollections) getPageNew(context page.Page, ref string) (page.Page, error) {
	var anError error

	ref = strings.ToLower(ref)

	// Absolute (content root relative) reference.
	if strings.HasPrefix(ref, "/") {
		p, err := c.getFromCache(ref)
		if err == nil && p != nil {
			return p, nil
		}
		if err != nil {
			anError = err
		}

	} else if context != nil {
		// Try the page-relative path.
		ppath := path.Join("/", strings.ToLower(context.SectionsPath()), ref)
		p, err := c.getFromCache(ppath)
		if err == nil && p != nil {
			return p, nil
		}
		if err != nil {
			anError = err
		}
	}

	if !strings.HasPrefix(ref, "/") {
		// Many people will have "post/foo.md" in their content files.
		p, err := c.getFromCache("/" + ref)
		if err == nil && p != nil {
			if context != nil {
				// TODO(bep) remove this case and the message below when the storm has passed
				err := wrapErr(errors.New(`make non-relative ref/relref page reference(s) in page %q absolute, e.g. {{< ref "/blog/my-post.md" >}}`), context)
				helpers.DistinctWarnLog.Println(err)
			}
			return p, nil
		}
		if err != nil {
			anError = err
		}
	}

	// Last try.
	ref = strings.TrimPrefix(ref, "/")
	p, err := c.getFromCache(ref)
	if err != nil {
		anError = err
	}

	if p == nil && anError != nil {
		return nil, wrapErr(errors.Wrap(anError, "failed to resolve ref"), context)
	}

	return p, nil
}
516607
func (p *provider) page(initialURL, token string, newObj func() interface{}, processObj func(interface{}) error) error {
	// track urls we've fetched to avoid cycles
	url := initialURL
	fetchedURLs := sets.NewString(url)
	for {
		// fetch and process
		obj := newObj()
		links, err := p.getJSON(url, token, obj)
		if err != nil {
			return err
		}
		if err := processObj(obj); err != nil {
			return err
		}

		// see if we need to page
		// https://developer.github.com/v3/#link-header
		url = links["next"]
		if len(url) == 0 {
			// no next URL, we're done paging
			break
		}
		if fetchedURLs.Has(url) {
			// break to avoid a loop
			break
		}
		// remember to avoid a loop
		fetchedURLs.Insert(url)
	}
	return nil
}
1308803
func (c *Client) Page(msg *Page) error {
	if msg.UserId == "" && msg.AnonymousId == "" {
		return errors.New("You must pass either an 'anonymousId' or 'userId'.")
	}

	msg.Type = "page"
	c.queue(msg)

	return nil
}
129360
func (s *IPServiceList) FirstPage() (*IPServiceList, error) {
	return s.getPage(s.Meta.FirstPageUri)
}
755452
func (c *IPMemberList) NextPage() (*IPMemberList, error) {
	if !c.HasNextPage() {
		return nil, Error{"No next page"}
	}

	return c.getPage(c.Meta.NextPageUri)
}
191758
func (p WeightedPages) Page() Page {
	if len(p) == 0 {
		panic("WeightedPages is empty")
	}

	first := p[0]

	// TODO(bep) fix tests
	if first.owner == nil {
		return nil
	}

	return first.owner.Page
}
500540
func (exp *explorerUI) AddressPage(w http.ResponseWriter, r *http.Request) {
	// AddressPageData is the data structure passed to the HTML template

	type AddressPageData struct {
		*CommonPageData
		Data         *dbtypes.AddressInfo
		CRLFDownload bool
		FiatBalance  *exchanges.Conversion
	}

	// Grab the URL query parameters
	address, txnType, limitN, offsetAddrOuts, err := parseAddressParams(r)
	if err != nil {
		exp.StatusPage(w, defaultErrorCode, err.Error(), address, ExpStatusError)
		return
	}

	// Validate the address.
	addr, addrType, addrErr := txhelpers.AddressValidation(address, exp.ChainParams)
	isZeroAddress := addrErr == txhelpers.AddressErrorZeroAddress
	if addrErr != nil && !isZeroAddress {
		var status expStatus
		var message string
		code := defaultErrorCode
		switch addrErr {
		case txhelpers.AddressErrorDecodeFailed, txhelpers.AddressErrorUnknown:
			status = ExpStatusError
			message = "Unexpected issue validating this address."
		case txhelpers.AddressErrorWrongNet:
			status = ExpStatusWrongNetwork
			message = fmt.Sprintf("The address %v is valid on %s, not %s.",
				addr, addr.Net().Name, exp.NetName)
			code = wrongNetwork
		default:
			status = ExpStatusError
			message = "Unknown error."
		}

		exp.StatusPage(w, code, message, address, status)
		return
	}

	// Handle valid but unsupported address types.
	switch addrType {
	case txhelpers.AddressTypeP2PKH, txhelpers.AddressTypeP2SH:
		// All good.
	case txhelpers.AddressTypeP2PK:
		message := "Looks like you are searching for an address of type P2PK."
		exp.StatusPage(w, defaultErrorCode, message, address, ExpStatusP2PKAddress)
		return
	default:
		message := "Unsupported address type."
		exp.StatusPage(w, defaultErrorCode, message, address, ExpStatusNotSupported)
		return
	}

	// Retrieve address information from the DB and/or RPC.
	var addrData *dbtypes.AddressInfo
	if isZeroAddress {
		// For the zero address (e.g. DsQxuVRvS4eaJ42dhQEsCXauMWjvopWgrVg),
		// short-circuit any queries.
		addrData = &dbtypes.AddressInfo{
			Address:         address,
			Net:             addr.Net().Name,
			IsDummyAddress:  true,
			Balance:         new(dbtypes.AddressBalance),
			UnconfirmedTxns: new(dbtypes.AddressTransactions),
		}
	} else {
		addrData, err = exp.AddressListData(address, txnType, limitN, offsetAddrOuts)
		if exp.timeoutErrorPage(w, err, "TicketsPriceByHeight") {
			return
		} else if err != nil {
			exp.StatusPage(w, defaultErrorCode, err.Error(), address, ExpStatusError)
			return
		}
	}

	// Set page parameters.
	addrData.IsDummyAddress = isZeroAddress // may be redundant
	addrData.Path = r.URL.Path

	// If exchange monitoring is active, prepare a fiat balance conversion
	conversion := exp.xcBot.Conversion(dcrutil.Amount(addrData.Balance.TotalUnspent).ToCoin())

	// For Windows clients only, link to downloads with CRLF (\r\n) line
	// endings.
	UseCRLF := strings.Contains(r.UserAgent(), "Windows")

	// Execute the HTML template.
	pageData := AddressPageData{
		CommonPageData: exp.commonData(r),
		Data:           addrData,
		CRLFDownload:   UseCRLF,
		FiatBalance:    conversion,
	}
	str, err := exp.templates.execTemplateToString("address", pageData)
	if err != nil {
		log.Errorf("Template execute failure: %v", err)
		exp.StatusPage(w, defaultErrorCode, defaultErrorMessage, "", ExpStatusError)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	w.Header().Set("Turbolinks-Location", r.URL.RequestURI())
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, str)
}
459579
func (wp WeightedPages) Pages() Pages {
	pages := make(Pages, len(wp))
	for i := range wp {
		pages[i] = wp[i].Page
	}
	return pages
}
693098
func (n *node) write(p *page) {
	// Initialize page.
	if n.isLeaf {
		p.flags |= leafPageFlag
	} else {
		p.flags |= branchPageFlag
	}

	if len(n.inodes) >= 0xFFFF {
		panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id))
	}
	p.count = uint16(len(n.inodes))

	// Stop here if there are no items to write.
	if p.count == 0 {
		return
	}

	// Loop over each item and write it to the page.
	b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):]
	for i, item := range n.inodes {
		_assert(len(item.key) > 0, "write: zero-length inode key")

		// Write the page element.
		if n.isLeaf {
			elem := p.leafPageElement(uint16(i))
			elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
			elem.flags = item.flags
			elem.ksize = uint32(len(item.key))
			elem.vsize = uint32(len(item.value))
		} else {
			elem := p.branchPageElement(uint16(i))
			elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
			elem.ksize = uint32(len(item.key))
			elem.pgid = item.pgid
			_assert(elem.pgid != p.id, "write: circular dependency occurred")
		}

		// If the length of key+value is larger than the max allocation size
		// then we need to reallocate the byte array pointer.
		//
		// See: https://github.com/boltdb/bolt/pull/335
		klen, vlen := len(item.key), len(item.value)
		if len(b) < klen+vlen {
			b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:]
		}

		// Write data for the element to the end of the page.
		copy(b[0:], item.key)
		b = b[klen:]
		copy(b[0:], item.value)
		b = b[vlen:]
	}

	// DEBUG ONLY: n.dump()
}
511703
func (m *MWApi) Read(pageName string) (*Page, error) {
	query := map[string]string{
		"action":  "query",
		"prop":    "revisions",
		"titles":  pageName,
		"rvlimit": "1",
		"rvprop":  "content|timestamp|user|comment",
	}
	body, err := m.API(query)
	if err != nil {
		return nil, err
	}

	var response Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		return nil, err
	}

	if len(response.Query.Pages) != 1 {
		return nil, errors.New("received unexpected number of pages")
	}

	// we use a hacky way of extracting the map's lone value
	var page *Page
	for _, pg := range response.Query.Pages {
		page = &pg
	}
	return page, nil
}
215754
func (l Links) PreviousPage() (int, error) {
	if l.Previous == "" {
		return 0, nil
	}
	return pageForURL(l.Previous)
}
745954
func (self *SimpleIdComponent) Page(pb PBundle, path []string, trailingSlash bool) ComponentResult {

	//allow singular to be used as synonym for plural
	if len(path) == 0 {
		return ComponentResult{
			Path:   "/" + filepath.Join(self.UrlPrefix(), "index.html"),
			Status: http.StatusOK,
		}
	}

	if (len(path) == 1 && path[0] == "new") || (len(path) == 1 && path[0] == "new.html") {
		if self.newcheck != nil {
			ok, err := self.newcheck(pb)
			if err != nil {
				return ComponentResult{
					Status:  http.StatusInternalServerError,
					Message: err.Error(),
				}
			}
			if !ok {
				return ComponentResult{
					Message: "you lose",
					Status:  http.StatusUnauthorized,
				}
			}
		}
		return ComponentResult{
			Path:   "/" + filepath.Join(self.UrlPrefix(), "new.html"),
			Status: http.StatusOK,
		}
	}

	if (len(path) == 1 && path[0] == "index") || (len(path) == 1 && path[0] == "index.html") {
		return ComponentResult{
			Path:   "/" + filepath.Join(self.UrlPrefix(), "index.html"),
			Status: http.StatusOK,
		}
	}

	// parse the id in the URL
	rawId := path[0]
	id, err := strconv.ParseInt(rawId, 10, 64)
	if err != nil {
		//handle the case of /<singular>/new.js
		return ComponentResult{
			Status:           CONTINUE,
			ContinueAt:       self.singular,
			ContinueConsumed: 1,
		}
	}
	if self.exists != nil {
		ok, err := self.exists(pb, id)
		if err != nil {
			return ComponentResult{
				Status:  http.StatusInternalServerError,
				Message: err.Error(),
			}
		}
		if !ok {
			return ComponentResult{
				Status:  http.StatusNotFound,
				Message: fmt.Sprintf("could not find %d", id),
			}
		}
	}

	// show view.html for /foo/1 or /foo/1/
	if len(path) == 1 {
		if self.viewedit != nil {
			ok, err := self.viewedit(pb, id, true)
			if err != nil {
				return ComponentResult{
					Status:  http.StatusInternalServerError,
					Message: err.Error(),
				}
			}
			if !ok {
				return ComponentResult{
					Message: "you lose",
					Status:  http.StatusUnauthorized,
				}
			}
		}
		return ComponentResult{
			Path:   "/" + filepath.Join(self.UrlPrefix(), "view.html"),
			Status: http.StatusOK,
		}
	}

	// see if it's a verb we understand
	if len(path) == 2 {
		verb := path[1]
		switch verb {
		case "edit", "edit.html", "view", "view.html":
			if !strings.HasSuffix(verb, ".html") {
				verb = verb + ".html"
			}
			if self.viewedit != nil {
				ok, err := self.viewedit(pb, id, verb == "view.html")
				if err != nil {
					return ComponentResult{
						Status:  http.StatusInternalServerError,
						Message: err.Error(),
					}
				}
				if !ok {
					return ComponentResult{
						Message: "you lose",
						Status:  http.StatusUnauthorized,
					}
				}
				return ComponentResult{
					Path:   "/" + filepath.Join(self.UrlPrefix(), verb),
					Status: http.StatusOK,
				}

			}
		default:
			return ComponentResult{
				Status:           CONTINUE,
				ContinueAt:       self.UrlPrefix(),
				ContinueConsumed: 2,
			}
		}
	}

	//we don't accept any more parts to the URL
	return ComponentResult{
		Status:  http.StatusBadRequest,
		Message: fmt.Sprintf("Unacceptable url for %s", self.singular),
	}
}
1104423
func (b *SelectStmt) Paginate(page, perPage uint64) *SelectStmt {
	b.Limit(perPage)
	b.Offset((page - 1) * perPage)
	return b
}
332216
func (p *Paginater) Pages() []*Page {
	if p.numPages == 0 {
		return []*Page{}
	} else if p.numPages == 1 && p.TotalPages() == 1 {
		// Only show current page.
		return []*Page{{1, true}}
	}

	// Total page number is less or equal.
	if p.TotalPages() <= p.numPages {
		pages := make([]*Page, p.TotalPages())
		for i := range pages {
			pages[i] = &Page{i + 1, i+1 == p.current}
		}
		return pages
	}

	numPages := p.numPages
	maxIdx := numPages - 1
	offsetIdx := 0
	hasMoreNext := false

	// Check more previous and next pages.
	previousNum := getMiddleIdx(p.numPages) - 1
	if previousNum > p.current-1 {
		previousNum -= previousNum - (p.current - 1)
	}
	nextNum := p.numPages - previousNum - 1
	if p.current+nextNum > p.TotalPages() {
		delta := nextNum - (p.TotalPages() - p.current)
		nextNum -= delta
		previousNum += delta
	}

	offsetVal := p.current - previousNum
	if offsetVal > 1 {
		numPages++
		maxIdx++
		offsetIdx = 1
	}

	if p.current+nextNum < p.TotalPages() {
		numPages++
		hasMoreNext = true
	}

	pages := make([]*Page, numPages)

	// There are more previous pages.
	if offsetIdx == 1 {
		pages[0] = &Page{-1, false}
	}
	// There are more next pages.
	if hasMoreNext {
		pages[len(pages)-1] = &Page{-1, false}
	}

	// Check previous pages.
	for i := 0; i < previousNum; i++ {
		pages[offsetIdx+i] = &Page{i + offsetVal, false}
	}

	pages[offsetIdx+previousNum] = &Page{p.current, true}

	// Check next pages.
	for i := 1; i <= nextNum; i++ {
		pages[offsetIdx+previousNum+i] = &Page{p.current + i, false}
	}

	return pages
}
682150
func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
	const bytesPerLineN = 16

	// Read page into buffer.
	buf := make([]byte, pageSize)
	addr := pageID * pageSize
	if n, err := r.ReadAt(buf, int64(addr)); err != nil {
		return err
	} else if n != pageSize {
		return io.ErrUnexpectedEOF
	}

	// Write out to writer in 16-byte lines.
	var prev []byte
	var skipped bool
	for offset := 0; offset < pageSize; offset += bytesPerLineN {
		// Retrieve current 16-byte line.
		line := buf[offset : offset+bytesPerLineN]
		isLastLine := (offset == (pageSize - bytesPerLineN))

		// If it's the same as the previous line then print a skip.
		if bytes.Equal(line, prev) && !isLastLine {
			if !skipped {
				fmt.Fprintf(w, "%07x *\n", addr+offset)
				skipped = true
			}
		} else {
			// Print line as hexadecimal in 2-byte groups.
			fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
				line[0:2], line[2:4], line[4:6], line[6:8],
				line[8:10], line[10:12], line[12:14], line[14:16],
			)

			skipped = false
		}

		// Save the previous line.
		prev = line
	}
	fmt.Fprint(w, "\n")

	return nil
}