text:
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tcp

import (
	"container/list"
	"crypto/sha1"
	"encoding/binary"
	"fmt"
	"hash"
	"io"
	"time"

	"gvisor.dev/gvisor/pkg/sync"
	"gvisor.dev/gvisor/pkg/tcpip"
	"gvisor.dev/gvisor/pkg/tcpip/header"
	"gvisor.dev/gvisor/pkg/tcpip/ports"
	"gvisor.dev/gvisor/pkg/tcpip/seqnum"
	"gvisor.dev/gvisor/pkg/tcpip/stack"
	"gvisor.dev/gvisor/pkg/waiter"
)

const (
	// tsLen is the length, in bits, of the timestamp in the SYN cookie.
	tsLen = 8

	// tsMask is a mask for timestamp values (i.e., tsLen bits).
	tsMask = (1 << tsLen) - 1

	// tsOffset is the offset, in bits, of the timestamp in the SYN cookie.
	tsOffset = 24

	// hashMask is the mask for hash values (i.e., tsOffset bits).
	hashMask = (1 << tsOffset) - 1

	// maxTSDiff is the maximum allowed difference between a received cookie
	// timestamp and the current timestamp. If the difference is greater
	// than maxTSDiff, the cookie is expired.
	maxTSDiff = 2
)

var (
	// mssTable is a slice containing the possible MSS values that we
	// encode in the SYN cookie with two bits.
	mssTable = []uint16{536, 1300, 1440, 1460}
)

func encodeMSS(mss uint16) uint32 {
	for i := len(mssTable) - 1; i > 0; i-- {
		if mss >= mssTable[i] {
			return uint32(i)
		}
	}
	return 0
}

// listenContext is used by a listening endpoint to store state used while
// listening for connections. This struct is allocated by the listen goroutine
// and must not be accessed or have its methods called concurrently as they
// may mutate the stored objects.
type listenContext struct {
	stack    *stack.Stack
	protocol *protocol

	// rcvWnd is the receive window that is sent by this listening context
	// in the initial SYN-ACK.
	rcvWnd seqnum.Size

	// nonce are random bytes that are initialized once when the context
	// is created and used to seed the hash function when generating
	// the SYN cookie.
	nonce [2][sha1.BlockSize]byte

	// listenEP is a reference to the listening endpoint associated with
	// this context. Can be nil if the context is created by the forwarder.
	listenEP *endpoint

	// hasherMu protects hasher.
	hasherMu sync.Mutex
	// hasher is the hash function used to generate a SYN cookie.
	hasher hash.Hash

	// v6Only is true if listenEP is a dual stack socket and has the
	// IPV6_V6ONLY option set.
	v6Only bool

	// netProto indicates the network protocol(IPv4/v6) for the listening
	// endpoint.
	netProto tcpip.NetworkProtocolNumber
}

// timeStamp returns an 8-bit timestamp with a granularity of 64 seconds.
func timeStamp(clock tcpip.Clock) uint32 {
	return uint32(clock.NowMonotonic().Sub(tcpip.MonotonicTime{}).Seconds()) >> 6 & tsMask
}

// newListenContext creates a new listen context.
func newListenContext(stk *stack.Stack, protocol *protocol, listenEP *endpoint, rcvWnd seqnum.Size, v6Only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {
	l := &listenContext{
		stack:    stk,
		protocol: protocol,
		rcvWnd:   rcvWnd,
		hasher:   sha1.New(),
		v6Only:   v6Only,
		netProto: netProto,
		listenEP: listenEP,
	}

	for i := range l.nonce {
		if _, err := io.ReadFull(stk.SecureRNG(), l.nonce[i][:]); err != nil {
			panic(err)
		}
	}

	return l
}

// cookieHash calculates the cookieHash for the given id, timestamp and nonce
// index. The hash is used to create and validate cookies.
func (l *listenContext) cookieHash(id stack.TransportEndpointID, ts uint32, nonceIndex int) uint32 {

	// Initialize block with fixed-size data: local ports and v.
	var payload [8]byte
	binary.BigEndian.PutUint16(payload[0:], id.LocalPort)
	binary.BigEndian.PutUint16(payload[2:], id.RemotePort)
	binary.BigEndian.PutUint32(payload[4:], ts)

	// Feed everything to the hasher.
	l.hasherMu.Lock()
	l.hasher.Reset()

	// Per hash.Hash.Writer:
	//
	// It never returns an error.
	l.hasher.Write(payload[:])
	l.hasher.Write(l.nonce[nonceIndex][:])
	l.hasher.Write(id.LocalAddress.AsSlice())
	l.hasher.Write(id.RemoteAddress.AsSlice())

	// Finalize the calculation of the hash and return the first 4 bytes.
	h := l.hasher.Sum(nil)
	l.hasherMu.Unlock()

	return binary.BigEndian.Uint32(h[:])
}

// createCookie creates a SYN cookie for the given id and incoming sequence
// number.
func (l *listenContext) createCookie(id stack.TransportEndpointID, seq seqnum.Value, data uint32) seqnum.Value {
	ts := timeStamp(l.stack.Clock())
	v := l.cookieHash(id, 0, 0) + uint32(seq) + (ts << tsOffset)
	v += (l.cookieHash(id, ts, 1) + data) & hashMask
	return seqnum.Value(v)
}

// isCookieValid checks if the supplied cookie is valid for the given id and
// sequence number. If it is, it also returns the data originally encoded in the
// cookie when createCookie was called.
func (l *listenContext) isCookieValid(id stack.TransportEndpointID, cookie seqnum.Value, seq seqnum.Value) (uint32, bool) {
	ts := timeStamp(l.stack.Clock())
	v := uint32(cookie) - l.cookieHash(id, 0, 0) - uint32(seq)
	cookieTS := v >> tsOffset
	if ((ts - cookieTS) & tsMask) > maxTSDiff {
		return 0, false
	}

	return (v - l.cookieHash(id, cookieTS, 1)) & hashMask, true
}

// createConnectingEndpoint creates a new endpoint in a connecting state, with
// the connection parameters given by the arguments. The newly created endpoint
// will be locked.
// +checklocksacquire:n.mu
func (l *listenContext) createConnectingEndpoint(s *segment, rcvdSynOpts header.TCPSynOptions, queue *waiter.Queue) (n *endpoint, _ tcpip.Error) {
	// Create a new endpoint.
	netProto := l.netProto
	if netProto == 0 {
		netProto = s.pkt.NetworkProtocolNumber
	}

	route, err := l.stack.FindRoute(s.pkt.NICID, s.pkt.Network().DestinationAddress(), s.pkt.Network().SourceAddress(), s.pkt.NetworkProtocolNumber, false /* multicastLoop */)
	if err != nil {
		return nil, err // +checklocksignore
	}

	n = newEndpoint(l.stack, l.protocol, netProto, queue)
	n.mu.Lock()
	n.ops.SetV6Only(l.v6Only)
	n.TransportEndpointInfo.ID = s.id
	n.boundNICID = s.pkt.NICID
	n.route = route
	n.effectiveNetProtos = []tcpip.NetworkProtocolNumber{s.pkt.NetworkProtocolNumber}
	n.ops.SetReceiveBufferSize(int64(l.rcvWnd), false /* notify */)
	n.amss = calculateAdvertisedMSS(n.userMSS, n.route)
	n.setEndpointState(StateConnecting)

	n.maybeEnableTimestamp(rcvdSynOpts)
	n.maybeEnableSACKPermitted(rcvdSynOpts)

	n.initGSO()

	// Bootstrap the auto tuning algorithm. Starting at zero will result in
	// a large step function on the first window adjustment causing the
	// window to grow to a really large value.
	initWnd := n.initialReceiveWindow()
	n.rcvQueueMu.Lock()
	n.RcvAutoParams.PrevCopiedBytes = initWnd
	n.rcvQueueMu.Unlock()

	return n, nil
}

// startHandshake creates a new endpoint in connecting state and then sends
// the SYN-ACK for the TCP 3-way handshake. It returns the state of the
// handshake in progress, which includes the new endpoint in the SYN-RCVD
// state.
//
// On success, a handshake h is returned.
//
// NOTE: h.ep.mu is not held and must be acquired if any state needs to be
// modified.
//
// Precondition: if l.listenEP != nil, l.listenEP.mu must be locked.
func (l *listenContext) startHandshake(s *segment, opts header.TCPSynOptions, queue *waiter.Queue, owner tcpip.PacketOwner) (h *handshake, _ tcpip.Error) {
	// Create new endpoint.
	irs := s.sequenceNumber
	isn := generateSecureISN(s.id, l.stack.Clock(), l.protocol.seqnumSecret)
	ep, err := l.createConnectingEndpoint(s, opts, queue)
	if err != nil {
		return nil, err // +checklocksignore
	}

	ep.owner = owner

	// listenEP is nil when listenContext is used by tcp.Forwarder.
	deferAccept := time.Duration(0)
	if l.listenEP != nil {
		if l.listenEP.EndpointState() != StateListen {

			// Ensure we release any registrations done by the newly
			// created endpoint.
			ep.mu.Unlock()
			ep.Close()

			return nil, &tcpip.ErrConnectionAborted{} // +checklocksignore
		}

		// Propagate any inheritable options from the listening endpoint
		// to the newly created endpoint.
		l.listenEP.propagateInheritableOptionsLocked(ep) // +checklocksforce

		if !ep.reserveTupleLocked() {
			ep.mu.Unlock()
			ep.Close()

			return nil, &tcpip.ErrConnectionAborted{} // +checklocksignore
		}

		deferAccept = l.listenEP.deferAccept
	}

	// Register new endpoint so that packets are routed to it.
	if err := ep.stack.RegisterTransportEndpoint(
		ep.effectiveNetProtos,
		ProtocolNumber,
		ep.TransportEndpointInfo.ID,
		ep,
		ep.boundPortFlags,
		ep.boundBindToDevice,
	); err != nil {
		ep.mu.Unlock()
		ep.Close()

		ep.drainClosingSegmentQueue()

		return nil, err // +checklocksignore
	}

	ep.isRegistered = true

	// Initialize and start the handshake.
	h = ep.newPassiveHandshake(isn, irs, opts, deferAccept)
	h.listenEP = l.listenEP
	h.start()
	h.ep.mu.Unlock()
	return h, nil
}

// performHandshake performs a TCP 3-way handshake. On success, the new
// established endpoint is returned.
//
// Precondition: if l.listenEP != nil, l.listenEP.mu must be locked.
func (l *listenContext) performHandshake(s *segment, opts header.TCPSynOptions, queue *waiter.Queue, owner tcpip.PacketOwner) (*endpoint, tcpip.Error) {
	waitEntry, notifyCh := waiter.NewChannelEntry(waiter.WritableEvents)
	queue.EventRegister(&waitEntry)
	defer queue.EventUnregister(&waitEntry)

	h, err := l.startHandshake(s, opts, queue, owner)
	if err != nil {
		return nil, err
	}

	// performHandshake is used by the Forwarder which will block till the
	// handshake either succeeds or fails. We do this by registering for
	// events above and block on the notification channel.
	<-notifyCh

	ep := h.ep
	ep.mu.Lock()
	if !ep.EndpointState().connected() {
		ep.stack.Stats().TCP.FailedConnectionAttempts.Increment()
		ep.stats.FailedConnectionAttempts.Increment()
		ep.h = nil
		ep.mu.Unlock()
		ep.Close()
		ep.notifyAborted()
		ep.drainClosingSegmentQueue()
		err := ep.LastError()
		if err == nil {
			// If err was nil then return the best error we can to indicate
			// a connection failure.
			err = &tcpip.ErrConnectionAborted{}
		}
		return nil, err
	}

	ep.isConnectNotified = true

	// Transfer any state from the completed handshake to the endpoint.
	//
	// Update the receive window scaling. We can't do it before the
	// handshake because it's possible that the peer doesn't support window
	// scaling.
	ep.rcv.RcvWndScale = ep.h.effectiveRcvWndScale()

	// Clean up handshake state stored in the endpoint so that it can be
	// GCed.
	ep.h = nil
	ep.mu.Unlock()
	return ep, nil
}

// propagateInheritableOptionsLocked propagates any options set on the listening
// endpoint to the newly created endpoint.
//
// +checklocks:e.mu
// +checklocks:n.mu
func (e *endpoint) propagateInheritableOptionsLocked(n *endpoint) {
	n.userTimeout = e.userTimeout
	n.portFlags = e.portFlags
	n.boundBindToDevice = e.boundBindToDevice
	n.boundPortFlags = e.boundPortFlags
	n.userMSS = e.userMSS
}

// reserveTupleLocked reserves an accepted endpoint's tuple.
//
// Precondition: e.propagateInheritableOptionsLocked has been called.
//
// +checklocks:e.mu
func (e *endpoint) reserveTupleLocked() bool {
	dest := tcpip.FullAddress{
		Addr: e.TransportEndpointInfo.ID.RemoteAddress,
		Port: e.TransportEndpointInfo.ID.RemotePort,
	}
	portRes := ports.Reservation{
		Networks:     e.effectiveNetProtos,
		Transport:    ProtocolNumber,
		Addr:         e.TransportEndpointInfo.ID.LocalAddress,
		Port:         e.TransportEndpointInfo.ID.LocalPort,
		Flags:        e.boundPortFlags,
		BindToDevice: e.boundBindToDevice,
		Dest:         dest,
	}
	if !e.stack.ReserveTuple(portRes) {
		e.stack.Stats().TCP.FailedPortReservations.Increment()
		return false
	}

	e.isPortReserved = true
	e.boundDest = dest
	return true
}

// notifyAborted wakes up any waiters on registered, but not accepted
// endpoints.
//
// This is strictly not required normally as a socket that was never accepted
// can't really have any registered waiters except when stack.Wait() is called
// which waits for all registered endpoints to stop and expects an EventHUp.
func (e *endpoint) notifyAborted() {
	e.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)
}

func (e *endpoint) acceptQueueIsFull() bool {
	e.acceptMu.Lock()
	full := e.acceptQueue.isFull()
	e.acceptMu.Unlock()
	return full
}

// +stateify savable
type acceptQueue struct {
	// NB: this could be an endpointList, but ilist only permits endpoints to
	// belong to one list at a time, and endpoints are already stored in the
	// dispatcher's list.
	endpoints list.List `state:".([]*endpoint)"`

	// pendingEndpoints is a set of all endpoints for which a handshake is
	// in progress.
	pendingEndpoints map[*endpoint]struct{}

	// capacity is the maximum number of endpoints that can be in endpoints.
	capacity int
}

func (a *acceptQueue) isFull() bool {
	return a.endpoints.Len() >= a.capacity
}

// handleListenSegment is called when a listening endpoint receives a segment
// and needs to handle it.
//
// +checklocks:e.mu
func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Error {
	e.rcvQueueMu.Lock()
	rcvClosed := e.RcvClosed
	e.rcvQueueMu.Unlock()
	if rcvClosed || s.flags.Contains(header.TCPFlagSyn|header.TCPFlagAck) {
		// If the endpoint is shutdown, reply with reset.
		//
		// RFC 793 section 3.4 page 35 (figure 12) outlines that a RST
		// must be sent in response to a SYN-ACK while in the listen
		// state to prevent completing a handshake from an old SYN.
		return replyWithReset(e.stack, s, e.sendTOS, e.ipv4TTL, e.ipv6HopLimit)
	}

	switch {
	case s.flags.Contains(header.TCPFlagRst):
		e.stack.Stats().DroppedPackets.Increment()
		return nil

	case s.flags.Contains(header.TCPFlagSyn):
		if e.acceptQueueIsFull() {
			e.stack.Stats().TCP.ListenOverflowSynDrop.Increment()
			e.stats.ReceiveErrors.ListenOverflowSynDrop.Increment()
			e.stack.Stats().DroppedPackets.Increment()
			return nil
		}

		opts := parseSynSegmentOptions(s)

		useSynCookies, err := func() (bool, tcpip.Error) {
			var alwaysUseSynCookies tcpip.TCPAlwaysUseSynCookies
			if err := e.stack.TransportProtocolOption(header.TCPProtocolNumber, &alwaysUseSynCookies); err != nil {
				panic(fmt.Sprintf("TransportProtocolOption(%d, %T) = %s", header.TCPProtocolNumber, alwaysUseSynCookies, err))
			}
			if alwaysUseSynCookies {
				return true, nil
			}
			e.acceptMu.Lock()
			defer e.acceptMu.Unlock()

			// The capacity of the accepted queue would always be one greater than the
			// listen backlog. But, the SYNRCVD connections count is always checked
			// against the listen backlog value for Linux parity reason.
			// https://github.com/torvalds/linux/blob/7acac4b3196/include/net/inet_connection_sock.h#L280
			if len(e.acceptQueue.pendingEndpoints) == e.acceptQueue.capacity-1 {
				return true, nil
			}

			h, err := ctx.startHandshake(s, opts, &waiter.Queue{}, e.owner)
			if err != nil {
				e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
				e.stats.FailedConnectionAttempts.Increment()
				return false, err
			}
			e.acceptQueue.pendingEndpoints[h.ep] = struct{}{}

			return false, nil
		}()
		if err != nil {
			return err
		}
		if !useSynCookies {
			return nil
		}

		net := s.pkt.Network()
		route, err := e.stack.FindRoute(s.pkt.NICID, net.DestinationAddress(), net.SourceAddress(), s.pkt.NetworkProtocolNumber, false /* multicastLoop */)
		if err != nil {
			return err
		}
		defer route.Release()

		// Send SYN without window scaling because we currently
		// don't encode this information in the cookie.
		//
		// Enable Timestamp option if the original syn did have
		// the timestamp option specified.
		//
		// Use the user supplied MSS on the listening socket for
		// new connections, if available.
		synOpts := header.TCPSynOptions{
			WS:    -1,
			TS:    opts.TS,
			TSEcr: opts.TSVal,
			MSS:   calculateAdvertisedMSS(e.userMSS, route),
		}
		if opts.TS {
			offset := e.protocol.tsOffset(net.DestinationAddress(), net.SourceAddress())
			now := e.stack.Clock().NowMonotonic()
			synOpts.TSVal = offset.TSVal(now)
		}
		cookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))
		fields := tcpFields{
			id:     s.id,
			ttl:    calculateTTL(route, e.ipv4TTL, e.ipv6HopLimit),
			tos:    e.sendTOS,
			flags:  header.TCPFlagSyn | header.TCPFlagAck,
			seq:    cookie,
			ack:    s.sequenceNumber + 1,
			rcvWnd: ctx.rcvWnd,
		}
		if err := e.sendSynTCP(route, fields, synOpts); err != nil {
			return err
		}
		e.stack.Stats().TCP.ListenOverflowSynCookieSent.Increment()
		return nil

	case s.flags.Contains(header.TCPFlagAck):
		iss := s.ackNumber - 1
		irs := s.sequenceNumber - 1

		// Since SYN cookies are in use this is potentially an ACK to a
		// SYN-ACK we sent but don't have a half open connection state
		// as cookies are being used to protect against a potential SYN
		// flood. In such cases validate the cookie and if valid create
		// a fully connected endpoint and deliver to the accept queue.
		//
		// If not, silently drop the ACK to avoid leaking information
		// when under a potential syn flood attack.
		//
		// Validate the cookie.
		data, ok := ctx.isCookieValid(s.id, iss, irs)
		if !ok || int(data) >= len(mssTable) {
			e.stack.Stats().TCP.ListenOverflowInvalidSynCookieRcvd.Increment()
			e.stack.Stats().DroppedPackets.Increment()

			// When not using SYN cookies, as per RFC 793, section 3.9, page 64:
			// Any acknowledgment is bad if it arrives on a connection still in
			// the LISTEN state.  An acceptable reset segment should be formed
			// for any arriving ACK-bearing segment.  The RST should be
			// formatted as follows:
			//
			//  <SEQ=SEG.ACK><CTL=RST>
			//
			// Send a reset as this is an ACK for which there is no
			// half open connections and we are not using cookies
			// yet.
			//
			// The only time we should reach here when a connection
			// was opened and closed really quickly and a delayed
			// ACK was received from the sender.
			return replyWithReset(e.stack, s, e.sendTOS, e.ipv4TTL, e.ipv6HopLimit)
		}

		// As an edge case when SYN-COOKIES are in use and we receive a
		// segment that has data and is valid we should check if it
		// already matches a created endpoint and redirect the segment
		// rather than try and create a new endpoint. This can happen
		// where the final ACK for the handshake and other data packets
		// arrive at the same time and are queued to the listening
		// endpoint before the listening endpoint has had time to
		// process the first ACK and create the endpoint that matches
		// the incoming packet's full 5 tuple.
		netProtos := []tcpip.NetworkProtocolNumber{s.pkt.NetworkProtocolNumber}
		// If the local address is an IPv4 Address then also look for IPv6
		// dual stack endpoints.
		if s.id.LocalAddress.To4() != (tcpip.Address{}) {
			netProtos = []tcpip.NetworkProtocolNumber{header.IPv4ProtocolNumber, header.IPv6ProtocolNumber}
		}
		for _, netProto := range netProtos {
			if newEP := e.stack.FindTransportEndpoint(netProto, ProtocolNumber, s.id, s.pkt.NICID); newEP != nil && newEP != e {
				tcpEP := newEP.(*endpoint)
				if !tcpEP.EndpointState().connected() {
					continue
				}
				if !tcpEP.enqueueSegment(s) {
					// Just silently drop the segment as we failed
					// to queue, we don't want to generate a RST
					// further below or try and create a new
					// endpoint etc.
					return nil
				}
				tcpEP.notifyProcessor()
				return nil
			}
		}

		// Keep hold of acceptMu until the new endpoint is in the accept queue (or
		// if there is an error), to guarantee that we will keep our spot in the
		// queue even if another handshake from the syn queue completes.
		e.acceptMu.Lock()
		if e.acceptQueue.isFull() {
			// Silently drop the ack as the application can't accept
			// the connection at this point. The ack will be
			// retransmitted by the sender anyway and we can
			// complete the connection at the time of retransmit if
			// the backlog has space.
			e.acceptMu.Unlock()
			e.stack.Stats().TCP.ListenOverflowAckDrop.Increment()
			e.stats.ReceiveErrors.ListenOverflowAckDrop.Increment()
			e.stack.Stats().DroppedPackets.Increment()
			return nil
		}

		e.stack.Stats().TCP.ListenOverflowSynCookieRcvd.Increment()
		// Create newly accepted endpoint and deliver it.
		rcvdSynOptions := header.TCPSynOptions{
			MSS: mssTable[data],
			// Disable Window scaling as original SYN is
			// lost.
			WS: -1,
		}

		// When syn cookies are in use we enable timestamp only
		// if the ack specifies the timestamp option assuming
		// that the other end did in fact negotiate the
		// timestamp option in the original SYN.
		if s.parsedOptions.TS {
			rcvdSynOptions.TS = true
			rcvdSynOptions.TSVal = s.parsedOptions.TSVal
			rcvdSynOptions.TSEcr = s.parsedOptions.TSEcr
		}

		n, err := ctx.createConnectingEndpoint(s, rcvdSynOptions, &waiter.Queue{})
		if err != nil {
			e.acceptMu.Unlock()
			return err
		}

		// Propagate any inheritable options from the listening endpoint
		// to the newly created endpoint.
		e.propagateInheritableOptionsLocked(n)

		if !n.reserveTupleLocked() {
			n.mu.Unlock()
			e.acceptMu.Unlock()
			n.Close()

			e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
			e.stats.FailedConnectionAttempts.Increment()
			return nil
		}

		// Register new endpoint so that packets are routed to it.
		if err := n.stack.RegisterTransportEndpoint(
			n.effectiveNetProtos,
			ProtocolNumber,
			n.TransportEndpointInfo.ID,
			n,
			n.boundPortFlags,
			n.boundBindToDevice,
		); err != nil {
			n.mu.Unlock()
			e.acceptMu.Unlock()
			n.Close()

			e.stack.Stats().TCP.FailedConnectionAttempts.Increment()
			e.stats.FailedConnectionAttempts.Increment()
			return err
		}

		n.isRegistered = true
		net := s.pkt.Network()
		n.TSOffset = n.protocol.tsOffset(net.DestinationAddress(), net.SourceAddress())

		// Switch state to connected.
		n.isConnectNotified = true
		h := handshake{
			ep:                  n,
			iss:                 iss,
			ackNum:              irs + 1,
			rcvWnd:              seqnum.Size(n.initialReceiveWindow()),
			sndWnd:              s.window,
			rcvWndScale:         e.rcvWndScaleForHandshake(),
			sndWndScale:         rcvdSynOptions.WS,
			mss:                 rcvdSynOptions.MSS,
			sampleRTTWithTSOnly: true,
		}
		h.ep.AssertLockHeld(n)
		h.transitionToStateEstablishedLocked(s)
		n.mu.Unlock()

		// Requeue the segment if the ACK completing the handshake has more info
		// to be processed by the newly established endpoint.
		if (s.flags.Contains(header.TCPFlagFin) || s.payloadSize() > 0) && n.enqueueSegment(s) {
			n.notifyProcessor()
		}

		e.stack.Stats().TCP.PassiveConnectionOpenings.Increment()

		// Deliver the endpoint to the accept queue.
		e.acceptQueue.endpoints.PushBack(n)
		e.acceptMu.Unlock()

		e.waiterQueue.Notify(waiter.ReadableEvents)
		return nil

	default:
		e.stack.Stats().DroppedPackets.Increment()
		return nil
	}
}

repository: google/gvisor

repo_name: google/gvisor


text:
/*
Copyright 2016 The GoStor Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package router

import "github.com/gostor/gotgt/pkg/apiserver/httputils"

// Router defines an interface to specify a group of routes to add the the docker server.
type Router interface {
	Routes() []Route
}

// Route defines an individual API route in the docker server.
type Route interface {
	// Handler returns the raw function to create the http handler.
	Handler() httputils.APIFunc
	// Method returns the http method that the route responds to.
	Method() string
	// Path returns the subpath where the route responds to.
	Path() string
}

// localRoute defines an individual API route to connect with the docker daemon.
// It implements router.Route.
type localRoute struct {
	method  string
	path    string
	handler httputils.APIFunc
}

// Handler returns the APIFunc to let the server wrap it in middlewares
func (l localRoute) Handler() httputils.APIFunc {
	return l.handler
}

// Method returns the http method that the route responds to.
func (l localRoute) Method() string {
	return l.method
}

// Path returns the subpath where the route responds to.
func (l localRoute) Path() string {
	return l.path
}

// NewRoute initializes a new local router for the reouter
func NewRoute(method, path string, handler httputils.APIFunc) Route {
	return localRoute{method, path, handler}
}

// NewGetRoute initializes a new route with the http method GET.
func NewGetRoute(path string, handler httputils.APIFunc) Route {
	return NewRoute("GET", path, handler)
}

// NewPostRoute initializes a new route with the http method POST.
func NewPostRoute(path string, handler httputils.APIFunc) Route {
	return NewRoute("POST", path, handler)
}

// NewPostRoute initializes a new route with the http method POST.
func NewDeleteRoute(path string, handler httputils.APIFunc) Route {
	return NewRoute("DELETE", path, handler)
}

repository: gostor/gotgt

license_type: permissive

repo_name: gostor/gotgt

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
package main

import (
	"strings"
)

func init() {
	addSolutions(5, problem5)
}

func problem5(ctx *problemContext) {
	var maxID int
	ids := make(map[int]struct{})
	replacer := strings.NewReplacer("F", "0", "B", "1", "L", "0", "R", "1")
	scanner := ctx.scanner()
	for scanner.scan() {
		s := replacer.Replace(scanner.text())
		id := int(parseInt(s, 2, 32))
		ids[id] = struct{}{}
		if id > maxID {
			maxID = id
		}
	}
	ctx.reportLoad()
	ctx.reportPart1(maxID)

	for n := maxID - 1; ; n-- {
		if _, ok := ids[n]; !ok {
			ctx.reportPart2(n)
			break
		}
	}

}

license: MIT

branch_name: refs/heads/main


text:
# Version Suite
# Author: Brian Panneton
# Descrition:   This small suite allows you to add support
#               for versioning in your projects

# This allows you to turn on and off the auto
# update of the (project name)Version.hpp file
if (FALSE) # XXX(kitware): force settings
SET(VERSION_CONTROL_AUTOUPDATE OFF CACHE BOOL "Automaticaly Update The Version")
MARK_AS_ADVANCED(VERSION_CONTROL_AUTOUPDATE)
else ()
set(VERSION_CONTROL_AUTOUPDATE OFF)
endif ()

# We need to make sure we have the header file
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/CMake/VersionSuite)

# Default incase CalculateVerison is not called
SET(vMajor "0")
SET(vMinor "0")
SET(vPatch "0")

# This Macro allows you to set up the Version in a one liner
MACRO(VersionCreate versionName versionMajor versionMinor versionPatch export_name)
    VersionMajorSet(${versionMajor})
    VersionMinorSet(${versionMinor})
    VersionPatchSet(${versionPatch})

# Manually generating minor version
#   VersionCalculate()
    VersionWrite(${versionName} ${export_name} "${ARGN}")
ENDMACRO()

# This Macro allows you to set the rewrite number
MACRO(VersionMajorSet versionMajor)
        SET(vMajor ${versionMajor})
ENDMACRO()

MACRO(VersionMinorSet versionMinor)
        SET(vMinor ${versionMinor})
ENDMACRO(VersionMinorSet)

MACRO(VersionPatchSet versionPatch)
        SET(vPatch ${versionPatch})
ENDMACRO(VersionPatchSet)

# This Macro calculates the number of tags from your git repo
MACRO(VersionCalculate)
    FIND_PACKAGE(Git)
    IF(GIT_FOUND)
        EXEC_PROGRAM(${GIT_EXECUTABLE} ${CMAKE_SOURCE_DIR} ARGS tag OUTPUT_VARIABLE return)
        STRING(REGEX REPLACE "\n" ";" return "${return}")
        SET(count 0)
        FOREACH(r ${return})
            MATH(EXPR count "${count} + 1")
        ENDFOREACH()
        SET(vMinor ${count})
    ELSE()
        SET(vMinor "X")
    ENDIF()
ENDMACRO()

# This Macro writes your hpp/cpp files
MACRO(VersionWrite vProjectName export_name)
    SET(include_list "${ARGN}")
    FOREACH(il ${include_list})
        SET(includes "${includes}\n\#include \"${il}\"")
    ENDFOREACH()
    FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${vProjectName}Version.hpp
"/* Current Version of ${vProjectName}
 * Major is: ${vMajor}
 * Minor is: ${vMinor}
 * Patch is: ${vPatch}
 */
${includes}
\#include \"ProjectVersion.hpp\"
extern ${export_name} ProjectVersion ${vProjectName}Version;\n"
    )

        FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${vProjectName}Version.cpp
"/* Current Version of ${vProjectName}
 * Make sure to include this file in your built sources
 */
\#include \"${vProjectName}Version.hpp\"
ProjectVersion ${vProjectName}Version = ProjectVersion(\"${vProjectName}\", \"${vMajor}\", \"${vMinor}\", \"${vPatch}\");\n"
        )
ENDMACRO()

repository: Kitware/VTK

repo_name: Kitware/VTK

gha_license_id: NOASSERTION

extension: cmake


text:
SUMMARY = "Basic python packages deployed in Elk Audio OS devices"
HOMEPAGE = "https://github.com/elk-audio/meta-elk"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/GPL-2.0-only;md5=801f80980d171dd6425610833a22dbe6"

inherit packagegroup

RDEPENDS_packagegroup-elk-python-basic = "\
    python3 \
    python3-pip \
    pyliblo \
    python-alsaseq \
    python3-grpcio \
    python3-grpcio-tools \
    python3-protobuf \
    python3-elkpy \
"

repository: elk-audio/meta-elk

repo_name: elk-audio/meta-elk

branch_name: refs/heads/hardknott

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
inherit autotools pkgconfig gconf

DESCRIPTION = "GTK PPP dialing tool"
DEPENDS = "gconf gtk+ libglade gettext ppp gpe-su"
RDEPENDS_${PN} = "ppp gconf gpe-su"
SECTION = "gpe"
PRIORITY = "optional"

PR = "r5"

SRC_URI = "http://familiar.handhelds.org/source/v0.8.2/${PN}-${PV}.tar.gz \
           file://gkdial-pgpe.patch \
           file://gkdial-ungnome.patch;striplevel=0 \
           file://gkdial-gladedir.patch;striplevel=0 \
           file://gkdial-gpepda.patch \
           file://gkdial.desktop \
           file://gkdial.png"

FILES_${PN} = "${sysconfdir}/chatscripts ${bindir} ${datadir}/pixmaps ${datadir}/applications"
FILES_${PN} += " ${datadir}/gkdial ${datadir}/gkdial/glade ${sysconfdir}/gconf/schemas"

CFLAGS_append = " -I${STAGING_KERNEL_DIR}/include -D_GNU_SOURCE"
LDFLAGS_append = " -Wl,--export-dynamic"

do_install_append () {
        mkdir -p  ${D}${datadir}/pixmaps
        install -m 0644 ${WORKDIR}/gkdial.png ${D}${datadir}/pixmaps/gkdial.png
        mkdir -p  ${D}${datadir}/applications
        install -m 0644 ${WORKDIR}/gkdial.desktop ${D}${datadir}/applications/gkdial.desktop
	mkdir -p ${D}${sysconfdir}/chatscripts
        mkdir -p ${D}${sysconfdir}/gconf/schemas
        install -m 0644 ${S}/gkdial.schemas ${D}${sysconfdir}/gconf/schemas/gkdial.schemas
}

SRC_URI[md5sum] = "b21c6f87b16e398a188a2ed7c5dcd387"
SRC_URI[sha256sum] = "851ce45628729684bfcb2fab53f18e9be8fecb5ec8b6805071706a0e8f5bf983"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
@article{li_fast_2010,
  title = {Fast and accurate long-read alignment with {Burrows}–{Wheeler} transform},
  volume = {26},
  issn = {1367-4803, 1460-2059},
  url = {http://bioinformatics.oxfordjournals.org/content/26/5/589},
  doi = {10.1093/bioinformatics/btp698},
  abstract = {Motivation: Many programs for aligning short sequencing reads to a reference genome have been developed in the last 2 years. Most of them are very efficient for short reads but inefficient or not applicable for reads {\textgreater}200 bp because the algorithms are heavily and specifically tuned for short queries with low sequencing error rate. However, some sequencing platforms already produce longer reads and others are expected to become available soon. For longer reads, hashing-based software such as BLAT and SSAHA2 remain the only choices. Nonetheless, these methods are substantially slower than short-read aligners in terms of aligned bases per unit time.
    Results: We designed and implemented a new algorithm, Burrows-Wheeler Aligner's Smith-Waterman Alignment (BWA-SW), to align long sequences up to 1 Mb against a large sequence database (e.g. the human genome) with a few gigabytes of memory. The algorithm is as accurate as SSAHA2, more accurate than BLAT, and is several to tens of times faster than both.
      Availability: http://bio-bwa.sourceforge.net
      Contact: rd@sanger.ac.uk},
  language = {en},
  number = {5},
  urldate = {2016-05-12},
  journal = {Bioinformatics},
  author = {Li, Heng and Durbin, Richard},
  month = mar,
  year = {2010},
  pmid = {20080505},
  pages = {589--595}
}

@article{li_fast_2009,
  title = {Fast and accurate short read alignment with {Burrows}-{Wheeler} transform},
  volume = {25},
  issn = {1367-4811},
  doi = {10.1093/bioinformatics/btp324},
  abstract = {MOTIVATION: The enormous amount of short reads generated by the new DNA sequencing technologies call for the development of fast and accurate read alignment programs. A first generation of hash table-based methods has been developed, including MAQ, which is accurate, feature rich and fast enough to align short reads from a single individual. However, MAQ does not support gapped alignment for single-end reads, which makes it unsuitable for alignment of longer reads where indels may occur frequently. The speed of MAQ is also a concern when the alignment is scaled up to the resequencing of hundreds of individuals.
    RESULTS: We implemented Burrows-Wheeler Alignment tool (BWA), a new read alignment package that is based on backward search with Burrows-Wheeler Transform (BWT), to efficiently align short sequencing reads against a large reference sequence such as the human genome, allowing mismatches and gaps. BWA supports both base space reads, e.g. from Illumina sequencing machines, and color space reads from AB SOLiD machines. Evaluations on both simulated and real data suggest that BWA is approximately 10-20x faster than MAQ, while achieving similar accuracy. In addition, BWA outputs alignment in the new standard SAM (Sequence Alignment/Map) format. Variant calling and other downstream analyses after the alignment can be achieved with the open source SAMtools software package.
      AVAILABILITY: http://maq.sourceforge.net.},
  language = {eng},
  number = {14},
  journal = {Bioinformatics (Oxford, England)},
  author = {Li, Heng and Durbin, Richard},
  month = jul,
  year = {2009},
  pmid = {19451168},
  pmcid = {PMC2705234},
  keywords = {Algorithms, Genomics, Sequence Alignment, Sequence Analysis, DNA, software},
  pages = {1754--1760}
}
--- EXPECTED ---
Li, H. & Durbin, R. (2009). Fast and accurate short read alignment with Burrows-Wheeler transform. Bioinformatics (Oxford, England), 25(14), 1754—1760. http://dx.doi.org/10.1093/bioinformatics/btp324

Li, H. & Durbin, R. (2010). Fast and accurate long-read alignment with Burrows–Wheeler transform. Bioinformatics, 26(5), 589—595. http://dx.doi.org/10.1093/bioinformatics/btp698

repository: cybernetics/monod

repo_name: cybernetics/monod

extension: bib


text:
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.29.0
// 	protoc        v3.17.3
// source: yandex/cloud/loadtesting/agent/v1/monitoring_service.proto

package agent

import (
	_ "github.com/yandex-cloud/go-genproto/yandex/cloud"
	_ "google.golang.org/genproto/googleapis/api/annotations"
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

type AddMetricRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	ComputeInstanceId string         `protobuf:"bytes,1,opt,name=compute_instance_id,json=computeInstanceId,proto3" json:"compute_instance_id,omitempty"`
	JobId             string         `protobuf:"bytes,3,opt,name=job_id,json=jobId,proto3" json:"job_id,omitempty"`
	Chunks            []*MetricChunk `protobuf:"bytes,4,rep,name=chunks,proto3" json:"chunks,omitempty"`
	AgentInstanceId   string         `protobuf:"bytes,5,opt,name=agent_instance_id,json=agentInstanceId,proto3" json:"agent_instance_id,omitempty"`
}

func (x *AddMetricRequest) Reset() {
	*x = AddMetricRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *AddMetricRequest) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*AddMetricRequest) ProtoMessage() {}

func (x *AddMetricRequest) ProtoReflect() protoreflect.Message {
	mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use AddMetricRequest.ProtoReflect.Descriptor instead.
func (*AddMetricRequest) Descriptor() ([]byte, []int) {
	return file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescGZIP(), []int{0}
}

func (x *AddMetricRequest) GetComputeInstanceId() string {
	if x != nil {
		return x.ComputeInstanceId
	}
	return ""
}

func (x *AddMetricRequest) GetJobId() string {
	if x != nil {
		return x.JobId
	}
	return ""
}

func (x *AddMetricRequest) GetChunks() []*MetricChunk {
	if x != nil {
		return x.Chunks
	}
	return nil
}

func (x *AddMetricRequest) GetAgentInstanceId() string {
	if x != nil {
		return x.AgentInstanceId
	}
	return ""
}

type MetricChunk struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data         []*Metric `protobuf:"bytes,1,rep,name=data,proto3" json:"data,omitempty"`
	Timestamp    int64     `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
	Comment      string    `protobuf:"bytes,3,opt,name=comment,proto3" json:"comment,omitempty"`
	InstanceHost string    `protobuf:"bytes,4,opt,name=instance_host,json=instanceHost,proto3" json:"instance_host,omitempty"`
}

func (x *MetricChunk) Reset() {
	*x = MetricChunk{}
	if protoimpl.UnsafeEnabled {
		mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *MetricChunk) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*MetricChunk) ProtoMessage() {}

func (x *MetricChunk) ProtoReflect() protoreflect.Message {
	mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use MetricChunk.ProtoReflect.Descriptor instead.
func (*MetricChunk) Descriptor() ([]byte, []int) {
	return file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescGZIP(), []int{1}
}

func (x *MetricChunk) GetData() []*Metric {
	if x != nil {
		return x.Data
	}
	return nil
}

func (x *MetricChunk) GetTimestamp() int64 {
	if x != nil {
		return x.Timestamp
	}
	return 0
}

func (x *MetricChunk) GetComment() string {
	if x != nil {
		return x.Comment
	}
	return ""
}

func (x *MetricChunk) GetInstanceHost() string {
	if x != nil {
		return x.InstanceHost
	}
	return ""
}

type Metric struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	MetricType  string  `protobuf:"bytes,1,opt,name=metric_type,json=metricType,proto3" json:"metric_type,omitempty"`
	MetricName  string  `protobuf:"bytes,2,opt,name=metric_name,json=metricName,proto3" json:"metric_name,omitempty"`
	MetricValue float64 `protobuf:"fixed64,3,opt,name=metric_value,json=metricValue,proto3" json:"metric_value,omitempty"`
}

func (x *Metric) Reset() {
	*x = Metric{}
	if protoimpl.UnsafeEnabled {
		mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[2]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *Metric) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*Metric) ProtoMessage() {}

func (x *Metric) ProtoReflect() protoreflect.Message {
	mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[2]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use Metric.ProtoReflect.Descriptor instead.
func (*Metric) Descriptor() ([]byte, []int) {
	return file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescGZIP(), []int{2}
}

func (x *Metric) GetMetricType() string {
	if x != nil {
		return x.MetricType
	}
	return ""
}

func (x *Metric) GetMetricName() string {
	if x != nil {
		return x.MetricName
	}
	return ""
}

func (x *Metric) GetMetricValue() float64 {
	if x != nil {
		return x.MetricValue
	}
	return 0
}

type AddMetricResponse struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	MetricTrailId string `protobuf:"bytes,1,opt,name=metric_trail_id,json=metricTrailId,proto3" json:"metric_trail_id,omitempty"`
	Code          int64  `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
}

func (x *AddMetricResponse) Reset() {
	*x = AddMetricResponse{}
	if protoimpl.UnsafeEnabled {
		mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[3]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *AddMetricResponse) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*AddMetricResponse) ProtoMessage() {}

func (x *AddMetricResponse) ProtoReflect() protoreflect.Message {
	mi := &file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[3]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use AddMetricResponse.ProtoReflect.Descriptor instead.
func (*AddMetricResponse) Descriptor() ([]byte, []int) {
	return file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescGZIP(), []int{3}
}

func (x *AddMetricResponse) GetMetricTrailId() string {
	if x != nil {
		return x.MetricTrailId
	}
	return ""
}

func (x *AddMetricResponse) GetCode() int64 {
	if x != nil {
		return x.Code
	}
	return 0
}

var File_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto protoreflect.FileDescriptor

var file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDesc = []byte{
	0x0a, 0x3a, 0x79, 0x61, 0x6e, 0x64, 0x65, 0x78, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x6c,
	0x6f, 0x61, 0x64, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74,
	0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x5f, 0x73,
	0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x21, 0x79, 0x61,
	0x6e, 0x64, 0x65, 0x78, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x74,
	0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x1a,
	0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f,
	0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1d, 0x79,
	0x61, 0x6e, 0x64, 0x65, 0x78, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x76, 0x61, 0x6c, 0x69,
	0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xfd, 0x01, 0x0a,
	0x10, 0x41, 0x64, 0x64, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
	0x74, 0x12, 0x38, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x70, 0x75, 0x74, 0x65, 0x5f, 0x69, 0x6e, 0x73,
	0x74, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x08,
	0x8a, 0xc8, 0x31, 0x04, 0x3c, 0x3d, 0x35, 0x30, 0x52, 0x11, 0x63, 0x6f, 0x6d, 0x70, 0x75, 0x74,
	0x65, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x06, 0x6a,
	0x6f, 0x62, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x0c, 0xe8, 0xc7, 0x31,
	0x01, 0x8a, 0xc8, 0x31, 0x04, 0x3c, 0x3d, 0x35, 0x30, 0x52, 0x05, 0x6a, 0x6f, 0x62, 0x49, 0x64,
	0x12, 0x4e, 0x0a, 0x06, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b,
	0x32, 0x2e, 0x2e, 0x79, 0x61, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e,
	0x6c, 0x6f, 0x61, 0x64, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x61, 0x67, 0x65, 0x6e,
	0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x43, 0x68, 0x75, 0x6e, 0x6b,
	0x42, 0x06, 0x82, 0xc8, 0x31, 0x02, 0x3e, 0x30, 0x52, 0x06, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x73,
	0x12, 0x34, 0x0a, 0x11, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e,
	0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x08, 0x8a, 0xc8, 0x31,
	0x04, 0x3c, 0x3d, 0x35, 0x30, 0x52, 0x0f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x73, 0x74,
	0x61, 0x6e, 0x63, 0x65, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x22, 0xb7, 0x01, 0x0a,
	0x0b, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x43, 0x68, 0x75, 0x6e, 0x6b, 0x12, 0x45, 0x0a, 0x04,
	0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x79, 0x61, 0x6e,
	0x64, 0x65, 0x78, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x65,
	0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4d,
	0x65, 0x74, 0x72, 0x69, 0x63, 0x42, 0x06, 0x82, 0xc8, 0x31, 0x02, 0x3e, 0x30, 0x52, 0x04, 0x64,
	0x61, 0x74, 0x61, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70,
	0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d,
	0x70, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01,
	0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x29, 0x0a, 0x0d, 0x69,
	0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01,
	0x28, 0x09, 0x42, 0x04, 0xe8, 0xc7, 0x31, 0x01, 0x52, 0x0c, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e,
	0x63, 0x65, 0x48, 0x6f, 0x73, 0x74, 0x22, 0x79, 0x0a, 0x06, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63,
	0x12, 0x25, 0x0a, 0x0b, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18,
	0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xe8, 0xc7, 0x31, 0x01, 0x52, 0x0a, 0x6d, 0x65, 0x74,
	0x72, 0x69, 0x63, 0x54, 0x79, 0x70, 0x65, 0x12, 0x25, 0x0a, 0x0b, 0x6d, 0x65, 0x74, 0x72, 0x69,
	0x63, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x04, 0xe8, 0xc7,
	0x31, 0x01, 0x52, 0x0a, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x21,
	0x0a, 0x0c, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03,
	0x20, 0x01, 0x28, 0x01, 0x52, 0x0b, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75,
	0x65, 0x22, 0x4f, 0x0a, 0x11, 0x41, 0x64, 0x64, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, 0x65,
	0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x26, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63,
	0x5f, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
	0x0d, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x72, 0x61, 0x69, 0x6c, 0x49, 0x64, 0x12, 0x12,
	0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x63, 0x6f,
	0x64, 0x65, 0x32, 0xc8, 0x01, 0x0a, 0x11, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e,
	0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0xb2, 0x01, 0x0a, 0x09, 0x41, 0x64, 0x64,
	0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x12, 0x33, 0x2e, 0x79, 0x61, 0x6e, 0x64, 0x65, 0x78, 0x2e,
	0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e,
	0x67, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x4d, 0x65,
	0x74, 0x72, 0x69, 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x34, 0x2e, 0x79, 0x61,
	0x6e, 0x64, 0x65, 0x78, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x74,
	0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e,
	0x41, 0x64, 0x64, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
	0x65, 0x22, 0x3a, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x34, 0x3a, 0x01, 0x2a, 0x22, 0x2f, 0x2f, 0x6c,
	0x6f, 0x61, 0x64, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74,
	0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x73, 0x2f,
	0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x42, 0x74, 0x0a,
	0x25, 0x79, 0x61, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x70,
	0x69, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x61, 0x67,
	0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x5a, 0x4b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
	0x6f, 0x6d, 0x2f, 0x79, 0x61, 0x6e, 0x64, 0x65, 0x78, 0x2d, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f,
	0x67, 0x6f, 0x2d, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x79, 0x61, 0x6e, 0x64,
	0x65, 0x78, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x6c, 0x6f, 0x61, 0x64, 0x74, 0x65, 0x73,
	0x74, 0x69, 0x6e, 0x67, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x61, 0x67,
	0x65, 0x6e, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescOnce sync.Once
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescData = file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDesc
)

func file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescGZIP() []byte {
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescOnce.Do(func() {
		file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescData)
	})
	return file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDescData
}

var file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_goTypes = []interface{}{
	(*AddMetricRequest)(nil),  // 0: yandex.cloud.loadtesting.agent.v1.AddMetricRequest
	(*MetricChunk)(nil),       // 1: yandex.cloud.loadtesting.agent.v1.MetricChunk
	(*Metric)(nil),            // 2: yandex.cloud.loadtesting.agent.v1.Metric
	(*AddMetricResponse)(nil), // 3: yandex.cloud.loadtesting.agent.v1.AddMetricResponse
}
var file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_depIdxs = []int32{
	1, // 0: yandex.cloud.loadtesting.agent.v1.AddMetricRequest.chunks:type_name -> yandex.cloud.loadtesting.agent.v1.MetricChunk
	2, // 1: yandex.cloud.loadtesting.agent.v1.MetricChunk.data:type_name -> yandex.cloud.loadtesting.agent.v1.Metric
	0, // 2: yandex.cloud.loadtesting.agent.v1.MonitoringService.AddMetric:input_type -> yandex.cloud.loadtesting.agent.v1.AddMetricRequest
	3, // 3: yandex.cloud.loadtesting.agent.v1.MonitoringService.AddMetric:output_type -> yandex.cloud.loadtesting.agent.v1.AddMetricResponse
	3, // [3:4] is the sub-list for method output_type
	2, // [2:3] is the sub-list for method input_type
	2, // [2:2] is the sub-list for extension type_name
	2, // [2:2] is the sub-list for extension extendee
	0, // [0:2] is the sub-list for field type_name
}

func init() { file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_init() }
func file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_init() {
	if File_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*AddMetricRequest); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*MetricChunk); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*Metric); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*AddMetricResponse); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   4,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_goTypes,
		DependencyIndexes: file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_depIdxs,
		MessageInfos:      file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_msgTypes,
	}.Build()
	File_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto = out.File
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_rawDesc = nil
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_goTypes = nil
	file_yandex_cloud_loadtesting_agent_v1_monitoring_service_proto_depIdxs = nil
}

repository: yandex-cloud/go-genproto

repo_name: yandex-cloud/go-genproto


text:
package main

import (
	"net";
	"runloop";
	"plugins";
	"core";

	// Plugins are imported so their init() functions are called
	_ "admin";
	_ "bouncer";
	_ "ping";
)

func main() {
	addr, _		:= net.ResolveTCPAddr("0.0.0.0:1234");
	listen, _	:= net.ListenTCP("tcp", addr);
	server, _	:= net.Dial("tcp", "", "chat.freenode.net:6667");

	core.AddNetwork("freenode", server, listen);

	plugins.Enable("admin");
	plugins.Enable("bouncer");
	plugins.Enable("ping");

	runloop.Run();
}

repository: stefanha/bouncin

repo_name: stefanha/bouncin


text:
# Copyright (C) 2018 GENIVI Alliance
# Released under the MIT license (see COPYING.MIT for the terms)

require genivi-dev-platform-core.bb

DESCRIPTION = "GENIVI Development Platform IVI image"

IMAGE_INSTALL_append = " \
    packagegroup-abstract-component-p1 \
    packagegroup-placeholder-component-p1 \
    packagegroup-specific-component-p2 \
    packagegroup-abstract-component-p2 \
    packagegroup-specific-component-p1 \
    packagegroup-gdp-am-demo \
    packagegroup-gdp-browser \
    packagegroup-gdp-hmi \
    packagegroup-gdp-qt5 \
    packagegroup-gdp-rvi \
    packagegroup-gdp-vsi \
    packagegroup-gdp-sdl \
    packagegroup-gdp-cdl \
"

repository: GENIVI/genivi-dev-platform

repo_name: GENIVI/genivi-dev-platform

gha_language: Shell


text:
package hitch

// This file is full of helpful traversal methods.
// It's considered a practical truism that lineages are the organizational unit
// for actual on-disk storage, so generally those are loaded, and then we do
// traversals in-memory from there.

import (
	"fmt"

	"github.com/warpfork/go-errcat"

	api "github.com/polydawn/go-timeless-api"
)

// LineagePluckReleaseByName traverses a linage and returns a release by name.
// This is a useful function because the serial form of release catalogs
// stores them in an ordered array.
//
// An error may be returned of category LookupError.
//
// A pointer is returned to express maybe-ness; mutating it has no effect.
func LineagePluckReleaseByName(lin api.Lineage, releaseName api.ReleaseName) (*api.Release, error) {
	for _, rel := range lin.Releases {
		if rel.Name == releaseName {
			return &rel, nil
		}
	}
	return nil, errcat.ErrorDetailed(ErrNoSuchRelease,
		fmt.Sprintf("no such release %q in lineage %q", releaseName, lin.Name),
		map[string]string{
			"ref": api.ItemRef{lin.Name, releaseName, ""}.String(),
		},
	)
}

// LineagePluckReleaseItem traverses a lineage and returns a wareID looked up
// by release and item label.
//
// An error may be returned of category LookupError.
//
// A pointer is returned to express maybe-ness; mutating it has no effect.
func LineagePluckReleaseItem(lin api.Lineage, releaseName api.ReleaseName, itemName api.ItemName) (*api.WareID, error) {
	rel, err := LineagePluckReleaseByName(lin, releaseName)
	if err != nil {
		return nil, err
	}
	if item, ok := rel.Items[itemName]; ok {
		return &item, nil
	}
	return nil, errcat.ErrorDetailed(ErrNoSuchItem,
		fmt.Sprintf("no such item %q in release %q", itemName, api.ItemRef{lin.Name, releaseName, ""}.String()),
		map[string]string{
			"ref": api.ItemRef{lin.Name, releaseName, itemName}.String(),
		},
	)
}

repository: polydawn/go-timeless-api

repo_name: polydawn/go-timeless-api


text:
/*
 * Copyright 2020-2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Package common implements mep server common functionalities
package common

import (
	"encoding/json"
	"fmt"

	"mepserver/common/models"
	"net/http"
	"strconv"
	"strings"

	"github.com/apache/servicecomb-service-center/pkg/log"
	"github.com/apache/servicecomb-service-center/pkg/rest"
	"github.com/apache/servicecomb-service-center/server/core/proto"
	error2 "github.com/apache/servicecomb-service-center/server/error"
	"github.com/apache/servicecomb-service-center/server/rest/controller"

	"mepserver/common/arch/workspace"
	"mepserver/common/util"
)

// SendHttpRsp holds the http response building parameters
type SendHttpRsp struct {
	HttpErrInf *proto.Response `json:"httpErrInf,in"`
	R          *http.Request   `json:"r,in"`
	workspace.TaskBase
	W          http.ResponseWriter `json:"w,in"`
	HttpRsp    interface{}         `json:"httpRsp,in"`
	StatusCode int
}

// OnRequest builds an http response based on the input provided
func (t *SendHttpRsp) OnRequest(data string) workspace.TaskCode {
	// remove service-center server header
	t.W.Header().Del(util.ServerHeader)

	failureEventLogFormat := "Response Message for ClientIP [%s] AppInstanceId [%s] Operation [%s] Resource " +
		"[%s] Result [Failure : %s]."
	successEventLogFormat := "Response Message for ClientIP [%s] AppInstanceId [%s] Operation [%s] Resource " +
		"[%s] Result [Success]."

	errInfo := t.GetSerErrInfo()
	if errInfo == nil {
		body := &models.ProblemDetails{
			Title:  "Internal Server Error",
			Status: uint32(util.RemoteServerErr),
			Detail: "server internal function failed",
		}
		log.Infof(failureEventLogFormat, util.GetClientIp(t.R), util.GetAppInstanceId(t.R), util.GetMethodFromReq(t.R),
			util.GetHttpResourceInfo(t.R), body.Detail)
		util.HttpErrResponse(t.W, util.RemoteServerErr, body)
		return workspace.TaskFinish
	}

	if errInfo.ErrCode == util.SerErrServiceNotFound && strings.EqualFold(errInfo.Message, "failed to find the instance") {
		t.writeResponse(t.W, t.HttpErrInf, make([]*models.ServiceInfo, 0))
		return workspace.TaskFinish
	}

	if errInfo.ErrCode >= int(workspace.TaskFail) {
		statusCode, httpBody := t.cvtHttpErrInfo(errInfo)
		util.HttpErrResponse(t.W, statusCode, httpBody)
		log.Infof(failureEventLogFormat, util.GetClientIp(t.R), util.GetAppInstanceId(t.R), util.GetMethodFromReq(t.R),
			util.GetHttpResourceInfo(t.R), errInfo.Message)
		return workspace.TaskFinish
	}
	log.Infof(successEventLogFormat, util.GetClientIp(t.R), util.GetAppInstanceId(t.R), util.GetMethodFromReq(t.R),
		util.GetHttpResourceInfo(t.R))
	t.writeResponse(t.W, t.HttpErrInf, t.HttpRsp)
	return workspace.TaskFinish
}

func (t *SendHttpRsp) writeResponse(w http.ResponseWriter, resp *proto.Response, obj interface{}) {
	if resp != nil && resp.GetCode() != proto.Response_SUCCESS {
		controller.WriteError(w, resp.GetCode(), resp.GetMessage())
		return
	}
	if obj == nil {
		w.Header().Set(rest.HEADER_RESPONSE_STATUS, strconv.Itoa(http.StatusExpectationFailed))
		w.Header().Set(rest.HEADER_CONTENT_TYPE, rest.CONTENT_TYPE_JSON)
		w.WriteHeader(http.StatusExpectationFailed)
		return
	}

	objJSON, err := json.Marshal(obj)
	if err != nil {
		controller.WriteError(w, error2.ErrInternal, err.Error())
		return
	}
	w.Header().Set(rest.HEADER_CONTENT_TYPE, rest.CONTENT_TYPE_JSON)
	if t.StatusCode == 0 {
		t.StatusCode = http.StatusOK
	}
	w.Header().Set(rest.HEADER_RESPONSE_STATUS, strconv.Itoa(t.StatusCode))
	w.WriteHeader(t.StatusCode)
	_, err = fmt.Fprintln(w, string(objJSON))
	if err != nil {
		return
	}
}

func (t *SendHttpRsp) cvtHttpErrInfo(errInfo *workspace.SerErrInfo) (int, interface{}) {
	statusCode := http.StatusBadRequest
	var httpBody interface{}
	body := &models.ProblemDetails{
		Title:  "",
		Status: uint32(errInfo.ErrCode),
		Detail: errInfo.Message,
	}
	switch workspace.ErrCode(errInfo.ErrCode) {
	case util.SerErrServiceNotFound:
		body.Title = "Can not found resource"
	case util.SerInstanceNotFound:
		fallthrough
	case util.HeartbeatServiceNotFound:
		fallthrough
	case util.SubscriptionNotFound:
		statusCode = http.StatusNotFound
		body.Title = "Can not found resource"
	case util.EtagMissMatchErr:
		statusCode = http.StatusPreconditionFailed
		body.Title = "Precondition failed"
	case util.RemoteServerErr:
		statusCode = http.StatusServiceUnavailable
		body.Title = "Remote server error"
	case util.AuthorizationValidateErr:
		statusCode = http.StatusUnauthorized
		body.Title = "UnAuthorization"
	case util.SerErrServiceRegFailed:
		body.Title = "Service register failed"
	case util.SerErrServiceInstanceFailed:
		body.Title = "Service instance failed"
	case util.RequestParamErr:
		body.Title = "Request parameter error"
	case util.SubscriptionErr:
		body.Title = "App subscription error"
	case util.ServiceInactive:
		statusCode = http.StatusConflict
		body.Title = "Service is in INACTIVE state"
	case util.ResourceExists:
		statusCode = http.StatusUnprocessableEntity
		body.Title = "Resource already exists"
	case util.DuplicateOperation:
		body.Title = "Duplicate request error"
	case util.ForbiddenOperation:
		statusCode = http.StatusForbidden
		body.Title = "Operation Not Allowed"

	default:
		body.Title = "Bad Request"
	}
	httpBody = body
	return statusCode, httpBody
}


text:
%# -*- coding: utf-8-unix -*-
@book{reinforce,
  author = {R. S. Sutton and A. G. Barto},
  title = {Reinforcement Learning: An Introduction},
  publisher = {MIT Press},
  year = {1998}
}

@inproceedings{benson2010under,
  author = {T. Benson and A. Anand and A. Akella and M. Zhang},
  title = {Understanding data center traffic characteristics},
  journal = {SIGCOMM},
  year = {2010},
}
@inproceedings{benson2010network,
  author = {T. Benson and A. Akella and D. A. Maltz},
  title = {Network traffic characteristics of data centers in the wild},
  journal = {SIGCOMM},
  year = {2010},
}
@inproceedings{netflow2018,
  author = {},
  title = {CISCO IOS NetFlow},
  journal = {CISCO report},
  year = {2018},
}

@inproceedings{wang2014Expeditus,
  author = {P. Wang and H. Xu},
  title = {Expeditus: Distributed load balancing with
global congestion information in data center networks},
  journal = {CoNEXT},
  year = {2014},
}

@inproceedings{maha2014VxLAN,
  author = {M. Mahalingam  },
  title = {Virtual extensible local area network (VXLAN): A framework for overlaying virtualized layer 2 networks over layer 3 networks},
  journal = {Internet Eng. Task Force},
  year = {2014},
}

@inproceedings{guo2009bcube,
  author = {C. Guo  },
  title = {BCube: A high performance, server-centric network
architecture for modular data centers},
  journal = {SIGCOMM},
  year = {2009},
}

@inproceedings{raiciu2011MPTCP,
  author = {C. Raiciu  },
  title = {Improving datacenter performance and robustness with multipath TCP},
  journal = {SIGCOMM},
  year = {2011},
}

@inproceedings{alizadeh2014CONGA,
  author = {M. Alizadeh  },
  title = {CONGA: Distributed congestion-aware load bal- ancing for datacenters},
  journal = {SIGCOMM},
  year = {2014},
}

@inproceedings{he2014Presto,
  author = {K. He  },
  title = {Presto: Edge-based load balancing for fast datacenter networks},
  journal = {SIGCOMM},
  year = {2015},
}

@inproceedings{sen2013LocalFlow,
  author = {S. Sen  },
  title = {Scalable, optimal flow routing in datacenters via local link balancing},
  journal = {CoNEXT},
  year = {2013},
}
@inproceedings{perry2014Fastpass,
  author = {J. Perry  },
  title = {Fastpass: A centralized ‘zero-queue’ datacenter network},
  journal = {SIGCOMM},
  year = {2014},
}
@inproceedings{fares2010hedera,
  author = {M. Al-Fares  },
  title = {Hedera: Dynamic flow scheduling for data center networks},
  journal = {USENIX NSDI},
  year = {2010},
}
@inproceedings{katta2016CLOVE,
  author = {N. Katta  },
  title = {CLOVE: How I learned to stop worrying about the core and love the edge},
  journal = {HotNets},
  year = {2016},
}
@inproceedings{chen2018auto,
  author = {Li Chen and Justinas Lingys and Kai Chen and Feng Liu},
  title = {AuTO: Scaling Deep Reinforcement Learning
for Datacenter-Scale Automatic Tra ic Optimization},
  journal = {SIGCOMM},
  year = {2018},
}
@inproceedings{mysore2009Portland,
  author = {Radhika Niranjan Mysore  },
  title = {PortLand: A Scalable Fault-Tolerant Layer 2 Data Center Network Fabric},
  journal = {SIGCOMM},
  year = {2009},
}

@inproceedings{alizadeh2010dctcp,
  author = {Mohammad Alizadeh  },
  title = {Data Center TCP (DCTCP)},
  journal = {SIGCOMM},
  year = {2010},
}
@inproceedings{bai2015pias,
  author = {Wei Bai  },
  title = {PIAS: Practical Information-Agnostic Flow Scheduling for Commodity Data Centers},
  journal = {USENIX NSDI},
  year = {2015},
}
@inproceedings{mitzen2001power,
  author = {M. Mitzenmacher},
  title = {The power of two choices in randomized load
balancing},
  journal = {IEEE Trans. Parallel Distrib. Syst.},
  year = {2001},
}

@inproceedings{dixit2013towards,
  author = {A. Dixit and F. Hao and S. Mukherjee and T. V. Lakshman and R. Kompella},
  title = {Towards an elastic distributed SDN controller},
  journal = {SIGCOMM},
  year = {2013},
}
@inproceedings{berde2014onos,
  author = {P. Berde  },
  title = {ONOS: Towards an open, distributed SDN OS},
  journal = {Workshop Hot Topics Softw. Defined Netw.},
  year = {2014},
}

@inproceedings{cui2015fmtcp,
  author = {Y. Cui and L. Wang and X. Wang and H. Wang and Y. Wang},
  title = {FMTCP: A foun- tain code-based multipath transmission control protocol},
  journal = {IEEE/ACM Trans. Netw.},
  year = {2015},
}

@inproceedings{Coudron2013AMPTCP,
  author = {M.Coudron and S.Secci and G.Pujolle and P.Raad and P.Gallard},
  title = {Cross-layer cooperation to boost multipath TCP performance in cloud networks},
  journal = {IEEE CloudNet},
  year = {2013},
}

@inproceedings{koomey2011growth,
  author = {J. Koomey},
  title = {Growth in Data Center Electricity Use 2005 to 2010},
  journal = {Analytical Press},
  year = {2011},
}

@inproceedings{zhang2011modeling,
  author = {J. Zhang and F. Ren and C. Lin},
  title = {Modeling and understanding TCP incast in data center networks},
  journal = {INFOCOM},
  year = {2011},
}

@inproceedings{wang2014rethinking,
  author = {T. Wang and Z. Su and Y. Xia and M. Hamdi},
  title = {Rethinking the data center networking: Architecture, network protocols, and resource sharing},
  journal = {IEEE Access},
  year = {2014},
}
@inproceedings{costa2012camcube,
  author = {P. Costa},
  title = {CamCube: Rethinking the data center cluster},
  journal = {Workshop Trends High Perform. Distrib. Comput.},
  year = {2012},
}
@inproceedings{alfares2008fattree,
  author = {M. Al-Fares and A. Loukissas and A. Vahdat},
  title = {A scalable, commodity data center network architecture},
  journal = {SIGCOMM},
  year = {2008},
}
@inproceedings{greenberg2009vl2,
  author = {A. Greenberg  },
  title = {VL2: A scalable and flexible data center network},
  journal = {SIGCOMM},
  year = {2009},
}
@inproceedings{guo2008dcell,
  author = {C. Guo  },
  title = {Dcell: A scalable and fault-tolerant network structure for data centers},
  journal = {SIGCOMM},
  year = {2008},
}
@inproceedings{alphago,
  author = {David Silver  },
  title = {Mastering the game of Go with deep neural network and tree search},
  journal = {Nature},
  year = {2016},
}

@inproceedings{docker,
  %author = {C. Guo  },
  title = {Build and run Docker containers leveraging NVIDIA GPUs},
  journal = {https://github.com/NVIDIA/nvidia-docker},
  year = {2018},
}

@inproceedings{tensorflow,
  %author = {C. Guo  },
  title = {API Documentation: TensorFlow},
  journal = {https://www. tensor ow.org/api_docs/},
  year = {2017},
}
@inproceedings{niu2010cell,
  author = {Z. Niu and Y. Wu and J. Gong  },
  title = {Cell zooming for cost-efficient green cellular networks},
  journal = {IEEE Commun. Mag.},
  year = {2010},
}
@inproceedings{zhang2018survey,
  author = {Jiao Zhang and F. Richard Yu and Shuo Wang  },
  title = {Load Balancing in Data Center Networks: A Survey},
  journal = {IEEE COMMUNICATIONS SURVEYS & TUTORIALS},
  year = {2018},
}

@inproceedings{khodashenas20165g,
  author = {P. S. Khodashenas and J. Aznar and A. Legarrea  },
  title = {5G Network Challenges and Realization Insights},
  journal = {ICTON},
  year = {2016},
}
@inproceedings{tsai2017load,
  author = {Chin Tsai and Melody Moh},
  title = {Load Balancing in 5G Cloud Radio Access Networks Supporting IoT Communications for Smart Communities},
  journal = {ISSPIT},
  year = {2017},
}
@inproceedings{lin2010efficient,
  author = {X. Lin and S. Wang},
  title = {Efficient Remote Radio Head Switching Scheme in Cloud Radio Access Network: A Load Balancing Perspective},
  journal = {INFOCOM},
  year = {2017},
}

@inproceedings{shah2015generic,
  author = {B. Shahriari and M. Moh},
  title = {Generic Online Learning for Partial Visible Dynamic Environment with Delayed Feedback - Online Learning for 5G C-RAN Load-Balancer},
  journal = {HPCS},
  year = {2017},
}
@inproceedings{hong2006dns,
  author = {Y. S. Hong and J.H. No and S. Y. Kim},
  title = {DNS-based load balancing in distributed Web-server systems},
  journal = {WCCIA},
  year = {2006},
}
@inproceedings{wang2016novel,
  author = {Z. Wang and C. Chen and H. Li and D. Dong and T. Tarn},
  title = {A novel incremental learning scheme for reinforcement learning in dynamic environments},
  journal = {WCICA},
  year = {2016},
}
@inproceedings{ghorbani2015drill,
  author = {S. Ghorbani  },
  title = {Micro load balancing in data centers with DRILL},
  journal = {HotNets},
  year = {2015},
}

@journal{bengio2011onthe,
  author = {Y. Bengio and O. Delalleau},
  title = {On the expressive power of deep architectures},
  journal = {Algorithmic Learning Theory},
  year = {2011},
}

@inproceedings{ran2015optimal,
  author = {C. Ran and S. Wang and C. Wang},
  title = {Optimal load balancing in cloud radio access networks},
  journal = {WCNC},
  year = {2015},
}
@inproceedings{ioffe2015batch,
  author = {Ioffe Sergey and Szegedy Christian},
  title = {Batch normalization: Accelerating deep network training by reducing internal covariate shift},
  journal = {ICML},
  year = {2015},
}

@inproceedings{uhlenbeck1930on,
  author = {Uhlenbeck George and Ornstein Leonard},
  title = {On the theory of the brownian motion},
  journal = {Physical review},
  year = {1930},
}

@inproceedings{hado2010double,
  author = {Hado van Hasselt},
  title = {Double Q-learning},
  journal = {NIPS},
  year = {2010},
}
@inproceedings{hado2016deep,
  author = {Hado van Hasselt and Arthur Guez and David Silver},
  title = {Deep Reinforcement Learning with Double Q-learning},
  journal = {AAAI},
  year = {2016},
}
@inproceedings{timothy2016cont,
  author = {Timothy P. Lillicrap and Jonathan J. Hunt and Alexander Pritzel  },
  title = {Continuous control with deep reinforcement learning},
  journal = {ICLR},
  year = {2016},
}
@inproceedings{silver2014deter,
  author = {David Silver and Guy Lever and Nicolas Heess  },
  title = {Deterministic Policy Gradient Algorithms},
  journal = {ICML},
  year = {2014},
}
@inproceedings{sutton1999policy,
  author = {Richard S. Sutton and David McAllester and Satinder Singh and Yishay Mansour},
  title = {Policy Gradient Methods for Reinforcement Learning with Function Approximation},
  journal = {NIPS},
  year = {1999},
}

@inproceedings{hado2011double,
  author = {Volodymyr Mnih and Koray Kavukcuoglu and David Silver  },
  title = {Playing Atari with Deep Reinforcement Learning},
  journal = {NIPS},
  year = {2013},
}

@inproceedings{hado2012double,
  author = {Volodymyr Mnih and Koray Kavukcuoglu and David Silver  },
  title = {Human-level control through deep reinforcement learning},
  journal = {Nature},
  volume = {518},
  year = {2015},
  publisher = {Macmillan Publishers}
}

@inproceedings{watkins1988q,
  author = {Watkins Ch. and Dayan P.},
  title = {Q-Learning},
  journal = {Machine Learning},
  year = {1992},
  publisher = {Kluwer Academic Publishers}
}
@book{Meta_CN,
  title = {电磁超介质及其应用},
  address = {北京},
  publisher = {国防工业出版社},
  year = {2008},
  author = {崔万照 and 马伟 and 邱乐德 and 张洪太}
}

@book{JohnD,
  title = {Photonic Crystals: Molding the Flow of Light},
  publisher = {Princeton University Press},
  year = {2008},
  author = {Joannopoulos, J. D. and Johnson, S. G. and Winn, J. N.}
}

@book{IEEE-1363,
  author={IEEE Std 1363-2000},
  title={IEEE Standard Specifications for Public-Key Cryptography},
  address={New York},
  publisher={IEEE},
  year={2000}
}

@inproceedings{chen2007act,
  author = {Chen, H. and Chan, C. T.},
  title = {Acoustic cloaking in three dimensions using acoustic metamaterials},
  journal = {Applied Physics Letters},
  year = {2007},
  volume = {91},
  pages = {183518},
  publisher = {AIP}
}

@inproceedings{chen2007ewi,
  author = {Chen, H. and Wu, B. I. and Zhang, B. and Kong, J. A.},
  title = {Electromagnetic Wave Interactions with a Metamaterial Cloak},
  journal = {Physical Review Letters},
  year = {2007},
  volume = {99},
  pages = {63903},
  number = {6},
  publisher = {APS}
}

@inproceedings{kocher99,
  author={C. Kocher and J. Jaffe and B. Jun},
  title={Differential Power Analysis},
  editor={M. Wiener},
  booktitle={Advances in Cryptology ({CRYPTO}~'99)},
  series={Lecture Notes in Computer Science},
  volume={1666},
  pages={388-397},
  publisher={Springer-Verlag},
  month={9},
  year={1999}
}

@incollection{Krasnogor2004e,
  AUTHOR = {N. Krasnogor},
  TITLE = {Towards robust memetic algorithms},
  BOOKTITLE = {Recent Advances in Memetic Algorithms},
  PUBLISHER = {Springer Berlin Heidelberg},
  YEAR = {2004},
  PAGES = {185-207},
  EDITOR = {W.E. Hart and N. Krasnogor and J.E. Smith},
  VOLUME = {166},
  SERIES = {Studies in Fuzziness and Soft Computing},
  ADDRESS = {New York},
}

@incollection{zjsw,
  AUTHOR = {班固},
  TITLE = {苏武传},
  BOOKTITLE = {传记散文英华},
  PUBLISHER = {湖北人民出版社},
  YEAR = {1998},
  PAGES = {65-69},
  EDITOR = {郑在瀛 and 汪超宏 and 周文复},
  VOLUME = {2},
  SERIES = {新古文观止丛书},
  ADDRESS = {武汉},
}

@inbook{clzs,
  AUTHOR = {阎真},
  TITLE = {沧浪之水},
  CHAPTER = {大人物还是讲人情的},
  PAGES = {185-207},
  PUBLISHER = {人民文学出版社},
  YEAR = {2001},
}

@book{tex,
 author    = {Donald E. Knuth},
 title     = {The {\TeX} Book},
 publisher = {Addison-Wesley Publishing Company},
 address   = {Reading, MA},
 year      = 1989,
 edition   = {15th},
}

@book{companion,
 author    = {Michel Goosens and Frank Mittelbach and Alexander Samarin},
 title     = {The {\LaTeX} Companion},
 publisher = {Addison-Wesley Publishing Company},
 address   = {Reading, MA},
 PAGES = {112--125},
 year      = 1994,
}

@inproceedings{ELIDRISSI94,
  AUTHOR =       {{Chafik El Idrissi}, M. and {Roney}, A. and {Frigon}, C. and
                  {Larzilli{\`e}re}, M.},
  TITLE =        {Measurements of total kinetic-energy released to the {$N=2$}
                  dissociation limit of {H}$_2$ --- evidence of the dissociation
                  of very high vibrational {R}ydberg states of {H}$_2$ by
                  doubly-excited states},
  JOURNAL =      {Chemical Physics Letters},
  PAGES =        {260-266},
  VOLUME =       224,
  NUMBER =       10,
  YEAR =         1994,
}

@inproceedings{MELLINGER96,
  AUTHOR =       {Mellinger, A. and Vidal, C. R. and Jungen, Ch.},
  TITLE =        {Laser reduced fluorescence study of the carbon-monoxide nd
                  triplet {R}ydberg series-experimental results and multichannel
                  quantum-defect analysis},
  JOURNAL =      {J. Chem. Phys.},
  PAGES =        {8913-8921},
  VOLUME =       104,
  NUMBER =       5,
  YEAR =         1996,
}

@inproceedings{SHELL02,
  AUTHOR =       {Michael Shell},
  TITLE =        {How to Use the {IEEEtran \LaTeX} Class},
  JOURNAL =      {Journal of {\LaTeX} Class Files},
  YEAR =         2002,
  VOLUME =       12,
  NUMBER =       4,
  PAGES =        {100--120}
}

@TechReport{NPB2,
  title =        {The {NAS} Parallel Benchmarks 2.0},
  author =       {Alex Woo and David Bailey and Maurice Yarrow and Wijngaart
                  Wijngaart and Tim Harris and William Saphir},
  year =         1995,
  month =        12,
  institution =  {The Pennsylvania State University CiteSeer Archives},
  url =          {http://www.nasa.org/}
}

@INPROCEEDINGS{DPMG,
  author =       {Kim, Sangbum and Woo, Namyoon and Yeom, Heon Y. and Park,
                  Taesoon and Park, Hyoungwoo},
  title =        {Design and {I}mplementation of {D}ynamic {P}rocess
                  {M}anagement for {G}rid-enabled {MPICH}},
  booktitle =    {the 10th European PVM/MPI Users' Group Conference},
  year =         2003,
  address =      {Venice, Italy},
  month =        sep,
}

@INPROCEEDINGS{cnproceed,
  author =       {王重阳 and 黄药师 and 欧阳峰 and 洪七公 and 段皇帝},
  title =        {武林高手论文集},
  booktitle =    {第~$N$~次华山论剑},
  year =         2006,
  address =      {西安, 中国},
  publisher = {中国古籍出版社},
  month =        sep,
}

@inproceedings{cninproceedings,
  AUTHOR =       {贾宝玉 and 林黛玉 and 薛宝钗 and 贾探春},
  TITLE =        {论刘姥姥食量大如牛之现实意义},
  JOURNAL =      {红楼梦杂谈},
  PAGES =        {260--266},
  VOLUME =       224,
  YEAR =         1800,
}

@thesis{zhubajie,
  author =       {猪八戒},
  title =        {论流体食物的持久保存},
  school =       {广寒宫大学},
  year =         2005,
  address =      {北京},
}

@thesis{shaheshang,
  title =        {论流沙河的综合治理},
  author =       {沙和尚},
  school =       {清华大学},
  year =         2005,
  address =      {北京},
}

@thesis{metamori2004,
  author =       {Ashwin Raju Jeyakumar},
  title =        {Metamori: A library for Incremental File Checkpointing},
  school =       {Virgina Tech},
  year =         2004,
  month =        7,
  address =      {Blacksburg},
}

@thesis{FistSystem01,
  AUTHOR =       {Erez Zadok},
  TITLE =        {FiST: A System for Stackable File System Code Generation},
  YEAR =         2001,
  MONTH =        {5},
  SCHOOL =       {Computer Science Department, Columbia University},
  ADDRESS =      {USA}
}

@INBOOK{ColdSources,
  AUTHOR =       {P. Gr{\"o}ning and L. Nilsson and P. Ruffieux and R.
                  Clergereaux and O. Gr{\"o}ning},
  TITLE =        {Encyclopedia of Nanoscience and Nanotechnology},
  pages =        {547--579},
  PUBLISHER =    {American Scientific Publishers},
  YEAR =         2004,
  volume =       1,
}

@phdthesis{bai2008,
	title={信用风险传染模型和信用衍生品的定价},
	author={白云芬},
	year={2008},
	school={上海交通大学},
	address={上海},
}

%萧钰.出版业信息化迈人快车道[EB/OL]. (2001-12-19)[2002-04-15]. http://www.creader.com/news/20011219/200112190019. html.
@inproceedings{xiaoyu2001,
  author =       {萧钰},
  title =        {出版业信息化迈人快车道},
  year =         {2001},
  TypeofLit =    {EB/OL},
  modifydate =   {2001-12-19},
  citedate =     {2002-04-15},
  url =          {http://www.creader.com/news/20011219/200112190019.html},
}

% 在线析出文献
@inproceedings{CHRISTINE1998,
  author =       {Christine, Mlot},
  title =        {Plant physiology: plant biology in the Genome Era},
  journal =      {Science},
  volume =       {281},
  pages =        {331-332},
  year =         {1998},
  TypeofLit =    {J/OL},
  citedate =     {1998-09-23},
  url =           {http://www.sciencemag.org/cgi/collection/anatmorp},
}

@book{RManual,
        Address = {Vienna, Austria},
        Author = {{R Core Team}},
        Note = {{ISBN} 3-900051-07-0},
        Organization = {R Foundation for Statistical Computing},
        title = {R: A Language and Environment for Statistical Computing},
        url = {http://www.R-project.org/},
        Year = {2012},
}
@book{OperatingSys,
        Address = {United States of America},
        Author = {Abraham Silberschatz and Peter Baer Galvin and Greg Gagne},
        Note = {{ISBN} 0-471-69466-5},
        Organization = {John Wiley & Sons. Inc.},
        title = {Operating System Concepts},
        %url = {http://www.R-project.org/},
        Year = {2004},
}

@inproceedings{ma2018coflow,
  author = {马腾，胡宇翔，张校辉},
  title = {基于深度增强学习的数据中心网络coflow调度机制},
  journal = {电子学报},
  year = {2018},
}
@inproceedings{lei2015cran,
  author = {雷秋燕，张治中，程方，胡昊南},
  title = {基于CRAN的5G无线接入网架构},
  journal = {电信科学},
  year = {2015},
}


text:
DESCRIPTION = "A simple recipe to deliver flashlayout files for STM32MP1 platforms"
HOMEPAGE = "https://st.com"
SECTION = "base"
LICENSE = "MPL-2.0"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MPL-2.0;md5=815ca599c9df247a0c7f619bab123dad"

inherit deploy

SRC_URI = "file://FlashLayout_emmc_stm32mp157a-ev1-trusted.tsv.in"

do_compile() {
    sed -e 's/@@IMAGE@@/${IMAGE}/' ${WORKDIR}/${LMP_FLASHLAYOUT}.in > ${WORKDIR}/${LMP_FLASHLAYOUT}
}

do_deploy() {
    install -m 0644 ${WORKDIR}/${LMP_FLASHLAYOUT} ${DEPLOYDIR}
}

addtask do_deploy after do_compile before do_build

repository: ldts/meta-lmp

repo_name: ldts/meta-lmp


text:
package registry

import (
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/terra-project/mantle-sdk/types"
)

func TestNewRegistry(t *testing.T) {
	// single entity
	func() {
		type Entity struct {
			Foo string
			Bar struct {
				Hello  uint64 `index:"hello"`
				Mantle string `index:"custom"`
			}
		}
		indexer := func(q types.Query, c types.Commit) error {
			return nil
		}

		registry := NewRegistry([]types.IndexerRegisterer{
			func(register types.Register) {
				register(
					indexer,
					reflect.TypeOf((*Entity)(nil)),
				)
			},
		})

		assert.Equal(t, 1, len(registry.Indexers))
		assert.Equal(t, 1, len(registry.IndexerOutputs))
		assert.Equal(t, 1, len(registry.Models))
		assert.Equal(t, 2, len(registry.KVIndexMap)) // always includes BaseState

		kvi, ok := registry.KVIndexMap["Entity"]
		assert.True(t, ok)

		assert.NotNil(t, kvi.GetIndexEntry("hello"))
		assert.NotNil(t, kvi.GetIndexEntry("custom"))
	}()

	// slice entity
	func() {
		type Entity struct {
			Foo string
			Bar struct {
				Hello  uint64 `index:"hello"`
				Mantle string `index:"custom"`
			}
		}
		type Entities []Entity

		indexer := func(q types.Query, c types.Commit) error {
			return nil
		}

		registry := NewRegistry([]types.IndexerRegisterer{
			func(register types.Register) {
				register(
					indexer,
					reflect.TypeOf((*Entities)(nil)),
				)
			},
		})

		assert.Equal(t, 1, len(registry.Indexers))
		assert.Equal(t, 1, len(registry.IndexerOutputs))
		assert.Equal(t, 1, len(registry.Models))
		assert.Equal(t, 2, len(registry.KVIndexMap)) // always includes BaseState

		kvi, ok := registry.KVIndexMap["Entities"]
		assert.True(t, ok)

		assert.NotNil(t, kvi.GetIndexEntry("hello"))
		assert.NotNil(t, kvi.GetIndexEntry("custom"))
	}()

	// map entity
	func() {
		type Entity struct {
			Foo string
			Bar struct {
				Hello  uint64 `index:"hello"`
				Mantle string `index:"custom""`
			}
		}
		type Entities map[string]Entity

		indexer := func(q types.Query, c types.Commit) error {
			return nil
		}

		registry := NewRegistry([]types.IndexerRegisterer{
			func(register types.Register) {
				register(
					indexer,
					reflect.TypeOf((*Entities)(nil)),
				)
			},
		})

		assert.Equal(t, 1, len(registry.Indexers))
		assert.Equal(t, 1, len(registry.IndexerOutputs))
		assert.Equal(t, 1, len(registry.Models))
		assert.Equal(t, 2, len(registry.KVIndexMap)) // always includes BaseState

		kvi, ok := registry.KVIndexMap["Entities"]
		assert.True(t, ok)

		assert.NotNil(t, kvi.GetIndexEntry("hello"))
		assert.NotNil(t, kvi.GetIndexEntry("custom"))
	}()

}


text:
package pedersenhash

import (
	"encoding/binary"
	"github.com/QED-it/go-jubjub/pkg/grouphash"
	"github.com/QED-it/go-jubjub/pkg/jubjub"
	"math/big"
)

func divCeil(x,y int) int {
	return (x+y-1)/y
}

type PedersenHasher struct {
	curve *jubjub.Jubjub
	generators []*jubjub.JubjubPoint

	chunksPerGenerator int
}

func NewPedersenHasher() (*PedersenHasher, error) {
	j := jubjub.NewJubjub()

	hasher, err := grouphash.NewGroupHasher([]byte("Zcash_PH"))
	if err != nil {
		return nil, err
	}

	generators := []*jubjub.JubjubPoint{}
	for i := 0; i < 5; i++ {
		msg := make([]byte, 4)
		binary.LittleEndian.PutUint32(msg, uint32(i))

		p, err := hasher.FindGroupHash(msg)
		if err != nil {
			return nil, err
		}

		if err != nil {
			return nil, err
		}
		//fmt.Printf("generator: %v\n", p)
		generators = append(generators, p)
	}

	return &PedersenHasher{
		curve:j,
		generators:generators,
		chunksPerGenerator:63,
	}, nil
}

func (hasher *PedersenHasher) PedersenHashForBits(personalization []bool, bitsToHash []bool) (*jubjub.JubjubPoint, error){
	bits := append(personalization, bitsToHash...)
	sum, err := hasher.curve.Point(big.NewInt(0), big.NewInt(1))
	if err != nil {
		return nil, err
	}
	sumS := big.NewInt(0)
	for i := 0; i < divCeil(len(bits), 3); i++ {
		//fmt.Printf("i: %d\n", i)
		g := hasher.generators[i/(hasher.chunksPerGenerator)]
		chunk := make([]int, 3)
		for j := 0; j < 3; j++ {
			if ((3*i+j) < len(bits)) && bits[3*i+j] {
				chunk[j] = 1
			}
		}

		s := (1-2*chunk[2])*(1+chunk[0] + 2*chunk[1])
		bigS := big.NewInt(int64(s))
		powerOf2 := big.NewInt(2)
		powerOf2.Exp(powerOf2, big.NewInt(int64(4*(i % hasher.chunksPerGenerator))), hasher.curve.JubjubS)
		bigS.Mul(bigS, powerOf2)
		bigS.Mod(bigS, hasher.curve.JubjubS)
		sumS.Add(sumS, bigS)
		//fmt.Printf("chunk = %v, %v\n", chunk, err)
		//fmt.Printf("bigS = %v, %v\n", bigS, err)

		if i % (hasher.chunksPerGenerator) == (hasher.chunksPerGenerator - 1) || i == divCeil(len(bits), 3) - 1{
			withScalar, err := hasher.curve.ScalarMult(sumS, g)
			if err != nil {
				return nil, err
			}
			sum, err = hasher.curve.Add(sum, withScalar)
			if err != nil {
				return nil, err
			}
			sumS = big.NewInt(0)
			//fmt.Printf("i = %d\n", i)
			//fmt.Printf("withScalar = %v\n", withScalar)
			//fmt.Printf("sum = %v\n", sum)
		}
		//fmt.Printf("sum = %v, %v\n", sum, err)
	}

	return sum, nil
}

repository: QED-it/go-jubjub

repo_name: QED-it/go-jubjub


text:
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set(LIBXML2_TARGET external.libxml2)
set(LIBXML2_INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/${LIBXML2_TARGET})
set(LIBXML2_SRC_DIR ${LIBXML2_INSTALL_DIR}/src/${LIBXML2_TARGET})

set(LIBXML2_INCLUDE_DIRS ${LIBXML2_INSTALL_DIR}/include/libxml2)
include_directories(${LIBXML2_INCLUDE_DIRS})

list(APPEND LIBXML2_LIBRARIES xml2)

foreach(lib IN LISTS LIBXML2_LIBRARIES)
  if (MSVC)
    if (CMAKE_BUILD_TYPE MATCHES Debug)
      set(LIB_PATH ${LIBXML2_INSTALL_DIR}/lib/${lib}d.lib)
    else()
      set(LIB_PATH ${LIBXML2_INSTALL_DIR}/lib/${lib}.lib)
    endif()
  else()
    set(LIB_PATH ${LIBXML2_INSTALL_DIR}/lib/lib${lib}.a)
  endif()
  list(APPEND LIBXML2_BUILD_BYPRODUCTS ${LIB_PATH})

  add_library(${lib} STATIC IMPORTED)
  set_property(TARGET ${lib} PROPERTY IMPORTED_LOCATION ${LIB_PATH})
  add_dependencies(${lib} ${LIBXML2_TARGET})
endforeach(lib)

include (ExternalProject)
if (MSVC)
ExternalProject_Add(${LIBXML2_TARGET}
    PREFIX ${LIBXML2_TARGET}
    GIT_REPOSITORY GIT_REPOSITORY https://gitlab.gnome.org/GNOME/libxml2
    GIT_TAG master
    UPDATE_COMMAND ""
    CMAKE_CACHE_ARGS -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}
                     -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER}
    CMAKE_ARGS ${CMAKE_ARGS}
               -DCMAKE_INSTALL_PREFIX=${LIBXML2_INSTALL_DIR}
               -DCMAKE_INSTALL_LIBDIR=lib
			   -DLIBXML2_WITH_PYTHON=OFF
			   -DCMAKE_TOOLCHAIN_FILE=F:/dev/vcpkg/scripts/buildsystems/vcpkg.cmake
			   "-DCMAKE_C_FLAGS=${LIBXML2_CFLAGS} -lclang_rt.fuzzer-i386.lib -lclang_rt.asan_dynamic-i386.lib"
			   "-DCMAKE_CXX_FLAGS=${LIBXML2_CXXFLAGS} -lclang_rt.asan_dll_thunk-i386.lib"
    BUILD_BYPRODUCTS ${LIBXML2_BUILD_BYPRODUCTS}
)
else ()
ExternalProject_Add(${LIBXML2_TARGET}
    PREFIX ${LIBXML2_TARGET}
    GIT_REPOSITORY GIT_REPOSITORY https://gitlab.gnome.org/GNOME/libxml2
    GIT_TAG master
    UPDATE_COMMAND ""
    CONFIGURE_COMMAND ${LIBXML2_SRC_DIR}/autogen.sh --without-python
                                                    --prefix=${LIBXML2_INSTALL_DIR}
                                                    CC=${CMAKE_C_COMPILER}
                                                    CXX=${CMAKE_CXX_COMPILER}
                                                    CFLAGS=${LIBXML2_CFLAGS}
                                                    CXXFLAGS=${LIBXML2_CXXFLAGS}
    BUILD_COMMAND make -j ${CPU_COUNT} all
    INSTALL_COMMAND make install
    BUILD_BYPRODUCTS ${LIBXML2_BUILD_BYPRODUCTS}
)
endif()


text:
require recipes-graphics/xorg-app/xorg-app-common.inc
DEPENDS += " xproto util-macros"
LIC_FILES_CHKSUM = "file://COPYING;md5=ef598adbe241bd0b0b9113831f6e249a"
PE = "1"
PR = "r6"

SRC_URI[md5sum] = "35c6cccbf25a872bdd62bfcb1a73d951"
SRC_URI[sha256sum] = "80887da011ad086fff88bfd16c6d9d5ac7da45ef1bc9d0c192a6f370423370f1"

FILES_${PN} += "${datadir}/X11"

repository: UNIVERSAL-IT-SYSTEMS/meta-oe

repo_name: UNIVERSAL-IT-SYSTEMS/meta-oe


text:
package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {

	resp, err := http.Get("https://golangcode.com")
	if err != nil {
		log.Fatal(err)
	}

	// Print the HTTP Status Code and Status Name
	fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))

	if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
		fmt.Println("HTTP Status is in the 2xx range")
	} else {
		fmt.Println("Argh! Broken")
	}
}

repository: Amitmund/golang

repo_name: Amitmund/golang


text:
@article{peng2017deterministic,
 abstract = {One of the central challenges in realizing multiferroics-based magnetoelectric memories is to switch perpendicular magnetic anisotropy (PMA) with a control voltage. In this study, we demonstrate electrical flipping of magnetization between the out-of-plane and the in-plane directions in (Co/Pt)3/(011) Pb(Mg1/3Nb2/3)O3-PbTiO3 multiferroic heterostructures through a voltage-controllable spin reorientation transition (SRT). The SRT onset temperature can be dramatically suppressed at least 200 K by applying an electric field, accompanied by a giant electric-field-induced effective magnetic anisotropy field ($Δ$Heff) up to 1100 Oe at 100 K. In comparison with conventional strain-mediated magnetoelastic coupling that provides a $Δ$Heff of only 110 Oe, that enormous effective field is mainly related to the interface effect of electric field modification of spin-orbit coupling from Co/Pt interfacial hybridization via strain. Moreover, electric field control of SRT is also achieved at room temperature, resulting in a $Δ$Heff of nearly 550 Oe. In addition, ferroelastically nonvolatile switching of PMA has been demonstrated in this system. E-field control of PMA and SRT in multiferroic heterostructures not only provides a platform to study strain effect and interfacial effect on magnetic anisotropy of the ultrathin ferromagnetic films but also enables the realization of power efficient PMA magnetoelectric and spintronic devices.},
 author = {Peng, Bin and Zhou, Ziyao and Nan, Tianxiang and Dong, Guohua and Feng, Mengmeng and Yang, Qu and Wang, Xinjun and Zhao, Shishun and Xian, Dan and Jiang, Zhuang De and Ren, Wei and Ye, Zuo Guang and Sun, Nian X. and Liu, Ming},
 doi = {10.1021/acsnano.7b01547},
 issn = {1936086X},
 journal = {ACS Nano},
 keywords = {ferromagnetic resonance,magnetoelectric coupling,multiferroic heterostructure,perpendicular magnetic anisotropy,spin reorientation transition,spin-orbit coupling},
 number = {4},
 pages = {4337--4345},
 publisher = {American Chemical Society},
 title = {Deterministic Switching of Perpendicular Magnetic Anisotropy by Voltage Control of Spin Reorientation Transition in (Co/Pt)3/Pb(Mg1/3Nb2/3)O3-PbTiO3 Multiferroic Heterostructures},
 volume = {11},
 year = {2017}
}


text:
SECTION = "console/network"
DEPENDS = "ncurses gnutls gpgme"
DESCRIPTION = "Mutt is a small but very powerful text-based \
MIME mail client. It is highly configurable, and is well-suited \
to the mail power user with advanced features like key \
bindings, keyboard macros, mail threading, regular expression \
searches, and a powerful pattern matching language for selecting \
groups of messages."
LICENSE = "GPL"
PR = "r2"
SRC_URI = "ftp://ftp.mutt.org/mutt/devel/mutt-${PV}.tar.gz \
           file://patch-1.5.19.sidebar.20090522.txt;apply=yes \
	   file://529838-gnutls-autoconf.patch \
           file://makedoc.patch"

S = "${WORKDIR}/mutt-1.5.19"

inherit autotools

EXTRA_OECONF = "--enable-gpgme --with-curses=${STAGING_LIBDIR}/.. \
	        --enable-pop --enable-imap --with-gnutls --enable-nntp"

do_compile_prepend () {
        ${BUILD_CC} doc/makedoc.c -o doc/makedoc
}

SRC_URI[md5sum] = "73b3747bc7f7c805921e8d24ebac693f"
SRC_URI[sha256sum] = "b160baedf2676a4c2c1a5c74049e2c63f00fccff43ee2594367087a08bfd63c8"