// XZSort sorts zset.
15687
func (db *DB) XZSort(key []byte, offset int, size int, alpha bool, desc bool, sortBy []byte, sortGet [][]byte) ([][]byte, error) {
	values, err := db.ZRangeByLex(key, nil, nil, store.RangeClose, 0, -1)
	if err != nil {
		return nil, err
	}

	return db.xsort(values, offset, size, alpha, desc, sortBy, sortGet)
}
873172
func (s *Sample) Sort() *Sample {
	if s.Sorted || sort.Float64sAreSorted(s.Xs) {
		// All set
	} else if s.Weights == nil {
		sort.Float64s(s.Xs)
	} else {
		sort.Sort(&sampleSorter{s.Xs, s.Weights})
	}
	s.Sorted = true
	return s
}
384138
func (f *FieldSetType) SortAll(sortList ...string) *FieldSetType {
	elem := f.fields
	size := len(elem)
	f.fields = make([]fields.FieldInterface, size)
	var sortSlice []string
	if len(sortList) == 1 {
		sortSlice = strings.Split(sortList[0], ",")
	} else {
		sortSlice = sortList
	}
	for k, fieldName := range sortSlice {
		if oldIndex, ok := f.fieldMap[fieldName]; ok {
			f.fields[k] = elem[oldIndex]
			f.fieldMap[fieldName] = k
		}
	}
	return f
}
540292
func clz32(x uint32) uint8 {
	var n uint8

	if x >= (1 << 16) {
		if x >= (1 << 24) {
			if x >= (1 << 28) {
				n = 28
			} else {
				n = 24
			}
		} else {
			if x >= (1 << 20) {
				n = 20
			} else {
				n = 16
			}
		}
	} else {
		if x >= (1 << 8) {
			if x >= (1 << 12) {
				n = 12
			} else {
				n = 8
			}
		} else {
			if x >= (1 << 4) {
				n = 4
			} else {
				n = 0
			}
		}
	}
	return clzLookup[x>>n] - n
}
150217
func (l sortEntries) Sort() {
	x := len(l)
	if x > 16 {
		sort.Sort(l)
	} else if len(l) > 1 {
		l.qSort()
	}
}
935821
func insertionSort_func(data lessSwap, a, b int) {
	for i := a + 1; i < b; i++ {
		for j := i; j > a && data.Less(j, j-1); j-- {
			data.Swap(j, j-1)
		}
	}
}
1221699
func (db *DB) ZRangeByScore(key []byte, min int64, max int64,
	offset int, count int) ([]ScorePair, error) {
	return db.ZRangeByScoreGeneric(key, min, max, offset, count, false)
}
454722
func (table *SimpleTable) Sort(columnIndex int) {
	sort.Sort(sortingSlice{
		column: columnIndex,
		slice:  &table.rows,
	})
}
758812
func (a azMachineFilterSort) FilterZones(cons constraints.Value) azMachineFilterSort {
	if !cons.HasZones() {
		return a
	}

	logger.Debugf("applying availability zone constraints: %s", strings.Join(*cons.Zones, ", "))
	filtered := a[:0]
	for _, azm := range a {
		for _, zone := range *cons.Zones {
			if azm.ZoneName == zone {
				filtered = append(filtered, azm)
				break
			}
		}
	}
	return filtered
}
624608
func (c *syncClient) Zrangebyscore(arg0 string, arg1 float64, arg2 float64) (result [][]byte, err Error) {
	arg0bytes := []byte(arg0)
	arg1bytes := []byte(fmt.Sprintf("%e", arg1))
	arg2bytes := []byte(fmt.Sprintf("%e", arg2))

	var resp Response
	resp, err = c.conn.ServiceRequest(&ZRANGEBYSCORE, [][]byte{arg0bytes, arg1bytes, arg2bytes})
	if err == nil {
		result = resp.GetMultiBulkData()
	}
	return result, err

}
447715
func Zipit(source, target, prefix string) error {
	// Thanks to Svett Ralchev
	// http://blog.ralch.com/tutorial/golang-working-with-zip/

	zipfile, err := os.Create(target)
	if err != nil {
		return err
	}
	defer zipfile.Close()

	if prefix != "" {
		_, err = io.WriteString(zipfile, prefix)
		if err != nil {
			return err
		}
	}

	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if path == source {
			return nil
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}
		header.Name, err = filepath.Rel(source, path)
		if err != nil {
			return err
		}

		header.Name = filepath.ToSlash(header.Name)

		if info.IsDir() {
			header.Name += "/"
			header.SetMode(0755)
		} else {
			header.Method = zip.Deflate
			header.SetMode(0744)
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()

		_, err = io.Copy(writer, file)
		return err
	})

	return err
}
766084
func (l _List_Map_Set_I32_Map_I32_Set_List_Map_Insanity_String_Zapper) MarshalLogArray(enc zapcore.ArrayEncoder) (err error) {
	for _, v := range l {
		err = multierr.Append(err, enc.AppendArray((_Map_Set_I32_Map_I32_Set_List_Map_Insanity_String_Zapper)(v)))
	}
	return err
}
145811
func IntroSort(data sort.Interface) {
	if data.Len() <= 1 {
		return
	}
	newListIntroSorter(data).Sort(0, data.Len())
}
718954
func (db *RedisDB) SortedSet(k string) (map[string]float64, error) {
	db.master.Lock()
	defer db.master.Unlock()
	if !db.exists(k) {
		return nil, ErrKeyNotFound
	}
	if db.t(k) != "zset" {
		return nil, ErrWrongType
	}
	return db.sortedSet(k), nil
}
172189
func HeapSort(stuff Sortable) {
	buildHeap(stuff)
	for i := stuff.Len() - 1; i > 0; i-- {
		stuff.Swap(0, i) // put max at end
		shuffleDown(stuff, 0, i)
	}
}
819364
func (s *GeoDistanceSort) NestedSort(nestedSort *NestedSort) *GeoDistanceSort {
	s.nestedSort = nestedSort
	return s
}
456656
func ParseTxns(txs []exptypes.MempoolTx, params *chaincfg.Params, lastBlock *BlockID) *exptypes.MempoolInfo {
	// The txs slice needs to be sorted by time, but we do not want to modify
	// the slice outside of this function and we do not want to waste time
	// copying it if it is already sorted. So, make a copy and sort only if it
	// is not already sorted.
	if !sort.SliceIsSorted(txs, func(i, j int) bool {
		return txs[i].Time > txs[j].Time
	}) {
		log.Debug("The transactions slice was not sorted by time. Sorting it now.")
		// Copy the input slice to avoid side effects.
		txs0 := txs
		txs = make([]exptypes.MempoolTx, len(txs0))
		copy(txs, txs0)
		sort.Sort(exptypes.MPTxsByTime(txs))
	}

	// Get the NumLatestMempoolTxns latest transactions in mempool.
	var latest []exptypes.MempoolTx
	if len(txs) > NumLatestMempoolTxns {
		latest = txs[:NumLatestMempoolTxns]
	} else {
		latest = txs
	}

	// Initialize with make to ensure they marshal to JSON as [] if empty.
	tickets := make([]exptypes.MempoolTx, 0)
	votes := make([]exptypes.MempoolTx, 0)
	revs := make([]exptypes.MempoolTx, 0)
	regular := make([]exptypes.MempoolTx, 0)

	// Transaction inventory.
	invRegular := make(map[string]struct{})
	invStake := make(map[string]struct{})

	blockhash := lastBlock.Hash.String()
	votingInfo := exptypes.NewVotingInfo(params.TicketsPerBlock)

	// Reduction variables.
	var latestTime int64
	var totalOut, regularTotal, ticketTotal, voteTotal, revTotal dcrutil.Amount
	var likelyMineable bool
	var likelyTotal dcrutil.Amount
	var totalSize, likelySize int32
	var numLikely int

	// Initialize the BlockValidatorIndex, a map.
	ticketSpendInds := make(exptypes.BlockValidatorIndex)

	for _, tx := range txs {
		likelyMineable = true
		out, _ := dcrutil.NewAmount(tx.TotalOut) // 0 for invalid amounts
		switch tx.Type {
		case "Ticket":
			if _, found := invStake[tx.Hash]; found {
				continue
			}
			ticketTotal += out
			invStake[tx.Hash] = struct{}{}
			tickets = append(tickets, tx)
		case "Vote":
			if _, found := invStake[tx.Hash]; found {
				continue
			}
			invStake[tx.Hash] = struct{}{}
			votes = append(votes, tx)

			if tx.VoteInfo == nil {
				log.Errorf("Missing vote information for %v!", tx)
				continue
			}
			// Assign an index to this vote that is unique to the spent ticket +
			// validated block.
			tx.VoteInfo.SetTicketIndex(ticketSpendInds)
			// Determine if this vote is (in)validating the previous block.
			tx.VoteInfo.ForLastBlock = tx.VoteInfo.VotesOnBlock(blockhash)
			// Update tally if this is for the previous block, the ticket has not
			// yet been spent. Do not attempt to decide block validity.
			if tx.VoteInfo.ForLastBlock && !votingInfo.VotedTickets[tx.VoteInfo.TicketSpent] {
				votingInfo.VotedTickets[tx.VoteInfo.TicketSpent] = true
				votingInfo.TicketsVoted++
				voteTotal += out
				votingInfo.Tally(tx.VoteInfo)
			} else {
				likelyMineable = false
			}
		case "Revocation":
			if _, found := invStake[tx.Hash]; found {
				continue
			}
			revTotal += out
			invStake[tx.Hash] = struct{}{}
			revs = append(revs, tx)
		default:
			if _, found := invRegular[tx.Hash]; found {
				continue
			}
			regularTotal += out
			invRegular[tx.Hash] = struct{}{}
			regular = append(regular, tx)
		}

		// Update mempool totals
		if likelyMineable {
			likelyTotal += out
			likelySize += tx.Size
			numLikely++
		}
		totalOut += out
		totalSize += tx.Size

		if latestTime < tx.Time {
			latestTime = tx.Time
		}
	}

	sort.Sort(exptypes.MPTxsByHeight(votes))
	formattedSize := humanize.Bytes(uint64(totalSize))

	// Store mempool data for template rendering
	mpInfo := exptypes.MempoolInfo{
		MempoolShort: exptypes.MempoolShort{
			LastBlockHeight:    lastBlock.Height,
			LastBlockHash:      blockhash,
			LastBlockTime:      lastBlock.Time,
			FormattedBlockTime: (exptypes.TimeDef{T: time.Unix(lastBlock.Time, 0)}).String(),
			Time:               latestTime,
			TotalOut:           totalOut.ToCoin(),
			TotalSize:          totalSize,
			NumTickets:         len(tickets),
			NumVotes:           len(votes),
			NumRegular:         len(regular),
			NumRevokes:         len(revs),
			NumAll:             len(txs),
			LikelyMineable: exptypes.LikelyMineable{
				Total:         likelyTotal.ToCoin(),
				Size:          likelySize,
				FormattedSize: humanize.Bytes(uint64(likelySize)),
				RegularTotal:  regularTotal.ToCoin(),
				TicketTotal:   ticketTotal.ToCoin(),
				VoteTotal:     voteTotal.ToCoin(),
				RevokeTotal:   revTotal.ToCoin(),
				Count:         numLikely,
			},
			LatestTransactions: latest,
			FormattedTotalSize: formattedSize,
			TicketIndexes:      ticketSpendInds,
			VotingInfo:         votingInfo,
			InvRegular:         invRegular,
			InvStake:           invStake,
		},
		Transactions: regular,
		Tickets:      tickets,
		Votes:        votes,
		Revocations:  revs,
	}

	return &mpInfo
}