// standardWebExposure generates a scheduler.Exposure for a web process in the
// standard Procfile format.
197876
func standardWebExposure(app *App) *twelvefactor.Exposure {
	ports := []twelvefactor.Port{
		{
			Container: 8080,
			Host:      80,
			Protocol:  &twelvefactor.HTTP{},
		},
	}

	// If a certificate is attached to the "web" process, add an SSL port.
	if cert, ok := app.Certs[webProcessType]; ok {
		ports = append(ports, twelvefactor.Port{
			Container: 8080,
			Host:      443,
			Protocol: &twelvefactor.HTTPS{
				Cert: cert,
			},
		})
	}

	return &twelvefactor.Exposure{
		External: app.Exposure == exposePublic,
		Ports:    ports,
	}
}
251950
func IsPCX(src *sdl.RWops) bool {
	_src := (*C.SDL_RWops)(unsafe.Pointer(src))
	return int(C.IMG_isPCX(_src)) > 0
}
988495
func (c *Client) GetWebProfiles() ([]WebProfile, error) {
	var wps []WebProfile

	url := fmt.Sprintf("%s%s", c.APIBase, "/v1/payment-experience/web-profiles")
	req, err := http.NewRequest("GET", url, nil)

	if err != nil {
		return wps, err
	}

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

	return wps, nil
}
932071
func (f *filter) ProcessProposal(ctx context.Context, signedProp *peer.SignedProposal) (*peer.ProposalResponse, error) {
	return f.next.ProcessProposal(ctx, signedProp)
}
772505
func parseCompExp(r string, pos int) (*vrange, int, error) {
	i := pos
	v := &vrange{}

	const (
		ce_start = iota
		val_start
		val_in
		val_end
		ce_end
	)
	st := ce_start
	vstart := 0
	vend := 0

	lt := true

LOOP:
	for ; i < len(r); i++ {
		c := r[i]
		switch c {
		case '<', '>':
			if st != ce_start {
				return nil, i, fmt.Errorf("rule parse error at position %d of rule %s", i, r)
			}
			if c == '<' {
				lt = true
			} else {
				lt = false
			}

			vstart = i + 1
			st = val_start
		case '=':
			if st != val_start {
				return nil, i, fmt.Errorf("rule parse error at position %d of rule %s, '=' should comes after '>' or '<'", i, r)
			}
			if lt {
				v.right = true
			} else {
				v.left = true
			}
			vstart += 1
		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', //positive, negative, or float digital
			'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f', 'X', 'x', //hex
			'h', 'm', 's', 'n', 'u', 'µ': //time.Duration
			if st == val_start {
				st = val_in
			}
		case ' ', '\t':
			switch st {
			case val_start:
				vstart = i + 1
			case val_in:
				st = val_end
				vend = i
				val := r[vstart:vend]
				num, err := parseInt(val)
				if err != nil {
					return nil, i, err
				}
				if lt {
					v.max = num
				} else {
					v.min = num
				}
				st = ce_end
				break LOOP
			default:
			}
		default:
			return nil, i, fmt.Errorf("unknown char at position %d of rule %s", i, r)
		}
	}
	if i == len(r) && st == val_in {
		st = val_end
		vend = i
		val := r[vstart:vend]
		num, err := parseInt(val)
		if err != nil {
			return nil, i, err
		}
		if lt {
			v.max = num
		} else {
			v.min = num
		}
		st = ce_end

	}
	if st != ce_end {
		return nil, i, fmt.Errorf("rule is incompleted %s", r)
	}

	if lt {
		v.min = math.MinInt64
	} else {
		v.max = math.MaxInt64
	}
	return v, i, nil
}
1111726
func RawMarkdown(body []byte, urlPrefix string) []byte {
	htmlFlags := 0
	htmlFlags |= blackfriday.HTML_SKIP_STYLE
	htmlFlags |= blackfriday.HTML_OMIT_CONTENTS

	if setting.Smartypants.Enabled {
		htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
		if setting.Smartypants.Fractions {
			htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
		}
		if setting.Smartypants.Dashes {
			htmlFlags |= blackfriday.HTML_SMARTYPANTS_DASHES
		}
		if setting.Smartypants.LatexDashes {
			htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
		}
		if setting.Smartypants.AngledQuotes {
			htmlFlags |= blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES
		}
	}

	renderer := &MarkdownRenderer{
		Renderer:  blackfriday.HtmlRenderer(htmlFlags, "", ""),
		urlPrefix: urlPrefix,
	}

	// set up the parser
	extensions := 0
	extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
	extensions |= blackfriday.EXTENSION_TABLES
	extensions |= blackfriday.EXTENSION_FENCED_CODE
	extensions |= blackfriday.EXTENSION_AUTOLINK
	extensions |= blackfriday.EXTENSION_STRIKETHROUGH
	extensions |= blackfriday.EXTENSION_SPACE_HEADERS
	extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK

	if setting.Markdown.EnableHardLineBreak {
		extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
	}

	body = blackfriday.Markdown(body, renderer, extensions)
	return body
}
1017621
func (m *MockEndorserServer) ProcessProposal(context context.Context,
	proposal *pb.SignedProposal) (*pb.ProposalResponse, error) {
	if m.ProposalError == nil {
		return &pb.ProposalResponse{Response: &pb.Response{
			Status: 200,
		}, Endorsement: &pb.Endorsement{Endorser: []byte("endorser"), Signature: []byte("signature")},
			Payload: m.createProposalResponsePayload()}, nil
	}
	return &pb.ProposalResponse{Response: &pb.Response{
		Status:  500,
		Message: m.ProposalError.Error(),
	}}, m.ProposalError
}
227801
func doPerfMeasure(fsPath string) (write, read float64, err error) {
	var count int
	var totalWriteElapsed time.Duration
	var totalReadElapsed time.Duration

	defer os.RemoveAll(fsPath)

	randBuf := make([]byte, randBufSize)
	rand.Read(randBuf)
	buf := bytes.Repeat(randBuf, randParts)

	// create the enclosing directory
	err = os.MkdirAll(fsPath, 0777)
	if err != nil {
		return 0, 0, err
	}

	for count = 1; count <= iterations; count++ {
		fsTempObjPath := path.Join(fsPath, strconv.Itoa(count))

		// Write performance calculation
		writeStart := time.Now()
		n, err := writeFile(fsTempObjPath, buf)

		if err != nil {
			return 0, 0, err
		}
		if n != fileSize {
			return 0, 0, errors.New("Could not write temporary data to disk")
		}

		writeElapsed := time.Since(writeStart)
		totalWriteElapsed += writeElapsed

		// Read performance calculation
		readStart := time.Now()
		n, err = readFile(fsTempObjPath, buf)

		if err != nil {
			return 0, 0, err
		}
		if n != fileSize {
			return 0, 0, errors.New("Could not read temporary data from disk")
		}

		readElapsed := time.Since(readStart)
		totalReadElapsed += readElapsed
	}
	// Average time spent = total time elapsed / number of writes
	avgWriteTime := totalWriteElapsed.Seconds() / float64(count)
	// Write perf = fileSize (in Bytes) / average time spent writing (in seconds)
	write = fileSize / avgWriteTime

	// Average time spent = total time elapsed / number of writes
	avgReadTime := totalReadElapsed.Seconds() / float64(count)
	// read perf = fileSize (in Bytes) / average time spent reading (in seconds)
	read = fileSize / avgReadTime

	return write, read, nil
}
420420
func OptionPrefix(x string) Option {
	return func(p *Prompt) error {
		p.renderer.prefix = x
		return nil
	}
}
799392
func WmStateReqExtra(xu *xgbutil.XUtil, win xproto.Window, action int,
	first string, second string, source int) (err error) {

	var atom1, atom2 xproto.Atom

	atom1, err = xprop.Atom(xu, first, false)
	if err != nil {
		return err
	}

	if len(second) > 0 {
		atom2, err = xprop.Atom(xu, second, false)
		if err != nil {
			return err
		}
	} else {
		atom2 = 0
	}

	return ClientEvent(xu, win, "_NET_WM_STATE", action, int(atom1), int(atom2),
		source)
}
1313022
func printWebSource(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
	printHeader(w, rpt)
	if err := PrintWebList(w, rpt, obj, -1); err != nil {
		return err
	}
	printPageClosing(w)
	return nil
}
1094353
func (rlp *RateLimitPolicy) WindowBegin(windowEnd time.Time) time.Time {
	return windowEnd.Add(-1 * rlp.Window.Duration)
}
147045
func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
	sel, isSel := p.GetParentByIndex(0).(*Selection)
	if !isSel {
		return nil, nil
	}

	for _, cond := range sel.Conditions {
		if con, ok := cond.(*expression.Constant); ok {
			result, err := expression.EvalBool(con, nil, p.ctx)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if !result {
				dummy := &PhysicalDummyScan{}
				dummy.tp = "Dummy"
				dummy.allocator = p.allocator
				dummy.initIDAndContext(p.ctx)
				dummy.SetSchema(p.schema)
				info := &physicalPlanInfo{p: dummy}
				p.storePlanInfo(prop, info)
				return info, nil
			}
		}
	}
	return nil, nil
}
624440
func (l *channelLink) processExitHop(pd *lnwallet.PaymentDescriptor,
	obfuscator ErrorEncrypter, fwdInfo ForwardingInfo, heightNow uint32) (
	bool, error) {

	// If hodl.ExitSettle is requested, we will not validate the final hop's
	// ADD, nor will we settle the corresponding invoice or respond with the
	// preimage.
	if l.cfg.DebugHTLC && l.cfg.HodlMask.Active(hodl.ExitSettle) {
		l.warnf(hodl.ExitSettle.Warning())

		return false, nil
	}

	// First, we'll check the expiry of the HTLC itself against, the current
	// block height. If the timeout is too soon, then we'll reject the HTLC.
	if pd.Timeout <= heightNow+l.cfg.FinalCltvRejectDelta {
		log.Errorf("htlc(%x) has an expiry that's too soon: expiry=%v"+
			", best_height=%v", pd.RHash[:], pd.Timeout, heightNow)

		failure := lnwire.NewFinalExpiryTooSoon()
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We're the designated payment destination.  Therefore we attempt to
	// see if we have an invoice locally which'll allow us to settle this
	// htlc.
	//
	// Only the immutable data from LookupInvoice is used, because otherwise
	// a race condition may be created with concurrent writes to the invoice
	// registry. For example: cancelation of an invoice.
	invoiceHash := lntypes.Hash(pd.RHash)
	invoice, minCltvDelta, err := l.cfg.Registry.LookupInvoice(invoiceHash)
	if err != nil {
		log.Errorf("unable to query invoice registry: %v", err)
		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// If the invoice is already settled, we choose to accept the payment to
	// simplify failure recovery.
	//
	// NOTE: Though our recovery and forwarding logic is predominately
	// batched, settling invoices happens iteratively. We may reject one of
	// two payments for the same rhash at first, but then restart and reject
	// both after seeing that the invoice has been settled. Without any
	// record of which one settles first, it is ambiguous as to which one
	// actually settled the invoice. Thus, by accepting all payments, we
	// eliminate the race condition that can lead to this inconsistency.
	//
	// TODO(conner): track ownership of settlements to properly recover from
	// failures? or add batch invoice settlement
	//
	// TODO(joostjager): The log statement below is not always accurate, as
	// the invoice may have been canceled after the LookupInvoice call.
	// Leaving it as is for now, because fixing this would involve changing
	// the signature of InvoiceRegistry.SettleInvoice just because of this
	// log statement.
	if invoice.Terms.State == channeldb.ContractSettled {
		log.Warnf("Accepting duplicate payment for hash=%x",
			pd.RHash[:])
	}

	// If we're not currently in debug mode, and the extended htlc doesn't
	// meet the value requested, then we'll fail the htlc.  Otherwise, we
	// settle this htlc within our local state update log, then send the
	// update entry to the remote party.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		pd.Amount < invoice.Terms.Value {

		log.Errorf("rejecting htlc due to incorrect amount: expected "+
			"%v, received %v", invoice.Terms.Value, pd.Amount)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// As we're the exit hop, we'll double check the hop-payload included in
	// the HTLC to ensure that it was crafted correctly by the sender and
	// matches the HTLC we were extended.
	//
	// NOTE: We make an exception when the value requested by the invoice is
	// zero. This means the invoice allows the payee to specify the amount
	// of satoshis they wish to send.  So since we expect the htlc to have a
	// different amount, we should not fail.
	if !l.cfg.DebugHTLC && invoice.Terms.Value > 0 &&
		fwdInfo.AmountToForward < invoice.Terms.Value {

		log.Errorf("Onion payload of incoming htlc(%x) has incorrect "+
			"value: expected %v, got %v", pd.RHash,
			invoice.Terms.Value, fwdInfo.AmountToForward)

		failure := lnwire.NewFailUnknownPaymentHash(pd.Amount)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// We'll also ensure that our time-lock value has been computed
	// correctly. Only check the final cltv expiry for invoices when the
	// invoice has not yet moved to the accepted state. Otherwise hodl htlcs
	// would be canceled after a restart.
	expectedHeight := heightNow + minCltvDelta
	switch {
	case !l.cfg.DebugHTLC &&
		invoice.Terms.State == channeldb.ContractOpen &&
		pd.Timeout < expectedHeight:

		log.Errorf("Incoming htlc(%x) has an expiration that is too "+
			"soon: expected at least %v, got %v",
			pd.RHash[:], expectedHeight, pd.Timeout)

		failure := lnwire.FailFinalExpiryTooSoon{}
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil

	case !l.cfg.DebugHTLC && pd.Timeout != fwdInfo.OutgoingCTLV:
		log.Errorf("HTLC(%x) has incorrect time-lock: expected %v, "+
			"got %v", pd.RHash[:], pd.Timeout, fwdInfo.OutgoingCTLV)

		failure := lnwire.NewFinalIncorrectCltvExpiry(
			fwdInfo.OutgoingCTLV,
		)
		l.sendHTLCError(pd.HtlcIndex, failure, obfuscator, pd.SourceRef)

		return true, nil
	}

	// Notify the invoiceRegistry of the exit hop htlc. If we crash right
	// after this, this code will be re-executed after restart. We will
	// receive back a resolution event.
	event, err := l.cfg.Registry.NotifyExitHopHtlc(
		invoiceHash, pd.Amount, l.hodlQueue.ChanIn(),
	)
	if err != nil {
		return false, err
	}

	// Create a hodlHtlc struct and decide either resolved now or later.
	htlc := hodlHtlc{
		pd:         pd,
		obfuscator: obfuscator,
	}

	if event == nil {
		// Save payment descriptor for future reference.
		hodlHtlcs := l.hodlMap[invoiceHash]
		l.hodlMap[invoiceHash] = append(hodlHtlcs, htlc)

		return false, nil
	}

	// Process the received resolution.
	err = l.processHodlEvent(*event, htlc)
	if err != nil {
		return false, err
	}
	return true, nil
}
1271139
func webHooksDescribe(triggers []buildv1.BuildTriggerPolicy, name, namespace string, c rest.Interface) map[string][]DescribeWebhook {
	result := map[string][]DescribeWebhook{}

	for _, trigger := range triggers {
		var allowEnv *bool

		switch trigger.Type {
		case buildv1.GitHubWebHookBuildTriggerType, buildv1.GitLabWebHookBuildTriggerType, buildv1.BitbucketWebHookBuildTriggerType:
		case buildv1.GenericWebHookBuildTriggerType:
			allowEnv = &trigger.GenericWebHook.AllowEnv

		default:
			continue
		}
		webHookDesc := result[string(trigger.Type)]

		var urlStr string
		webhookClient := buildmanualclient.NewWebhookURLClient(c, namespace)
		u, err := webhookClient.WebHookURL(name, &trigger)
		if err != nil {
			urlStr = fmt.Sprintf("<error: %s>", err.Error())
		} else {
			urlStr, _ = url.PathUnescape(u.String())
		}

		webHookDesc = append(webHookDesc,
			DescribeWebhook{
				URL:      urlStr,
				AllowEnv: allowEnv,
			})
		result[string(trigger.Type)] = webHookDesc
	}

	return result
}
101023
func Standard(ctx context.Context) {
	if r := recover(); r != nil {
		outputPanic(ctx, r)
	}
}
1062787
func exposeMetrics() {
	goroutines := expvar.NewInt("total_goroutines")
	uptime := expvar.NewFloat("process_uptime_seconds")

	start := time.Now()

	go func() {
		for range time.Tick(5 * time.Second) {
			goroutines.Set(int64(runtime.NumGoroutine()))
			uptime.Set(time.Since(start).Seconds())
		}
	}()

	log.Println("Expvars at http://localhost:8123/debug/vars")
	go http.ListenAndServe(":8123", nil)
}