// AddOrder adds new order
493247
func (api *KrakenApi) AddOrder(pair string, direction string, orderType string, volume string, args map[string]string) (*AddOrderResponse, error) {
	params := url.Values{
		"pair":      {pair},
		"type":      {direction},
		"ordertype": {orderType},
		"volume":    {volume},
	}

	if value, ok := args["price"]; ok {
		params.Add("price", value)
	}
	if value, ok := args["price2"]; ok {
		params.Add("price2", value)
	}
	if value, ok := args["leverage"]; ok {
		params.Add("leverage", value)
	}
	if value, ok := args["oflags"]; ok {
		params.Add("oflags", value)
	}
	if value, ok := args["starttm"]; ok {
		params.Add("starttm", value)
	}
	if value, ok := args["expiretm"]; ok {
		params.Add("expiretm", value)
	}
	if value, ok := args["validate"]; ok {
		params.Add("validate", value)
	}
	if value, ok := args["close_order_type"]; ok {
		params.Add("close[ordertype]", value)
	}
	if value, ok := args["close_price"]; ok {
		params.Add("close[price]", value)
	}
	if value, ok := args["close_price2"]; ok {
		params.Add("close[price2]", value)
	}
	if value, ok := args["trading_agreement"]; ok {
		params.Add("trading_agreement", value)
	}
	if value, ok := args["userref"]; ok {
		params.Add("userref", value)
	}
	resp, err := api.queryPrivate("AddOrder", params, &AddOrderResponse{})

	if err != nil {
		return nil, err
	}

	return resp.(*AddOrderResponse), nil
}
266546
func (s *ListTrainingJobsInput) SetSortOrder(v string) *ListTrainingJobsInput {
	s.SortOrder = &v
	return s
}
1100039
func (jb *join) Reorder(order int) {
	jb.Left.Reorder(order)
	jb.leftOrder = jb.Left.Order()
	jb.Right.Reorder(jb.leftOrder)
	jb.order = jb.Right.Order() + 1
}
1038620
func (s *ListBuildsForProjectInput) SetSortOrder(v string) *ListBuildsForProjectInput {
	s.SortOrder = &v
	return s
}
957036
func (sa *StorageAuthority) CountOrders(_ context.Context, _ int64, _, _ time.Time) (int, error) {
	return 0, nil
}
1324512
func (s *DescribeMLModelsInput) SetSortOrder(v string) *DescribeMLModelsInput {
	s.SortOrder = &v
	return s
}
528313
func (p *MemPostings) EnsureOrder() {
	p.mtx.Lock()
	defer p.mtx.Unlock()

	if p.ordered {
		return
	}

	n := runtime.GOMAXPROCS(0)
	workc := make(chan []uint64)

	var wg sync.WaitGroup
	wg.Add(n)

	for i := 0; i < n; i++ {
		go func() {
			for l := range workc {
				sort.Slice(l, func(i, j int) bool { return l[i] < l[j] })
			}
			wg.Done()
		}()
	}

	for _, e := range p.m {
		for _, l := range e {
			workc <- l
		}
	}
	close(workc)
	wg.Wait()

	p.ordered = true
}
802806
func NewOrder(stmt *rel.SqlSelect) *Order {
	return &Order{Stmt: stmt, PlanBase: NewPlanBase(false)}
}
280978
func (s ScriptSort) Order(ascending bool) ScriptSort {
	s.ascending = ascending
	return s
}
265081
func (c *Client) AuthorizeOrder(orderID string, amount *Amount) (*Authorization, error) {
	type authRequest struct {
		Amount *Amount `json:"amount"`
	}

	auth := &Authorization{}

	req, err := c.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v2/checkout/orders/"+orderID+"/authorize"), authRequest{Amount: amount})
	if err != nil {
		return auth, err
	}

	if err = c.SendWithAuth(req, auth); err != nil {
		return auth, err
	}

	return auth, nil
}
204397
func (s *OrderByElement) SetSortOrder(v string) *OrderByElement {
	s.SortOrder = &v
	return s
}
101631
func (s GeoDistanceSort) Order(ascending bool) GeoDistanceSort {
	s.ascending = ascending
	return s
}
695240
func NewDeleteOrder(ctx *middleware.Context, handler DeleteOrderHandler) *DeleteOrder {
	return &DeleteOrder{Context: ctx, Handler: handler}
}
63592
func NewGetOrder(ctx *middleware.Context, handler GetOrderHandler) *GetOrder {
	return &GetOrder{Context: ctx, Handler: handler}
}
1010889
func (client *Client) CreateOrder(args *CreateOrderArgs) (resp CreateOrderResponse, err error) {
	response := CreateOrderResponse{}
	err = client.Invoke("CreateOrder", args, &response)
	return response, err
}
96853
func (ra *RegistrationAuthorityImpl) NewOrder(ctx context.Context, req *rapb.NewOrderRequest) (*corepb.Order, error) {
	order := &corepb.Order{
		RegistrationID: req.RegistrationID,
		Names:          core.UniqueLowerNames(req.Names),
	}

	// Validate that our policy allows issuing for each of the names in the order
	for _, name := range order.Names {
		id := core.AcmeIdentifier{Value: name, Type: core.IdentifierDNS}
		if err := ra.PA.WillingToIssueWildcard(id); err != nil {
			return nil, err
		}
	}

	if err := wildcardOverlap(order.Names); err != nil {
		return nil, err
	}

	// See if there is an existing unexpired pending (or ready) order that can be reused
	// for this account
	useV2Authzs := features.Enabled(features.NewAuthorizationSchema)
	existingOrder, err := ra.SA.GetOrderForNames(ctx, &sapb.GetOrderForNamesRequest{
		AcctID:              order.RegistrationID,
		Names:               order.Names,
		UseV2Authorizations: &useV2Authzs,
	})
	// If there was an error and it wasn't an acceptable "NotFound" error, return
	// immediately
	if err != nil && !berrors.Is(err, berrors.NotFound) {
		return nil, err
	}
	// If there was an order, return it
	if existingOrder != nil {
		return existingOrder, nil
	}
	// Otherwise we were unable to find an order to reuse, continue creating a new
	// order

	// Check if there is rate limit space for a new order within the current window
	if err := ra.checkNewOrdersPerAccountLimit(ctx, *order.RegistrationID); err != nil {
		return nil, err
	}

	if features.Enabled(features.EarlyOrderRateLimit) {
		// Check if there is rate limit space for issuing a certificate for the new
		// order's names. If there isn't then it doesn't make sense to allow creating
		// an order - it will just fail when finalization checks the same limits.
		if err := ra.checkLimits(ctx, order.Names, *order.RegistrationID); err != nil {
			return nil, err
		}
	}

	// An order's lifetime is effectively bound by the shortest remaining lifetime
	// of its associated authorizations. For that reason it would be Uncool if
	// `sa.GetAuthorizations` returned an authorization that was very close to
	// expiry. The resulting pending order that references it would itself end up
	// expiring very soon.
	// To prevent this we only return authorizations that are at least 1 day away
	// from expiring.
	authzExpiryCutoff := ra.clk.Now().AddDate(0, 0, 1).UnixNano()

	// We do not want any legacy V1 API authorizations not associated with an
	// order to be returned from the SA so we set requireV2Authzs to true
	requireV2Authzs := true
	existingAuthz, err := ra.SA.GetAuthorizations(ctx, &sapb.GetAuthorizationsRequest{
		RegistrationID:  order.RegistrationID,
		Now:             &authzExpiryCutoff,
		Domains:         order.Names,
		RequireV2Authzs: &requireV2Authzs,
	})
	if err != nil {
		return nil, err
	}

	// Collect up the authorizations we found into a map keyed by the domains the
	// authorizations correspond to
	nameToExistingAuthz := make(map[string]*corepb.Authorization, len(order.Names))
	for _, v := range existingAuthz.Authz {
		// Don't reuse a valid authorization if the reuseValidAuthz flag is
		// disabled.
		if *v.Authz.Status == string(core.StatusValid) && !ra.reuseValidAuthz {
			continue
		}
		nameToExistingAuthz[*v.Domain] = v.Authz
	}

	// For each of the names in the order, if there is an acceptable
	// existing authz, append it to the order to reuse it. Otherwise track
	// that there is a missing authz for that name.
	var missingAuthzNames []string
	for _, name := range order.Names {
		// If there isn't an existing authz, note that its missing and continue
		if _, exists := nameToExistingAuthz[name]; !exists {
			missingAuthzNames = append(missingAuthzNames, name)
			continue
		}
		authz := nameToExistingAuthz[name]
		// If the identifier is a wildcard and the existing authz only has one
		// DNS-01 type challenge we can reuse it. In theory we will
		// never get back an authorization for a domain with a wildcard prefix
		// that doesn't meet this criteria from SA.GetAuthorizations but we verify
		// again to be safe.
		if strings.HasPrefix(name, "*.") &&
			len(authz.Challenges) == 1 && *authz.Challenges[0].Type == core.ChallengeTypeDNS01 {
			order.Authorizations = append(order.Authorizations, *authz.Id)
			continue
		} else if !strings.HasPrefix(name, "*.") {
			// If the identifier isn't a wildcard, we can reuse any authz
			order.Authorizations = append(order.Authorizations, *authz.Id)
			continue
		}

		// Delete the authz from the nameToExistingAuthz map since we are not reusing it.
		delete(nameToExistingAuthz, name)
		// If we reached this point then the existing authz was not acceptable for
		// reuse and we need to mark the name as requiring a new pending authz
		missingAuthzNames = append(missingAuthzNames, name)
	}

	// If the order isn't fully authorized we need to check that the client has
	// rate limit room for more pending authorizations
	if len(missingAuthzNames) > 0 {
		if err := ra.checkPendingAuthorizationLimit(ctx, *order.RegistrationID); err != nil {
			return nil, err
		}
	}

	// Loop through each of the names missing authzs and create a new pending
	// authorization for each.
	var newAuthzs []*corepb.Authorization
	v2 := features.Enabled(features.NewAuthorizationSchema)
	for _, name := range missingAuthzNames {
		// TODO(#3069): Batch this check
		if err := ra.checkInvalidAuthorizationLimit(ctx, *order.RegistrationID, name); err != nil {
			return nil, err
		}
		pb, err := ra.createPendingAuthz(ctx, *order.RegistrationID, core.AcmeIdentifier{
			Type:  core.IdentifierDNS,
			Value: name,
		}, v2)
		if err != nil {
			return nil, err
		}
		newAuthzs = append(newAuthzs, pb)
	}

	// Start with the order's own expiry as the minExpiry. We only care
	// about authz expiries that are sooner than the order's expiry
	minExpiry := ra.clk.Now().Add(ra.orderLifetime)

	// Check the reused authorizations to see if any have an expiry before the
	// minExpiry (the order's lifetime)
	for _, authz := range nameToExistingAuthz {
		// An authz without an expiry is an unexpected internal server event
		if authz.Expires == nil {
			return nil, berrors.InternalServerError(
				"SA.GetAuthorizations returned an authz (%s) with nil expiry",
				*authz.Id)
		}
		// If the reused authorization expires before the minExpiry, it's expiry
		// is the new minExpiry.
		authzExpiry := time.Unix(0, *authz.Expires)
		if authzExpiry.Before(minExpiry) {
			minExpiry = authzExpiry
		}
	}

	// If new authorizations are needed, call AddPendingAuthorizations. Also check
	// whether the newly created pending authz's have an expiry lower than minExpiry
	if len(newAuthzs) > 0 {
		var ids []string
		req := sapb.AddPendingAuthorizationsRequest{Authz: newAuthzs}
		if v2 {
			authzIDs, err := ra.SA.NewAuthorizations2(ctx, &req)
			if err != nil {
				return nil, err
			}
			for _, id := range authzIDs.Ids {
				ids = append(ids, fmt.Sprintf("%d", id))
			}
		} else {
			authzIDs, err := ra.SA.AddPendingAuthorizations(ctx, &req)
			if err != nil {
				return nil, err
			}
			ids = authzIDs.Ids
		}
		order.Authorizations = append(order.Authorizations, ids...)

		// If the newly created pending authz's have an expiry closer than the
		// minExpiry the minExpiry is the pending authz expiry.
		newPendingAuthzExpires := ra.clk.Now().Add(ra.pendingAuthorizationLifetime)
		if newPendingAuthzExpires.Before(minExpiry) {
			minExpiry = newPendingAuthzExpires
		}
	}

	// Set the order's expiry to the minimum expiry
	minExpiryTS := minExpiry.UnixNano()
	order.Expires = &minExpiryTS
	storedOrder, err := ra.SA.NewOrder(ctx, order)
	if err != nil {
		return nil, err
	}

	return storedOrder, nil
}
747787
func (s *ListModelsInput) SetSortOrder(v string) *ListModelsInput {
	s.SortOrder = &v
	return s
}