// FindFirstItem returns the order of the target workitem
164243
func (r *GormWorkItemRepository) FindFirstItem(ctx context.Context, spaceID uuid.UUID, id uuid.UUID) (*float64, error) {
	res := WorkItemStorage{}
	tx := r.db.Model(WorkItemStorage{}).Where("id=? and space_id=?", id, spaceID).First(&res)
	if tx.RecordNotFound() {
		return nil, errors.NewNotFoundError("work item", id.String())
	}
	if tx.Error != nil {
		return nil, errors.NewInternalError(ctx, tx.Error)
	}
	return &res.ExecutionOrder, nil
}
390152
func (s *SkipList) SeekToFirst() Iterator {
	if s.length == 0 {
		return nil
	}

	current := s.header.next()

	return &iter{
		current: current,
		key:     current.key,
		list:    s,
		value:   current.value,
	}
}
1065289
func (s Selector) MatchFirst(n *html.Node) *html.Node {
	if s.Match(n) {
		return n
	}

	for c := n.FirstChild; c != nil; c = c.NextSibling {
		m := s.MatchFirst(c)
		if m != nil {
			return m
		}
	}
	return nil
}
522800
func (q *LinkedBlockingDeque) unlinkFirst() interface{} {
	// assert lock.isHeldByCurrentThread();
	f := q.first
	if f == nil {
		return nil
	}
	n := f.next
	item := f.item
	f.item = nil
	f.next = f //help GC
	q.first = n
	if n == nil {
		q.last = nil
	} else {
		n.prev = nil
	}
	q.count = q.count - 1
	q.notFull.Signal()
	return item
}
696113
func (s *ScrollService) bodyFirst() (interface{}, error) {
	var err error
	var body interface{}

	if s.body != nil {
		body = s.body
	} else {
		// Use _doc sort by default if none is specified
		if !s.ss.hasSort() {
			// Use efficient sorting when no user-defined query/body is specified
			s.ss = s.ss.SortBy(SortByDoc{})
		}

		// Body from search source
		body, err = s.ss.Source()
		if err != nil {
			return nil, err
		}
	}

	return body, nil
}
242277
func (trs *TaskResultSet) FirstValue() interface{} {
	for _, result := range trs.results {
		if result.Value != nil {
			return result.Value
		}
	}
	return nil
}
50757
func (c *Cache) GetItem(key string) (it Item, ok bool) {
	c.Lock()
	defer c.Unlock()
	if it, ok := c.getItemPtr(key); ok {
		return *it, true
	}
	return
}
40551
func (pq *PriorityQueue) getNextItem() (*PriorityItem, error) {
	// If the current priority level is empty.
	if pq.levels[pq.curLevel].length() == 0 {
		// Set starting value for curLevel.
		pq.resetCurrentLevel()

		// Try to get the next priority level.
		for i := 0; i <= 255; i++ {
			if (pq.cmpAsc(uint8(i)) || pq.cmpDesc(uint8(i))) && pq.levels[uint8(i)].length() > 0 {
				pq.curLevel = uint8(i)
			}
		}

		// If still empty, return queue empty error.
		if pq.levels[pq.curLevel].length() == 0 {
			return nil, ErrEmpty
		}
	}

	// Try to get the next item in the current priority level.
	return pq.getItemByPriorityID(pq.curLevel, pq.levels[pq.curLevel].head+1)
}
309425
func (pq *PriorityQueue) findOffset(offset uint64) (*PriorityItem, error) {
	var length uint64
	var curLevel uint8 = pq.curLevel
	var newLevel int

	// Handle newLevel initialization for descending order.
	if pq.order == DESC {
		newLevel = 255
	}

	// For condition expression.
	condExpr := func(level int) bool {
		if pq.order == ASC {
			return level <= 255
		}
		return level >= 0
	}

	// For loop expression.
	loopExpr := func(level *int) {
		if pq.order == ASC {
			*level++
		} else if pq.order == DESC {
			*level--
		}
	}

	// Level comparison.
	cmpLevels := func(newLevel, curLevel uint8) bool {
		if pq.order == ASC {
			return newLevel >= curLevel
		}
		return newLevel <= curLevel
	}

	// Loop through the priority levels.
	for ; condExpr(newLevel); loopExpr(&newLevel) {
		// If this level is lower than the current level based on ordering and contains items.
		if cmpLevels(uint8(newLevel), curLevel) && pq.levels[uint8(newLevel)].length() > 0 {
			curLevel = uint8(newLevel)
			newLength := pq.levels[curLevel].length()

			// If the offset is within the current priority level.
			if length+newLength >= offset+1 {
				return pq.getItemByPriorityID(curLevel, offset-length+1)
			}

			length += newLength
		}
	}

	return nil, ErrOutOfBounds
}
1172179
func (ec *EstablishingController) processNextWorkItem() bool {
	key, quit := ec.queue.Get()
	if quit {
		return false
	}
	defer ec.queue.Done(key)

	err := ec.syncFn(key.(string))
	if err == nil {
		ec.queue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
	ec.queue.AddRateLimited(key)

	return true
}
404634
func (ti *TagIterator) First(ctx context.Context, items *[]Tag) bool {
	if ti.err != nil {
		return false
	}
	ti.err = ti.fetch(ctx, ti.Paging.First)
	if ti.err != nil {
		return false
	}
	*items = ti.Items
	return true
}
1211843
func (t *PrimaryTree) SeekFirst() (e *PrimaryEnumerator, err error) {
	q := t.first
	if q == nil {
		return nil, io.EOF
	}

	return btEPool1.get(nil, true, 0, q.d[0].k, q, t, atomic.LoadUint64(&t.ver)), nil
}
1331167
func getWorkItemsOfLinks(ctx context.Context, appl application.Application, req *http.Request, linksDataArr []*app.WorkItemLinkData) ([]*app.WorkItem, error) {
	// Build our "set" of distinct work item IDs
	idMap := map[uuid.UUID]struct{}{}
	idArr := []uuid.UUID{}
	for _, linkData := range linksDataArr {
		src := linkData.Relationships.Source.Data.ID
		tgt := linkData.Relationships.Target.Data.ID
		if _, ok := idMap[src]; !ok {
			idMap[src] = struct{}{}
			idArr = append(idArr, src)
		}
		if _, ok := idMap[tgt]; !ok {
			idMap[tgt] = struct{}{}
			idArr = append(idArr, tgt)
		}
	}

	// Fetch all work items specified in the array
	res := []*app.WorkItem{}
	for _, id := range idArr {
		wi, err := appl.WorkItems().LoadByID(ctx, id)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		wit, err := appl.WorkItemTypes().Load(ctx, wi.Type)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to load work item type: %s", wi.Type)
		}
		converted, err := ConvertWorkItem(req, *wit, *wi)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		res = append(res, converted)
	}
	return res, nil
}
631716
func getFirstChildEl(n *html.Node) *html.Node {
	c := n.FirstChild
	for c != nil && c.Type != html.ElementNode {
		c = c.NextSibling
	}
	return c
}
920653
func includeParentWorkItem(ctx context.Context, ancestors link.AncestorList, childLinks link.WorkItemLinkList) WorkItemConvertFunc {
	return func(request *http.Request, wi *workitem.WorkItem, wi2 *app.WorkItem) error {
		var parentID *uuid.UUID
		// If we have an ancestry we can lookup the parent in no time.
		if ancestors != nil && len(ancestors) != 0 {
			p := ancestors.GetParentOf(wi.ID)
			if p != nil {
				parentID = &p.ID
			}
		}
		// If no parent ID was found in the ancestor list, see if the child
		// link list contains information to use.
		if parentID == nil && childLinks != nil && len(childLinks) != 0 {
			p := childLinks.GetParentIDOf(wi.ID, link.SystemWorkItemLinkTypeParentChildID)
			if p != uuid.Nil {
				parentID = &p
			}
		}
		if wi2.Relationships.Parent == nil {
			wi2.Relationships.Parent = &app.RelationKindUUID{}
		}
		if parentID != nil {
			if wi2.Relationships.Parent.Data == nil {
				wi2.Relationships.Parent.Data = &app.DataKindUUID{}
			}
			wi2.Relationships.Parent.Data.ID = *parentID
			wi2.Relationships.Parent.Data.Type = APIStringTypeWorkItem
		}
		return nil
	}
}
10865
func (r *GormWorkItemLinkRepository) ListWorkItemChildren(ctx context.Context, parentID uuid.UUID, start *int, limit *int) ([]workitem.WorkItem, int, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemlink", "children", "query"}, time.Now())
	where := fmt.Sprintf(`
	id in (
		SELECT target_id FROM %s
		WHERE source_id = $1 AND link_type_id = $2 AND deleted_at IS NULL
	)`, WorkItemLink{}.TableName())
	baseDB := r.db.Model(&workitem.WorkItemStorage{}).Where(where, parentID.String(), SystemWorkItemLinkTypeParentChildID.String())
	if start != nil {
		if *start < 0 {
			return nil, 0, errors.NewBadParameterError("start", *start)
		}
		baseDB = baseDB.Offset(*start)
	}
	if limit != nil {
		if *limit <= 0 {
			return nil, 0, errors.NewBadParameterError("limit", *limit)
		}
		baseDB = baseDB.Limit(*limit)
	}
	db := baseDB.Select("count(*) over () as cnt2 , *").Order("execution_order desc")
	// To sort by title do this:
	// db = db.Select("count(*) over () as cnt2 , *").Order(fmt.Sprintf("fields->>'%s'", workitem.SystemTitle))
	rows, err := db.Rows()
	defer closeable.Close(ctx, rows)
	if err != nil {
		return nil, 0, err
	}
	result := []workitem.WorkItemStorage{}

	columns, err := rows.Columns()
	if err != nil {
		return nil, 0, errors.NewInternalError(ctx, err)
	}

	var count int
	var ignore interface{}
	columnValues := make([]interface{}, len(columns))

	for index := range columnValues {
		columnValues[index] = &ignore
	}
	columnValues[0] = &count
	first := true

	for rows.Next() {
		value := workitem.WorkItemStorage{}
		db.ScanRows(rows, &value)

		if first {
			first = false
			if err = rows.Scan(columnValues...); err != nil {
				return nil, 0, errors.NewInternalError(ctx, err)
			}
		}
		result = append(result, value)
	}

	if first {
		// means 0 rows were returned from the first query (maybe because of
		// offset outside of total count), need to do a count(*) to find out
		// total
		db := baseDB.Select("count(*)")
		if db.Error != nil {
			return nil, 0, errs.WithStack(db.Error)
		}
		rows2, err := db.Rows()
		defer closeable.Close(ctx, rows2)
		if err != nil {
			return nil, 0, errs.WithStack(err)
		}
		rows2.Next() // count(*) will always return a row
		rows2.Scan(&count)
	}

	res := make([]workitem.WorkItem, len(result))
	for index, value := range result {
		wiType, err := r.workItemTypeRepo.Load(ctx, value.Type)
		if err != nil {
			return nil, 0, errors.NewInternalError(ctx, err)
		}
		modelWI, err := workitem.ConvertWorkItemStorageToModel(wiType, &value)
		if err != nil {
			return nil, 0, errors.NewInternalError(ctx, err)
		}
		res[index] = *modelWI
	}

	return res, count, nil
}
1286752
func (c *AggregationController) processNextWorkItem() bool {
	key, quit := c.queue.Get()
	defer c.queue.Done(key)
	if quit {
		return false
	}

	if aggregator.IsLocalAPIService(key.(string)) {
		// for local delegation targets that are aggregated once per second, log at
		// higher level to avoid flooding the log
		klog.V(5).Infof("OpenAPI AggregationController: Processing item %s", key)
	} else {
		klog.Infof("OpenAPI AggregationController: Processing item %s", key)
	}

	action, err := c.syncHandler(key.(string))
	if err == nil {
		c.queue.Forget(key)
	} else {
		utilruntime.HandleError(fmt.Errorf("loading OpenAPI spec for %q failed with: %v", key, err))
	}

	switch action {
	case syncRequeue:
		if aggregator.IsLocalAPIService(key.(string)) {
			klog.V(7).Infof("OpenAPI AggregationController: action for local item %s: Requeue after %s.", key, successfulUpdateDelayLocal)
			c.queue.AddAfter(key, successfulUpdateDelayLocal)
		} else {
			klog.V(7).Infof("OpenAPI AggregationController: action for item %s: Requeue.", key)
			c.queue.AddAfter(key, successfulUpdateDelay)
		}
	case syncRequeueRateLimited:
		klog.Infof("OpenAPI AggregationController: action for item %s: Rate Limited Requeue.", key)
		c.queue.AddRateLimited(key)
	case syncNothing:
		klog.Infof("OpenAPI AggregationController: action for item %s: Nothing (removed from the queue).", key)
	}

	return true
}