text:
package oauth

import (
	"fmt"
	"reflect"
	"testing"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/validation/field"

	configv1 "github.com/openshift/api/config/v1"
)

const wrongConfigMapSecretErrMsg string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')"

func htpasswdIDP() configv1.IdentityProviderConfig {
	return configv1.IdentityProviderConfig{
		Type: configv1.IdentityProviderTypeHTPasswd,
		HTPasswd: &configv1.HTPasswdIdentityProvider{
			FileData: configv1.SecretNameReference{
				Name: "innocent.llama",
			},
		},
	}
}

func TestValidateOAuthSpec(t *testing.T) {
	doubledIdPs := configv1.IdentityProviderConfig{
		Type: configv1.IdentityProviderTypeHTPasswd,
		HTPasswd: &configv1.HTPasswdIdentityProvider{
			FileData: configv1.SecretNameReference{
				Name: "innocent.llama",
			},
		},
		GitLab: &configv1.GitLabIdentityProvider{
			ClientID:     "masterOfInstances",
			ClientSecret: configv1.SecretNameReference{Name: "secret-gitlab-secret"},
			URL:          "https://thisgitlabinstancerighthere.com",
			CA:           configv1.ConfigMapNameReference{Name: "letsencrypt-for-gitlab.instance"},
		},
	}

	type args struct {
		spec configv1.OAuthSpec
	}
	tests := []struct {
		name string
		args args
		want field.ErrorList
	}{
		{
			name: "empty object",
			args: args{
				spec: configv1.OAuthSpec{},
			},
		},
		{
			name: "more than one challenge issuing IdPs",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "htpasswd",
							IdentityProviderConfig: htpasswdIDP(),
						},
						{
							Name:                   "ldap",
							IdentityProviderConfig: ldapIDP(),
						},
					},
				},
			},
		},
		{
			name: "more than one challenge redirecting IdPs",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "sso1",
							IdentityProviderConfig: requestHeaderIDP(true, true),
						},
						{
							Name:                   "sso2",
							IdentityProviderConfig: requestHeaderIDP(true, false),
						},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "identityProviders"), "<omitted>", "only one identity provider can redirect clients requesting an authentication challenge, found: sso1, sso2"),
			},
		},
		{
			name: "mixing challenge issuing and redirecting IdPs",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "sso",
							IdentityProviderConfig: requestHeaderIDP(true, false),
						},
						{
							Name:                   "ldap",
							IdentityProviderConfig: ldapIDP(),
						},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "identityProviders"), "<omitted>", "cannot mix providers that redirect clients requesting auth challenges (sso) with providers issuing challenges to those clients (ldap)"),
			},
		},
		{
			name: "two IdPs with the same name",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "aname",
							IdentityProviderConfig: htpasswdIDP(),
						},
						{
							Name:                   "bname",
							IdentityProviderConfig: htpasswdIDP(),
						},
						{
							Name:                   "aname",
							IdentityProviderConfig: htpasswdIDP(),
						},
						{
							Name:                   "cname",
							IdentityProviderConfig: htpasswdIDP(),
						},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "identityProviders").Index(2).Child("name"), "aname", "must have a unique name"),
			},
		},
		{
			name: "negative token inactivity timeout",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenInactivityTimeout: &metav1.Duration{Duration: -50 * time.Second},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "tokenConfig", "accessTokenInactivityTimeout"), metav1.Duration{Duration: -50 * time.Second}, fmt.Sprintf("the minimum acceptable token timeout value is %d seconds", MinimumInactivityTimeoutSeconds)),
			},
		},
		{
			name: "positive token inactivity timeout",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenInactivityTimeout: &metav1.Duration{Duration: 32578 * time.Second},
					},
				},
			},
		},
		{
			name: "zero token inactivity timeout",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenInactivityTimeout: &metav1.Duration{Duration: 0},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "tokenConfig", "accessTokenInactivityTimeout"), metav1.Duration{Duration: 0 * time.Second}, fmt.Sprintf("the minimum acceptable token timeout value is %d seconds", MinimumInactivityTimeoutSeconds)),
			},
		},
		{
			name: "token inactivity timeout lower than the api constant minimum",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenInactivityTimeout: &metav1.Duration{Duration: 250 * time.Second},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "tokenConfig", "accessTokenInactivityTimeout"), metav1.Duration{Duration: 250 * time.Second}, fmt.Sprintf("the minimum acceptable token timeout value is %d seconds", MinimumInactivityTimeoutSeconds)),
			},
		},
		{
			name: "negative token max age",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenMaxAgeSeconds: -20,
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "tokenConfig", "accessTokenMaxAgeSeconds"), -20, "must be a positive integer or 0"),
			},
		},
		{
			name: "positive token max age",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenMaxAgeSeconds: 213123,
					},
				},
			},
		},
		{
			name: "zero token max age",
			args: args{
				spec: configv1.OAuthSpec{
					TokenConfig: configv1.TokenConfig{
						AccessTokenMaxAgeSeconds: 0,
					},
				},
			},
		},
		{
			name: "template names all messed up",
			args: args{
				spec: configv1.OAuthSpec{
					Templates: configv1.OAuthTemplates{
						Login:             configv1.SecretNameReference{Name: "/this/is/wrong.html"},
						ProviderSelection: configv1.SecretNameReference{Name: "also_wrong"},
						Error:             configv1.SecretNameReference{Name: "the&very+woRst"},
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "templates", "login", "name"), "/this/is/wrong.html", wrongConfigMapSecretErrMsg),
				field.Invalid(field.NewPath("spec", "templates", "providerSelection", "name"), "also_wrong", wrongConfigMapSecretErrMsg),
				field.Invalid(field.NewPath("spec", "templates", "error", "name"), "the&very+woRst", wrongConfigMapSecretErrMsg),
			},
		},
		{
			name: "everything set properly",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "some_httpasswd",
							IdentityProviderConfig: htpasswdIDP(),
						},
						{
							Name:                   "sso",
							IdentityProviderConfig: requestHeaderIDP(false, true),
						},
					},
					TokenConfig: configv1.TokenConfig{
						AccessTokenInactivityTimeout: &metav1.Duration{Duration: 300 * time.Second},
						AccessTokenMaxAgeSeconds:     216000,
					},
					Templates: configv1.OAuthTemplates{
						Login:             configv1.SecretNameReference{Name: "my-login-template"},
						ProviderSelection: configv1.SecretNameReference{Name: "provider-selection.template"},
						Error:             configv1.SecretNameReference{Name: "a.template-with-error"},
					},
				},
			},
		},
		{
			name: "two different IdPs in one object",
			args: args{
				spec: configv1.OAuthSpec{
					IdentityProviders: []configv1.IdentityProvider{
						{
							Name:                   "bad_bad_config",
							IdentityProviderConfig: doubledIdPs,
						},
					},
					TokenConfig: configv1.TokenConfig{
						AccessTokenMaxAgeSeconds: 216000,
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("spec", "identityProviders").Index(0), doubledIdPs, "only one identity provider can be configured in single object"),
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := validateOAuthSpec(tt.args.spec)

			// DeepEqual does not seem to be working well here
			var failedCheck bool
			if len(got) != len(tt.want) {
				failedCheck = true
			} else {
				// Check all the errors
				for i := range got {
					if got[i].Error() != tt.want[i].Error() {
						failedCheck = true
						break
					}
				}
			}

			if failedCheck {
				t.Errorf("validateOAuthSpec() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestValidateIdentityProvider(t *testing.T) {
	type args struct {
		identityProvider configv1.IdentityProvider
		fldPath          *field.Path
	}
	tests := []struct {
		name string
		args args
		want field.ErrorList
	}{
		{
			name: "empty provider needs at least name and type in provider",
			args: args{
				identityProvider: configv1.IdentityProvider{},
			},
			want: field.ErrorList{
				field.Required(field.NewPath("name"), ""),
				field.Required(field.NewPath("type"), ""),
			},
		},
		{
			name: "unknown type name",
			args: args{
				identityProvider: configv1.IdentityProvider{
					Name: "providingProvider",
					IdentityProviderConfig: configv1.IdentityProviderConfig{
						Type: "someText",
					},
				},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("type"), "someText", "not a valid provider type"),
			},
		},
		{
			name: "basic provider",
			args: args{
				identityProvider: configv1.IdentityProvider{
					Name:                   "providingProvider",
					IdentityProviderConfig: htpasswdIDP(),
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := ValidateIdentityProvider(tt.args.identityProvider, tt.args.fldPath)
			// DeepEqual does not seem to be working well here
			var failedCheck bool
			if len(got) != len(tt.want) {
				failedCheck = true
			} else {
				// Check all the errors
				for i := range got {
					if got[i].Error() != tt.want[i].Error() {
						failedCheck = true
						break
					}
				}
			}

			if failedCheck {
				t.Errorf("ValidateIdentityProvider() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestValidateOAuthIdentityProvider(t *testing.T) {
	type args struct {
		clientID        string
		clientSecretRef configv1.SecretNameReference
		fieldPath       *field.Path
	}
	tests := []struct {
		name string
		args args
		want field.ErrorList
	}{
		{
			name: "empty client ID and secret ref",
			args: args{
				clientID:        "",
				clientSecretRef: configv1.SecretNameReference{},
			},
			want: field.ErrorList{
				field.Required(field.NewPath("clientID"), ""),
				field.Required(field.NewPath("clientSecret", "name"), ""),
			},
		},
		{
			name: "improper client secret refname",
			args: args{
				clientID:        "thisBeClient",
				clientSecretRef: configv1.SecretNameReference{Name: "terribleName_forASecret"},
			},
			want: field.ErrorList{
				field.Invalid(field.NewPath("clientSecret", "name"), "terribleName_forASecret", wrongConfigMapSecretErrMsg),
			},
		},
		{
			name: "working example",
			args: args{
				clientID:        "thisBeClient",
				clientSecretRef: configv1.SecretNameReference{Name: "client-secret-hideout"},
			},
			want: field.ErrorList{},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := ValidateOAuthIdentityProvider(tt.args.clientID, tt.args.clientSecretRef, tt.args.fieldPath); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ValidateOAuthIdentityProvider() = %v, want %v", got, tt.want)
			}
		})
	}
}

repository: openshift/kubernetes

repo_name: openshift/kubernetes


text:
package noise

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/oasislabs/ed25519"
	"go.uber.org/zap"
	"io"
	"net"
	"sync"
)

type clientSide bool

const (
	clientSideInbound  clientSide = false
	clientSideOutbound clientSide = true
)

// Client represents an pooled inbound/outbound connection under some node. Should a client successfully undergo
// noise's protocol handshake, information about the peer representative of this client, such as its ID is available.
//
// A clients connection may be closed through (*Client).Close, through the result of a failed handshake, through
// exceeding the max inbound/outbound connection count configured on the clients associated node, through a node
// gracefully being stopped, through a Handler configured on the node returning an error upon recipient of some data,
// or through receiving unexpected/suspicious data.
//
// The lifecycle of a client may be controlled through (*Client).WaitUntilReady, and (*Client).WaitUntilClosed. It
// provably has been useful in writing unit tests where a client instance is used under high concurrency scenarios.
//
// A client in total has three goroutines associated to it: a goroutine responsible for handling writing messages, a
// goroutine responsible for handling the recipient of messages, and a goroutine for handling protocol logic such as
// handshaking/executing Handler's.
type Client struct {
	node *Node

	id ID

	addr string
	conn net.Conn
	side clientSide

	suite cipher.AEAD

	logger struct {
		sync.RWMutex
		*zap.Logger
	}

	reader *connReader
	writer *connWriter

	requests *requestMap

	ready       chan struct{}
	writerDone  chan struct{}
	readerDone  chan struct{}
	handlerDone chan struct{}
	clientDone  chan struct{}

	err struct {
		sync.Mutex
		error
	}

	closeOnce sync.Once
}

func newClient(node *Node) *Client {
	c := &Client{
		node:        node,
		reader:      newConnReader(),
		writer:      newConnWriter(),
		requests:    newRequestMap(),
		ready:       make(chan struct{}),
		writerDone:  make(chan struct{}),
		readerDone:  make(chan struct{}),
		handlerDone: make(chan struct{}),

		clientDone: make(chan struct{}),
	}

	c.SetLogger(node.logger)

	return c
}

// ID returns an immutable copy of the ID of this client, which is established once the client has successfully
// completed the handshake protocol configured from this clients associated node.
//
// ID may be called concurrently.
func (c *Client) ID() ID {
	return c.id
}

// Logger returns the underlying logger associated to this client. It may optionally be set via (*Client).SetLogger.
//
// Logger may be called concurrently.
func (c *Client) Logger() *zap.Logger {
	c.logger.RLock()
	defer c.logger.RUnlock()

	return c.logger.Logger
}

// SetLogger updates the logger instance of this client.
//
// SetLogger may be called concurrently.
func (c *Client) SetLogger(logger *zap.Logger) {
	c.logger.Lock()
	defer c.logger.Unlock()

	c.logger.Logger = logger
}

// Close asynchronously kills the underlying connection and signals all goroutines to stop underlying this client.
//
// Close may be called concurrently.
func (c *Client) Close() {
	c.close()
}

// WaitUntilReady pauses the goroutine to which it was called within until/unless the client has successfully
// completed/failed the handshake protocol configured under the node instance to which this peer was derived from.
//
// It pauses the goroutine by reading from a channel that is closed when the client has successfully completed/failed
// the aforementioned handshake protocol.
//
// WaitUntilReady may be called concurrently.
func (c *Client) WaitUntilReady() {
	c.waitUntilReady()
}

// WaitUntilClosed pauses the goroutine to which it was called within until all goroutines associated to this client
// has been closed. The goroutines associated to this client would only close should:
//
// 1) handshaking failed/succeeded,
// 2) the connection was dropped, or
// 3) (*Client).Close was called.
//
// WaitUntilReady may be called concurrently.
func (c *Client) WaitUntilClosed() {
	c.waitUntilClosed()
}

// Error returns the very first error that has caused this clients connection to have dropped.
//
// Error may be called concurrently.
func (c *Client) Error() error {
	c.err.Lock()
	defer c.err.Unlock()

	return c.err.error
}

func (c *Client) reportError(err error) {
	c.err.Lock()
	defer c.err.Unlock()

	if c.err.error == nil {
		c.err.error = err
	}
}

func (c *Client) close() {
	c.closeOnce.Do(func() {
		c.writer.close()

		if c.conn != nil {
			c.conn.Close()
		}
	})
}

func (c *Client) waitUntilReady() {
	<-c.ready
}

func (c *Client) waitUntilClosed() {
	<-c.clientDone
}

func (c *Client) outbound(ctx context.Context, addr string) {
	c.addr = addr
	c.side = clientSideInbound

	defer func() {
		c.node.outbound.remove(addr)
		close(c.clientDone)
	}()

	var dialer net.Dialer

	conn, err := dialer.DialContext(ctx, "tcp", addr)
	if err != nil {
		c.reportError(err)
		close(c.ready)
		close(c.writerDone)
		close(c.readerDone)
		close(c.handlerDone)
		return
	}

	_ = conn.(*net.TCPConn).SetNoDelay(false)
	_ = conn.(*net.TCPConn).SetWriteBuffer(10000)
	_ = conn.(*net.TCPConn).SetReadBuffer(10000)

	c.conn = conn

	go c.readLoop(conn)
	go c.writeLoop(conn)

	c.handshake(ctx)

	c.handleLoop()

	c.Logger().Debug("Peer connection closed.")

	for _, protocol := range c.node.protocols {
		if protocol.OnPeerDisconnected == nil {
			continue
		}

		protocol.OnPeerDisconnected(c)
	}
}

func (c *Client) inbound(conn net.Conn, addr string) {
	c.addr = addr
	c.conn = conn
	c.side = clientSideOutbound

	defer func() {
		c.node.inbound.remove(addr)
		close(c.clientDone)
	}()

	ctx := context.Background()

	go c.readLoop(conn)
	go c.writeLoop(conn)

	c.handshake(ctx)

	if _, open := <-c.ready; !open && c.Error() != nil {
		close(c.handlerDone)
		c.close()
		return
	}

	c.handleLoop()

	for _, protocol := range c.node.protocols {
		if protocol.OnPeerDisconnected == nil {
			continue
		}

		protocol.OnPeerDisconnected(c)
	}
}

func (c *Client) request(ctx context.Context, data []byte) (message, error) {
	// Figure out an available request nonce.

	ch, nonce, err := c.requests.nextNonce()
	if err != nil {
		return message{}, err
	}

	// Send request.

	if err := c.send(nonce, data); err != nil {
		c.requests.markRequestFailed(nonce)
		return message{}, err
	}

	// Await response.

	var msg message

	select {
	case msg = <-ch:
		if msg.nonce == 0 {
			return message{}, io.EOF
		}
	case <-ctx.Done():
		return message{}, ctx.Err()
	}

	return msg, nil
}

func (c *Client) send(nonce uint64, data []byte) error {
	data = message{nonce: nonce, data: data}.marshal()

	if c.suite != nil {
		var err error

		if data, err = encryptAEAD(c.suite, data); err != nil {
			return err
		}
	}

	c.writer.write(data)

	return nil
}

func (c *Client) recv(ctx context.Context) (message, error) {
	select {
	case data, open := <-c.reader.pending:
		if !open {
			return message{}, io.EOF
		}

		if c.suite != nil {
			var err error

			if data, err = decryptAEAD(c.suite, data); err != nil {
				return message{}, err
			}
		}

		msg, err := unmarshalMessage(data)
		if err != nil {
			return message{}, err
		}

		return msg, nil
	case <-ctx.Done():
		return message{}, ctx.Err()
	}
}

func (c *Client) handshake(ctx context.Context) {
	defer close(c.ready)

	// Generate Ed25519 ephemeral keypair to perform a Diffie-Hellman handshake.

	pub, sec, err := GenerateKeys(nil)
	if err != nil {
		c.reportError(err)
		return
	}

	// Send our Ed25519 ephemeral public key and signature of the message '.__noise_handshake'.

	if err := c.send(0, append(pub[:], sec.Sign([]byte(".__noise_handshake"))...)); err != nil {
		c.reportError(fmt.Errorf("failed to send session handshake: %w", err))
		return
	}

	// Read from our peer their Ed25519 ephemeral public key and signature of the message '.__noise_handshake'.

	msg, err := c.recv(ctx)
	if err != nil {
		c.reportError(err)
		return
	}

	if msg.nonce != 0 {
		c.reportError(fmt.Errorf("got session handshake with nonce %d, but expected nonce to be 0", msg.nonce))
		return
	}

	if len(msg.data) != ed25519.PublicKeySize+ed25519.SignatureSize {
		c.reportError(fmt.Errorf("received invalid number of bytes opening a session: expected %d byte(s), but got %d byte(s)",
			ed25519.PublicKeySize+ed25519.SignatureSize,
			len(msg.data),
		))

		return
	}

	var peerPublicKey PublicKey
	copy(peerPublicKey[:], msg.data[:ed25519.PublicKeySize])

	// Verify ownership of our peers Ed25519 public key by verifying the signature they sent.

	if !peerPublicKey.Verify([]byte(".__noise_handshake"), msg.data[ed25519.PublicKeySize:]) {
		c.reportError(errors.New("could not verify session handshake"))
		return
	}

	// Transform all Ed25519 points to Curve25519 points and perform a Diffie-Hellman handshake
	// to derive a shared key.

	shared, err := ECDH(sec, peerPublicKey)
	if err != nil {
		c.reportError(err)
		return
	}

	// Use the derived shared key from Diffie-Hellman to encrypt/decrypt all future communications
	// with AES-256 Galois Counter Mode (GCM).

	core, err := aes.NewCipher(shared[:])
	if err != nil {
		c.reportError(fmt.Errorf("could not instantiate aes: %w", err))
		return
	}

	suite, err := cipher.NewGCM(core)
	if err != nil {
		c.reportError(fmt.Errorf("could not instantiate aes-gcm: %w", err))
		return
	}

	c.suite = suite

	// Send to our peer our overlay ID.

	buf := c.node.id.Marshal()
	buf = append(buf, c.node.Sign(append(buf, shared...))...)

	if err := c.send(0, buf); err != nil {
		c.reportError(fmt.Errorf("failed to send session handshake: %w", err))
		return
	}

	// Read and parse from our peer their overlay ID.

	msg, err = c.recv(ctx)
	if err != nil {
		c.reportError(fmt.Errorf("failed to read overlay handshake: %w", err))
		return
	}

	if msg.nonce != 0 {
		c.reportError(fmt.Errorf("got overlay handshake with nonce %d, but expected nonce to be 0", msg.nonce))
		return
	}

	id, err := UnmarshalID(msg.data)
	if err != nil {
		c.reportError(fmt.Errorf("failed to parse peer id while handling overlay handshake: %w", err))
		return
	}

	// Validate the peers ownership of the overlay ID.

	data := make([]byte, id.Size())
	copy(data, msg.data)

	if !id.ID.Verify(append(data, shared...), msg.data[len(data):]) {
		c.reportError(errors.New("overlay handshake signature is malformed"))
		return
	}

	c.id = id

	c.SetLogger(c.Logger().With(
		zap.String("peer_id", id.ID.String()),
		zap.String("peer_addr", id.Address),
		zap.String("remote_addr", c.conn.RemoteAddr().String()),
		zap.String("session_key", hex.EncodeToString(shared[:])),
	))

	c.Logger().Debug("Peer connection opened.")

	for _, protocol := range c.node.protocols {
		if protocol.OnPeerConnected == nil {
			continue
		}

		protocol.OnPeerConnected(c)
	}
}

func (c *Client) handleLoop() {
	defer close(c.handlerDone)
	defer c.requests.close()

	for {
		msg, err := c.recv(context.Background())
		if err != nil {
			if !isEOF(err) {
				c.Logger().Warn("Got an error deserializing a message from a peer.", zap.Error(err))
			}
			c.reportError(err)
			break
		}

		for _, protocol := range c.node.protocols {
			if protocol.OnMessageRecv == nil {
				continue
			}

			protocol.OnMessageRecv(c)
		}

		if ch := c.requests.findRequest(msg.nonce); ch != nil {
			ch <- msg
			close(ch)
			continue
		}

		for _, handler := range c.node.handlers {
			if err = handler(HandlerContext{client: c, msg: msg}); err != nil {
				c.Logger().Warn("Got an error executing a message handler.", zap.Error(err))
				c.reportError(err)
				break
			}
		}

		if err != nil {
			break
		}
	}

	c.close()
}

func (c *Client) writeLoop(conn net.Conn) {
	defer close(c.writerDone)

	if err := c.writer.loop(conn, c.node.idleTimeout); err != nil {
		if !isEOF(err) {
			c.Logger().Warn("Got an error while sending messages.", zap.Error(err))
		}
		c.reportError(err)
		c.close()
	}
}

func (c *Client) readLoop(conn net.Conn) {
	defer close(c.readerDone)

	if err := c.reader.loop(conn, c.node.idleTimeout, c.node.maxRecvMessageSize); err != nil {
		if !isEOF(err) {
			c.Logger().Warn("Got an error while reading incoming messages.", zap.Error(err))
		}
		c.reportError(err)
		c.close()
	}
}

func isEOF(err error) bool {
	if errors.Is(err, io.EOF) {
		return true
	}

	var netErr *net.OpError

	if errors.As(err, &netErr) {
		if netErr.Err.Error() == "use of closed network connection" {
			return true
		}
	}

	return false
}

license: MIT

license_type: permissive

branch_name: refs/heads/master

gha_license_id: MIT

extension: go


text:
require qt-${PV}.inc
require nativesdk-qt5-tools.inc

PR = "${INC_PR}.0"
DEFAULT_PREFERENCE = "-1"

extension: bb


text:
SUMMARY = "IPTV plugin for VDR"
HOMEPAGE = "http://www.saunalahti.fi/~rahrenbe/vdr/iptv/"
LICENSE = "GPL-2.0"

LIC_FILES_CHKSUM = "file://COPYING;md5=892f569a555ba9c07a568a7c0c4fa63a"

SRC_URI = "http://www.saunalahti.fi/~rahrenbe/vdr/iptv/files/vdr-iptv-${PV}.tgz \
    file://0001-vdr-plugin-iptv-gcc6-build.patch \
    "
SRC_URI[md5sum] = "318d58e097895789b18a07cac46dfd1c"
SRC_URI[sha256sum] = "db9e397ed8c229f42ab71daea096c7ac66997905901639a767de193633854da2"

S = "${WORKDIR}/iptv-${PV}"

DEPENDS = "vdr curl"

do_install () {
  oe_runmake install DESTDIR=${D}
}

PACKAGES_append = " ${PN}-scripts"
INSANE_SKIP_${PN} = "already-stripped"

FILES_${PN}_append = " ${libdir}/vdr/*"
FILES_${PN}-dbg_append = " ${libdir}/vdr/.debug"
FILES_${PN}-scripts = "/usr/share/vdr/plugins/iptv/"

repository: ivovka/meta-htpc

repo_name: ivovka/meta-htpc


text:
SUMMARY = "Evince is a document viewer for document formats like pdf, ps, djvu"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=96f2f8d5ee576a2163977938ea36fa7b"
SECTION = "x11/office"
DEPENDS = "gtk+3 libsecret gnome-desktop3 poppler gstreamer1.0-plugins-base orc adwaita-icon-theme intltool-native"
PR = "r5"

inherit gnome pkgconfig gtk-icon-cache gsettings gobject-introspection distro_features_check

REQUIRED_DISTRO_FEATURES = "x11"

SRC_URI[archive.md5sum] = "c39af6b8b1c44d4393ef8ac9dab99c0b"
SRC_URI[archive.sha256sum] = "42ad6c7354d881a9ecab136ea84ff867acb942605bcfac48b6c12e1c2d8ecb17"

SRC_URI += "file://0001-help-remove-YELP-macro.patch \
            file://0002-fix-gcc6-errors.patch \
"

EXTRA_OECONF = " --enable-thumbnailer \
"

do_compile_prepend() {
        export GIR_EXTRA_LIBS_PATH="${B}/libdocument/.libs"
}

do_install_append() {
    install -d install -d ${D}${datadir}/pixmaps
    install -m 0755 ${S}/data/icons/48x48/apps/evince.png ${D}${datadir}/pixmaps/
}

PACKAGECONFIG ??= ""
PACKAGECONFIG[nautilus] = "--enable-nautilus,--disable-nautilus,nautilus"
PACKAGECONFIG[browser-plugin] = "--enable-browser-plugin,--disable-browser-plugin,"

RDEPENDS_${PN} += "glib-2.0-utils"
RRECOMMMENDS_${PN} = "adwaita-icon-theme"

PACKAGES =+ "${PN}-nautilus-extension"
PACKAGES =+ "${PN}-browser-plugin"
FILES_${PN} += "${datadir}/dbus-1 \
                ${datadir}/appdata \
                ${datadir}/thumbnailers \
               "
FILES_${PN}-dbg += "${libdir}/*/*/.debug \
                    ${libdir}/*/*/*/.debug"
FILES_${PN}-dev += "${libdir}/nautilus/extensions-2.0/*.la \
                    ${libdir}/evince/*/backends/*.la"
FILES_${PN}-staticdev += "${libdir}/nautilus/extensions-2.0/*.a \
                          ${libdir}/evince/*/backends/*.a"
FILES_${PN}-nautilus-extension = "${libdir}/nautilus/*/*so"
FILES_${PN}-browser-plugin = "${libdir}/mozilla/*/*so"


text:
/*
	Innards.h
	(c)2000 PaleStar Development, Richard Lyle
*/

#ifndef INNARDS_H
#define INNARDS_H

#include "DarkSpace/GadgetDrive.h"

//----------------------------------------------------------------------------

class Innards : public GadgetDrive
{
public:
	DECLARE_WIDGET_CLASS();

	// NounGadget interface
	int durability() const
	{
		return 0;
	}
	int	maxDamage() const
	{
		return 8000;
	}
	int	addValue() const
	{
		return 0;
	}
	int buildTechnology() const
	{
		return 1000;
	}
	int	buildCost() const
	{
		return 0;
	}
	dword buildFlags() const
	{
		return 0;
	}
	int	buildTime() const
	{
		return 150;
	}

	// GadgetDrive interface
	float thrust() const
	{
		return 5.0f;
	}
	int maxEnergy() const
	{
		return 7000;
	}
	int energy() const
	{
		return 14;
	}
	int energyFalloff() const
	{
		return 14;
	}
};

//----------------------------------------------------------------------------

#endif

//----------------------------------------------------------------------------
// EOF

repository: palestar/darkspace

repo_name: palestar/darkspace

branch_name: refs/heads/develop

extension: h


text:
// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.

package codec

import (
	"math/rand"
	"time"
)

// NoopHandle returns a no-op handle. It basically does nothing.
// It is only useful for benchmarking, as it gives an idea of the
// overhead from the codec framework.
//
// LIBRARY USERS: *** DO NOT USE ***
func NoopHandle(slen int) *noopHandle {
	h := noopHandle{}
	h.rand = rand.New(rand.NewSource(time.Now().UnixNano()))
	h.B = make([][]byte, slen)
	h.S = make([]string, slen)
	for i := 0; i < len(h.S); i++ {
		b := make([]byte, i+1)
		for j := 0; j < len(b); j++ {
			b[j] = 'a' + byte(i)
		}
		h.B[i] = b
		h.S[i] = string(b)
	}
	return &h
}

// noopHandle does nothing.
// It is used to simulate the overhead of the codec framework.
type noopHandle struct {
	BasicHandle
	binaryEncodingType
	noopDrv // noopDrv is unexported here, so we can get a copy of it when needed.
}

type noopDrv struct {
	d    *Decoder
	e    *Encoder
	i    int
	S    []string
	B    [][]byte
	mks  []bool    // stack. if map (true), else if array (false)
	mk   bool      // top of stack. what container are we on? map or array?
	ct   valueType // last response for IsContainerType.
	cb   int       // counter for ContainerType
	rand *rand.Rand
}

func (h *noopDrv) r(v int) int { return h.rand.Intn(v) }
func (h *noopDrv) m(v int) int { h.i++; return h.i % v }

func (h *noopDrv) newEncDriver(e *Encoder) encDriver { h.e = e; return h }
func (h *noopDrv) newDecDriver(d *Decoder) decDriver { h.d = d; return h }

func (h *noopDrv) reset()       {}
func (h *noopDrv) uncacheRead() {}

// --- encDriver

// stack functions (for map and array)
func (h *noopDrv) start(b bool) {
	// println("start", len(h.mks)+1)
	h.mks = append(h.mks, b)
	h.mk = b
}
func (h *noopDrv) end() {
	// println("end: ", len(h.mks)-1)
	h.mks = h.mks[:len(h.mks)-1]
	if len(h.mks) > 0 {
		h.mk = h.mks[len(h.mks)-1]
	} else {
		h.mk = false
	}
}

func (h *noopDrv) EncodeBuiltin(rt uintptr, v interface{}) {}
func (h *noopDrv) EncodeNil()                              {}
func (h *noopDrv) EncodeInt(i int64)                       {}
func (h *noopDrv) EncodeUint(i uint64)                     {}
func (h *noopDrv) EncodeBool(b bool)                       {}
func (h *noopDrv) EncodeFloat32(f float32)                 {}
func (h *noopDrv) EncodeFloat64(f float64)                 {}
func (h *noopDrv) EncodeRawExt(re *RawExt, e *Encoder)     {}
func (h *noopDrv) EncodeArrayStart(length int)             { h.start(true) }
func (h *noopDrv) EncodeMapStart(length int)               { h.start(false) }
func (h *noopDrv) EncodeEnd()                              { h.end() }

func (h *noopDrv) EncodeString(c charEncoding, v string)      {}
func (h *noopDrv) EncodeSymbol(v string)                      {}
func (h *noopDrv) EncodeStringBytes(c charEncoding, v []byte) {}

func (h *noopDrv) EncodeExt(rv interface{}, xtag uint64, ext Ext, e *Encoder) {}

// ---- decDriver
func (h *noopDrv) initReadNext()                              {}
func (h *noopDrv) CheckBreak() bool                           { return false }
func (h *noopDrv) IsBuiltinType(rt uintptr) bool              { return false }
func (h *noopDrv) DecodeBuiltin(rt uintptr, v interface{})    {}
func (h *noopDrv) DecodeInt(bitsize uint8) (i int64)          { return int64(h.m(15)) }
func (h *noopDrv) DecodeUint(bitsize uint8) (ui uint64)       { return uint64(h.m(35)) }
func (h *noopDrv) DecodeFloat(chkOverflow32 bool) (f float64) { return float64(h.m(95)) }
func (h *noopDrv) DecodeBool() (b bool)                       { return h.m(2) == 0 }
func (h *noopDrv) DecodeString() (s string)                   { return h.S[h.m(8)] }
func (h *noopDrv) DecodeStringAsBytes() []byte                { return h.DecodeBytes(nil, true) }

func (h *noopDrv) DecodeBytes(bs []byte, zerocopy bool) []byte { return h.B[h.m(len(h.B))] }

func (h *noopDrv) ReadEnd() { h.end() }

// toggle map/slice
func (h *noopDrv) ReadMapStart() int   { h.start(true); return h.m(10) }
func (h *noopDrv) ReadArrayStart() int { h.start(false); return h.m(10) }

func (h *noopDrv) ContainerType() (vt valueType) {
	// return h.m(2) == 0
	// handle kStruct, which will bomb is it calls this and doesn't get back a map or array.
	// consequently, if the return value is not map or array, reset it to one of them based on h.m(7) % 2
	// for kstruct: at least one out of every 2 times, return one of valueTypeMap or Array (else kstruct bombs)
	// however, every 10th time it is called, we just return something else.
	var vals = [...]valueType{valueTypeArray, valueTypeMap}
	//  ------------ TAKE ------------
	// if h.cb%2 == 0 {
	// 	if h.ct == valueTypeMap || h.ct == valueTypeArray {
	// 	} else {
	// 		h.ct = vals[h.m(2)]
	// 	}
	// } else if h.cb%5 == 0 {
	// 	h.ct = valueType(h.m(8))
	// } else {
	// 	h.ct = vals[h.m(2)]
	// }
	//  ------------ TAKE ------------
	// if h.cb%16 == 0 {
	// 	h.ct = valueType(h.cb % 8)
	// } else {
	// 	h.ct = vals[h.cb%2]
	// }
	h.ct = vals[h.cb%2]
	h.cb++
	return h.ct

	// if h.ct == valueTypeNil || h.ct == valueTypeString || h.ct == valueTypeBytes {
	// 	return h.ct
	// }
	// return valueTypeUnset
	// TODO: may need to tweak this so it works.
	// if h.ct == valueTypeMap && vt == valueTypeArray || h.ct == valueTypeArray && vt == valueTypeMap {
	// 	h.cb = !h.cb
	// 	h.ct = vt
	// 	return h.cb
	// }
	// // go in a loop and check it.
	// h.ct = vt
	// h.cb = h.m(7) == 0
	// return h.cb
}
func (h *noopDrv) TryDecodeAsNil() bool {
	if h.mk {
		return false
	} else {
		return h.m(8) == 0
	}
}
func (h *noopDrv) DecodeExt(rv interface{}, xtag uint64, ext Ext) uint64 {
	return 0
}

func (h *noopDrv) DecodeNaked() {
	// use h.r (random) not h.m() because h.m() could cause the same value to be given.
	var sk int
	if h.mk {
		// if mapkey, do not support values of nil OR bytes, array, map or rawext
		sk = h.r(7) + 1
	} else {
		sk = h.r(12)
	}
	n := &h.d.n
	switch sk {
	case 0:
		n.v = valueTypeNil
	case 1:
		n.v, n.b = valueTypeBool, false
	case 2:
		n.v, n.b = valueTypeBool, true
	case 3:
		n.v, n.i = valueTypeInt, h.DecodeInt(64)
	case 4:
		n.v, n.u = valueTypeUint, h.DecodeUint(64)
	case 5:
		n.v, n.f = valueTypeFloat, h.DecodeFloat(true)
	case 6:
		n.v, n.f = valueTypeFloat, h.DecodeFloat(false)
	case 7:
		n.v, n.s = valueTypeString, h.DecodeString()
	case 8:
		n.v, n.l = valueTypeBytes, h.B[h.m(len(h.B))]
	case 9:
		n.v = valueTypeArray
	case 10:
		n.v = valueTypeMap
	default:
		n.v = valueTypeExt
		n.u = h.DecodeUint(64)
		n.l = h.B[h.m(len(h.B))]
	}
	h.ct = n.v
	return
}

repository: deepfence/ThreatMapper

repo_name: deepfence/ThreatMapper

branch_name: refs/heads/main

gha_language: TypeScript


text:
enable_language(C)

cmake_policy(SET CMP0026 OLD)

add_subdirectory(clear-cached-information-dir)

# Critical: this needs to happen in root CMakeLists.txt and not inside
# the subdir.
get_target_property(mypath Hello LOCATION)
# Now we create the file later, so you can see, ultimately no error should
# happen e.g. during generate phase:
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/clear-cached-information-dir/main.c)
set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/clear-cached-information-dir/main.c PROPERTIES GENERATED TRUE)

extension: cmake


text:
#include "blocks/rce.h"
#include "blocks/block_replacer.h"
#include "blocks/block_visitor.h"
#include "blocks/expr.h"
#include "blocks/stmt.h"
#include <algorithm>
#include <map>
#include <vector>
namespace block {

class var_use_counter : public block_visitor {
public:
	using block_visitor::visit;
	std::map<var::Ptr, uint64_t> usage_count;
	std::vector<var::Ptr> assigned_vars;
	virtual void visit(var_expr::Ptr e) override {
		var::Ptr v = e->var1;
		if (usage_count.find(v) != usage_count.end())
			usage_count[v]++;
		else
			usage_count[v] = 1;
	}
	virtual void visit(assign_expr::Ptr e) override {
		e->var1->accept(this);
		e->expr1->accept(this);
		if (!isa<var_expr>(e->var1))
			return;
		var_expr::Ptr ve = to<var_expr>(e->var1);
		var::Ptr v = ve->var1;
		if (std::find(assigned_vars.begin(), assigned_vars.end(), v) == assigned_vars.end())
			assigned_vars.push_back(v);
	}
};

class check_side_effects : public block_visitor {
public:
	using block_visitor::visit;
	bool has_side_effects = false;
	virtual void visit(assign_expr::Ptr) override {
		has_side_effects = true;
	}
	virtual void visit(function_call_expr::Ptr) override {
		has_side_effects = true;
	}
	virtual void visit(addr_of_expr::Ptr) override {
		has_side_effects = true;
	}
};

class gather_rce_decls : public block_visitor {
public:
	using block_visitor::visit;
	std::vector<decl_stmt::Ptr> gathered_decls;
	// This are vars (y) that may have one use but the use is of the form int x = y (use of y)
	// and x has multiple uses. When x is replaced with y it will have multiple uses
	// so we want to black list such x's
	std::vector<var::Ptr> duplicated_vars;
	std::map<var::Ptr, uint64_t> usage_count;
	std::vector<var::Ptr> assigned_vars;

	virtual void visit(decl_stmt::Ptr decl) {
		if (decl->init_expr == nullptr)
			return;
		var::Ptr v = decl->decl_var;
		if (std::find(assigned_vars.begin(), assigned_vars.end(), v) != assigned_vars.end())
			return;
		int use_count = 0;
		if (usage_count.find(v) != usage_count.end())
			use_count = usage_count[v];
		if (isa<var_expr>(decl->init_expr)) {
			// This is time to blacklist y
			if (use_count > 1) {
				var_expr::Ptr ve = to<var_expr>(decl->init_expr);
				var::Ptr v = ve->var1;
				if (std::find(duplicated_vars.begin(), duplicated_vars.end(), v) ==
				    duplicated_vars.end()) {
					duplicated_vars.push_back(v);
				}
			}
			gathered_decls.push_back(decl);
			return;
		}

		if (use_count == 1) {
			check_side_effects checker;
			decl->init_expr->accept(&checker);
			// We will also allow variables that are used exactly once
			// and don't have side effects
			if (checker.has_side_effects == false) {
				gathered_decls.push_back(decl);
				return;
			}
		}
	}
};

class replace_rce_vars : public block_replacer {
public:
	using block_replacer::visit;
	std::vector<decl_stmt::Ptr> gathered_decls;
	std::map<var::Ptr, decl_stmt::Ptr> var_decl_map;
	std::vector<var::Ptr> perma_enabled_decls;
	std::vector<var::Ptr> enabled_decls;

	virtual void visit(decl_stmt::Ptr decl) override {
		if (decl->init_expr)
			decl->init_expr = rewrite(decl->init_expr);
		if (std::find(gathered_decls.begin(), gathered_decls.end(), decl) != gathered_decls.end()) {
			if (isa<var_expr>(decl->init_expr))
				perma_enabled_decls.push_back(decl->decl_var);
			else {
				// Store decls that have a complex expression on the RHS
				// separately, if there is any statement that has side-effects,
				// we can immediately clear this
				enabled_decls.push_back(decl->decl_var);
			}
		}
		node = decl;
	}
	virtual void visit(assign_expr::Ptr assign) override {
		assign->expr1 = rewrite(assign->expr1);
		assign->var1 = rewrite(assign->var1);
		enabled_decls.clear();
		node = assign;
	}
	virtual void visit(addr_of_expr::Ptr addr) override {
		addr->expr1 = rewrite(addr->expr1);
		enabled_decls.clear();
		node = addr;
	}
	virtual void visit(function_call_expr::Ptr f) override {
		for (unsigned int i = 0; i < f->args.size(); i++) {
			f->args[i] = rewrite(f->args[i]);
		}
		enabled_decls.clear();
		node = f;
	}
	virtual void visit(var_expr::Ptr ve) override {
		var::Ptr v = ve->var1;
		if (std::find(perma_enabled_decls.begin(), perma_enabled_decls.end(), v) != perma_enabled_decls.end() ||
		    std::find(enabled_decls.begin(), enabled_decls.end(), v) != enabled_decls.end()) {
			decl_stmt::Ptr de = var_decl_map[v];
			node = de->init_expr;
		} else {
			node = ve;
		}
	}
};

class rce_decl_deleter : public block_visitor {
public:
	using block_visitor::visit;
	std::map<var::Ptr, uint64_t> usage_count;
	virtual void visit(stmt_block::Ptr b) {
		std::vector<stmt::Ptr> new_stmts;
		for (auto stmt : b->stmts) {
			if (isa<decl_stmt>(stmt)) {
				var::Ptr v = to<decl_stmt>(stmt)->decl_var;
				if (usage_count.find(v) != usage_count.end()) {
					// TODO: ensure that we are not deleting decls who's RHS have side-effects
					new_stmts.push_back(stmt);
				}
			} else {
				new_stmts.push_back(stmt);
			}
			stmt->accept(this);
		}
		b->stmts = new_stmts;
	}
};

void eliminate_redundant_vars(block::Ptr ast) {
	var_use_counter counter;
	ast->accept(&counter);
	gather_rce_decls gatherer;
	gatherer.usage_count = counter.usage_count;
	gatherer.assigned_vars = counter.assigned_vars;
	ast->accept(&gatherer);

	replace_rce_vars replacer;
	for (auto decl : gatherer.gathered_decls) {
		var::Ptr v = decl->decl_var;

		if (!isa<var_expr>(decl->init_expr) &&
		    std::find(gatherer.duplicated_vars.begin(), gatherer.duplicated_vars.end(), v) !=
			gatherer.duplicated_vars.end())
			continue;
		replacer.gathered_decls.push_back(decl);
		replacer.var_decl_map[v] = decl;
	}
	ast->accept(&replacer);
	// Now that all th replacements have been done, we will decls that are not used
	var_use_counter post_counter;
	ast->accept(&post_counter);

	rce_decl_deleter deleter;
	deleter.usage_count = post_counter.usage_count;
	ast->accept(&deleter);
}

} // namespace block

repository: AjayBrahmakshatriya/buildit

repo_name: AjayBrahmakshatriya/buildit

extension: cpp


text:
@article{Corinaldesi2017,
 abstract = {© 2017 The Author(s). Viruses are the most abundant and, likely, one of the most diverse biological components in the oceans. By infecting their hosts, they play key roles in biogeochemical cycles and ecosystem functioning at a global scale. The ocean interior hosts most of the microbial life, and, despite deep-sea sediments represent the main repository of this component and the largest biome on Earth, viral diversity in these ecosystems remains almost completely unknown. We compared a physical-chemical procedure and a previously published sediment washing-based procedure for isolating viruses from benthic deep-sea ecosystems to generate viromes through high-throughput sequencing. The procedure based on a physical-chemical dislodgment of viral particles from the sediments, followed by vacuum filtration was much more efficient allowing us to recover  \textgreater 85% of the extractable viruses. By using this procedure, a high fraction of viral DNA was recovered and new viromes from different benthic deep-sea sites were generated. Such viromes were diversified in terms of both viral families and putative functions. Overall, the results presented here provide new insights for evaluating benthic deep-sea viral diversity through metagenomic analyses, and reveal that deep-sea sediments are a hot spot of novel viral genotypes and functions.},
 author = {Corinaldesi, C. and Tangherlini, M. and Dell'anno, A.},
 doi = {10.1038/s41598-017-08783-4},
 issn = {20452322},
 journal = {Scientific Reports},
 number = {1},
 title = {From virus isolation to metagenome generation for investigating viral diversity in deep-sea sediments},
 volume = {7},
 year = {2017}
}

repository: mTangherlini/aMTangherlini

repo_name: mTangherlini/aMTangherlini

extension: bib


text:
SUMMARY = "Phosphor OpenBMC DBUS Permissions"
DESCRIPTION = "Phosphor OpenBMC DBUS Permissions."
HOMEPAGE = "http://github.com/openbmc/"
PR = "r1"

inherit allarch
inherit obmc-phosphor-license
inherit obmc-phosphor-dbus-service

DBUS_SERVICES += " \
        org.openbmc \
        "

gha_language: Python


text: @misc{w. guan_y. deng_q. peng_y. fang_md. hope_a. webster_m. yiqiong_d. lichtenstein_poggiali_g. soldati_et al._1970, title={Role of point-of-care ultrasound during the COVID-19 pandemic: our recommendations in the management of dialytic patients}, url={https://theultrasoundjournal.springeropen.com/articles/10.1186/s13089-020-00177-4}, journal={The Ultrasound Journal}, publisher={SpringerOpen}, author={W. Guan, Z. Ni and Y. Deng, W. Liu and Q. Peng, X. Wang and Y. Fang, H. Zhang and MD. Hope, CA. Raptis and A. Webster, E. Nagler and M. Yiqiong, B. Diao and D. Lichtenstein, M. Malbrain and Poggiali, E. and G. Soldati, A. Smargiassi and et al.}, year={1970}, month={Jan}}

repository: jmagallones/Final-RGDY-Project

repo_name: jmagallones/Final-RGDY-Project


text:
package golang

import goformat "go/format"

func FormatCode(code string) string {
	ret, err := goformat.Source([]byte(code))
	if err != nil {
		return code
	}

	return string(ret)
}


text:
package mux

import (
	"fmt"
	"net"
	"sync"
	"time"
)

type Handler interface {
	HandleTCP(net.Conn)
}

type HandlerFunc func(net.Conn)

func (f HandlerFunc) HandleTCP(c net.Conn) {
	f(c)
}

type Mux struct {
	h map[byte]Handler
	m sync.RWMutex
}

func (m *Mux) Handle(typ byte, h Handler) {
	m.m.Lock()
	defer m.m.Unlock()
	if m.h == nil {
		m.h = make(map[byte]Handler)
	}
	m.h[typ] = h
}

func (m *Mux) Dispatch(c net.Conn) error {
	typ := make([]byte, 1)
	_, err := c.Read(typ)
	if err != nil {
		return err
	}
	m.m.RLock()
	defer m.m.RUnlock()
	if h := m.h[typ[0]]; h != nil {
		h.HandleTCP(c)
		return nil
	}
	c.Close()
	return fmt.Errorf("Unknown type: %x", typ[0])
}

var DefaultMux = &Mux{}

func Handle(typ byte, h Handler) {
	DefaultMux.Handle(typ, h)
}

func Dispatch(c net.Conn) error {
	return DefaultMux.Dispatch(c)
}

func Dial(network, address string, typ byte) (net.Conn, error) {
	c, err := net.Dial(network, address)
	if err != nil {
		return nil, err
	}
	return newClient(c, typ)
}

func DialTimeout(network, address string, typ byte, timeout time.Duration) (net.Conn, error) {
	c, err := net.DialTimeout(network, address, timeout)
	if err != nil {
		return nil, err
	}
	return newClient(c, typ)
}

func newClient(c net.Conn, typ byte) (net.Conn, error) {
	_, err := c.Write([]byte{typ})
	if err != nil {
		return nil, err
	}
	return c, nil
}

repository: yosisa/craft

repo_name: yosisa/craft


text:
package test

import (
	"testing"

	"github.com/mgechev/revive/lint"
	"github.com/mgechev/revive/rule"
)

func TestFunctionResultsLimit(t *testing.T) {
	testRule(t, "function-result-limit", &rule.FunctionResultsLimitRule{}, &lint.RuleConfig{
		Arguments: []interface{}{int64(3)},
	})
}

repository: mgechev/revive

repo_name: mgechev/revive

gha_language: Go


text:
file(REMOVE_RECURSE
  "CMakeFiles/NFScalePlugin.dir/NFScaleModule.cpp.o"
  "CMakeFiles/NFScalePlugin.dir/NFScalePlugin.cpp.o"
  "CMakeFiles/NFScalePlugin.dir/dllmain.cpp.o"
  "../../../_Out/Debug/NFScalePlugin_d.pdb"
  "../../../_Out/Debug/NFScalePlugin_d.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/NFScalePlugin.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: junfff/nf-server

repo_name: junfff/nf-server


text:
@Misc{KubeAdvShedule-sp20-516-232,
  title =	 {Advanced Scheduling in Kubernetes},
  organization = {The Linux Foundation},
  howpublished = {Web page},
  year =	 {2020},
  url = {https://kubernetes.io/blog/2017/03/advanced-scheduling-in-kubernetes/}
}

@Misc{KubeShedule-sp20-516-232,
  title =	 {The Kubernetes Scheduler},
  organization = {medium},
  howpublished = {Web page},
  url = {https://medium.com/@dominik.tornow/the-kubernetes-scheduler-cd429abac02f}
}

@Misc{KubeImplAdvShedule-sp20-516-232,
  title =	 {Implementing Advanced Scheduling Techniques with Kubernetes},
  organization = {thenewstack.io},
  howpublished = {Web page},
  url = {https://thenewstack.io/implementing-advanced-scheduling-techniques-with-kubernetes}
}


text:
// Code generated by smithy-go-codegen DO NOT EDIT.

package connect

import (
	"context"
	"errors"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
	smithyendpoints "github.com/aws/smithy-go/endpoints"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Updates your claimed phone number from its current Amazon Connect instance or
// traffic distribution group to another Amazon Connect instance or traffic
// distribution group in the same Amazon Web Services Region. After using this API,
// you must verify that the phone number is attached to the correct flow in the
// target instance or traffic distribution group. You need to do this because the
// API switches only the phone number to a new instance or traffic distribution
// group. It doesn't migrate the flow configuration of the phone number, too. You
// can call DescribePhoneNumber (https://docs.aws.amazon.com/connect/latest/APIReference/API_DescribePhoneNumber.html)
// API to verify the status of a previous UpdatePhoneNumber (https://docs.aws.amazon.com/connect/latest/APIReference/API_UpdatePhoneNumber.html)
// operation.
func (c *Client) UpdatePhoneNumber(ctx context.Context, params *UpdatePhoneNumberInput, optFns ...func(*Options)) (*UpdatePhoneNumberOutput, error) {
	if params == nil {
		params = &UpdatePhoneNumberInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "UpdatePhoneNumber", params, optFns, c.addOperationUpdatePhoneNumberMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*UpdatePhoneNumberOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type UpdatePhoneNumberInput struct {

	// A unique identifier for the phone number.
	//
	// This member is required.
	PhoneNumberId *string

	// The Amazon Resource Name (ARN) for Amazon Connect instances or traffic
	// distribution groups that phone numbers are claimed to.
	//
	// This member is required.
	TargetArn *string

	// A unique, case-sensitive identifier that you provide to ensure the idempotency
	// of the request. If not provided, the Amazon Web Services SDK populates this
	// field. For more information about idempotency, see Making retries safe with
	// idempotent APIs (https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/)
	// .
	ClientToken *string

	noSmithyDocumentSerde
}

type UpdatePhoneNumberOutput struct {

	// The Amazon Resource Name (ARN) of the phone number.
	PhoneNumberArn *string

	// A unique identifier for the phone number.
	PhoneNumberId *string

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationUpdatePhoneNumberMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsRestjson1_serializeOpUpdatePhoneNumber{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsRestjson1_deserializeOpUpdatePhoneNumber{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addlegacyEndpointContextSetter(stack, options); err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack, options); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addUpdatePhoneNumberResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = addIdempotencyToken_opUpdatePhoneNumberMiddleware(stack, options); err != nil {
		return err
	}
	if err = addOpUpdatePhoneNumberValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdatePhoneNumber(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
		return err
	}
	return nil
}

type idempotencyToken_initializeOpUpdatePhoneNumber struct {
	tokenProvider IdempotencyTokenProvider
}

func (*idempotencyToken_initializeOpUpdatePhoneNumber) ID() string {
	return "OperationIdempotencyTokenAutoFill"
}

func (m *idempotencyToken_initializeOpUpdatePhoneNumber) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
	out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
	if m.tokenProvider == nil {
		return next.HandleInitialize(ctx, in)
	}

	input, ok := in.Parameters.(*UpdatePhoneNumberInput)
	if !ok {
		return out, metadata, fmt.Errorf("expected middleware input to be of type *UpdatePhoneNumberInput ")
	}

	if input.ClientToken == nil {
		t, err := m.tokenProvider.GetIdempotencyToken()
		if err != nil {
			return out, metadata, err
		}
		input.ClientToken = &t
	}
	return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opUpdatePhoneNumberMiddleware(stack *middleware.Stack, cfg Options) error {
	return stack.Initialize.Add(&idempotencyToken_initializeOpUpdatePhoneNumber{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}

func newServiceMetadataMiddleware_opUpdatePhoneNumber(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "connect",
		OperationName: "UpdatePhoneNumber",
	}
}

type opUpdatePhoneNumberResolveEndpointMiddleware struct {
	EndpointResolver EndpointResolverV2
	BuiltInResolver  builtInParameterResolver
}

func (*opUpdatePhoneNumberResolveEndpointMiddleware) ID() string {
	return "ResolveEndpointV2"
}

func (m *opUpdatePhoneNumberResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
	out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
	if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
		return next.HandleSerialize(ctx, in)
	}

	req, ok := in.Request.(*smithyhttp.Request)
	if !ok {
		return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
	}

	if m.EndpointResolver == nil {
		return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
	}

	params := EndpointParameters{}

	m.BuiltInResolver.ResolveBuiltIns(&params)

	var resolvedEndpoint smithyendpoints.Endpoint
	resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
	if err != nil {
		return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
	}

	req.URL = &resolvedEndpoint.URI

	for k := range resolvedEndpoint.Headers {
		req.Header.Set(
			k,
			resolvedEndpoint.Headers.Get(k),
		)
	}

	authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
	if err != nil {
		var nfe *internalauth.NoAuthenticationSchemesFoundError
		if errors.As(err, &nfe) {
			// if no auth scheme is found, default to sigv4
			signingName := "connect"
			signingRegion := m.BuiltInResolver.(*builtInResolver).Region
			ctx = awsmiddleware.SetSigningName(ctx, signingName)
			ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)

		}
		var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
		if errors.As(err, &ue) {
			return out, metadata, fmt.Errorf(
				"This operation requests signer version(s) %v but the client only supports %v",
				ue.UnsupportedSchemes,
				internalauth.SupportedSchemes,
			)
		}
	}

	for _, authScheme := range authSchemes {
		switch authScheme.(type) {
		case *internalauth.AuthenticationSchemeV4:
			v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
			var signingName, signingRegion string
			if v4Scheme.SigningName == nil {
				signingName = "connect"
			} else {
				signingName = *v4Scheme.SigningName
			}
			if v4Scheme.SigningRegion == nil {
				signingRegion = m.BuiltInResolver.(*builtInResolver).Region
			} else {
				signingRegion = *v4Scheme.SigningRegion
			}
			if v4Scheme.DisableDoubleEncoding != nil {
				// The signer sets an equivalent value at client initialization time.
				// Setting this context value will cause the signer to extract it
				// and override the value set at client initialization time.
				ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
			}
			ctx = awsmiddleware.SetSigningName(ctx, signingName)
			ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
			break
		case *internalauth.AuthenticationSchemeV4A:
			v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
			if v4aScheme.SigningName == nil {
				v4aScheme.SigningName = aws.String("connect")
			}
			if v4aScheme.DisableDoubleEncoding != nil {
				// The signer sets an equivalent value at client initialization time.
				// Setting this context value will cause the signer to extract it
				// and override the value set at client initialization time.
				ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
			}
			ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
			ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
			break
		case *internalauth.AuthenticationSchemeNone:
			break
		}
	}

	return next.HandleSerialize(ctx, in)
}

func addUpdatePhoneNumberResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
	return stack.Serialize.Insert(&opUpdatePhoneNumberResolveEndpointMiddleware{
		EndpointResolver: options.EndpointResolverV2,
		BuiltInResolver: &builtInResolver{
			Region:       options.Region,
			UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
			UseFIPS:      options.EndpointOptions.UseFIPSEndpoint,
			Endpoint:     options.BaseEndpoint,
		},
	}, "ResolveEndpoint", middleware.After)
}


text:
#ifndef DLA_INTERFACE_ERROR_MESSAGE_H
#define DLA_INTERFACE_ERROR_MESSAGE_H

#include <string>
#include <sstream>
#include "util_output.h"

namespace dla_interface {
  namespace util {
    // declaration of internal functions to compose the error message
    template <class... Args>
    std::string errorMessageInternal(const char* file, int line, const char* func,
                                     const Args&... args);
    void errorMessageCont(std::stringstream& s);
    template <class T, class... Args>
    void errorMessageCont(std::stringstream& s, const T& value, const Args&... args);

    // Implementations
    inline void errorMessageCont(std::stringstream& s) {}

    template <class T, class... Args>
    void errorMessageCont(std::stringstream& s, const T& value, const Args&... args) {
      s << value;
      errorMessageCont(s, args...);
    }

    template <class... Args>
    std::string errorMessageInternal(const char* file, int line, const char* func,
                                     const Args&... args) {
      std::stringstream s;
      s << "Calling function " << func << ": Error raised on " << file << ":" << line << ": ";
      errorMessageCont(s, args...);
      return s.str();
    }
  }
}

// Macro to generate the error message which add filename, line and function name.
// The message will have the following structure:
// "Calling function __func__: Error raised on __FILE__:__LINE__: <message>.
// where message is composed concatenating the rest of the arguments with operator<<.
#define errorMessageFunc(func, ...) \
  dla_interface::util::errorMessageInternal(__FILE__, __LINE__, func, __VA_ARGS__)
// Same as errorMessageFunc with func = __func__.
#define errorMessage(...) \
  dla_interface::util::errorMessageInternal(__FILE__, __LINE__, __func__, __VA_ARGS__)

#endif  // DLA_INTERFACE_ERROR_MESSAGE_H

repository: eth-cscs/DLA-interface

repo_name: eth-cscs/DLA-interface


text:
# Find pdcurses C Library

# Look for header files in the project specific include directory
find_path(PDCURSES_INCLUDE_DIR curses.h HINTS ${PROJECT_SOURCE_DIR}/include ${PDCURSES_BASE}/include ${LIBRARY_BASE}/include)

# Look for library in the project specific library path (We're specifically looking for the static library here)
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    set(LIBRARY_HINTS ${PROJECT_SOURCE_DIR}/lib/Win64)
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    set(LIBRARY_HINTS ${PROJECT_SOURCE_DIR}/lib/Linux)
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(LIBRARY_HINTS ${PROJECT_SOURCE_DIR}/lib/macOS)
endif()
find_library(PDCURSES_LIBRARY NAME pdcurses HINTS ${LIBRARY_HINTS} ${PDCURSES_BASE}/lib ${LIBRARY_BASE}/lib)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PDCURSES DEFAULT_MSG PDCURSES_LIBRARY PDCURSES_INCLUDE_DIR)

mark_as_advanced(PDCURSES_INCLUDE_DIR PDCURSES_LIBRARY)

set(PDCURSES_LIBRARIES ${PDCURSES_LIBRARY})
set(PDCURSES_INCLUDE_DIRS ${PDCURSES_INCLUDE_DIR})

repository: stbowers/Alcubierre

repo_name: stbowers/Alcubierre


text:
@proceedings{ws-2016-linguistic,
    title = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    editor = "Friedrich, Annemarie  and
      Tomanek, Katrin",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1700",
    doi = "10.18653/v1/W16-17",
}
@inproceedings{hong-etal-2016-building,
    title = "Building a Cross-document Event-Event Relation Corpus",
    author = "Hong, Yu  and
      Zhang, Tongtao  and
      O{'}Gorman, Tim  and
      Horowit-Hendler, Sharone  and
      Ji, Heng  and
      Palmer, Martha",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1701",
    doi = "10.18653/v1/W16-1701",
    pages = "1--6",
}
@inproceedings{li-etal-2016-annotating,
    title = "Annotating the Little Prince with {C}hinese {AMR}s",
    author = "Li, Bin  and
      Wen, Yuan  and
      Qu, Weiguang  and
      Bu, Lijun  and
      Xue, Nianwen",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1702",
    doi = "10.18653/v1/W16-1702",
    pages = "7--15",
}
@inproceedings{luu-etal-2016-converting,
    title = "Converting {S}yn{T}ag{R}us Dependency Treebank into {P}enn Treebank Style",
    author = "Luu, Alex  and
      Malamud, Sophia A.  and
      Xue, Nianwen",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1703",
    doi = "10.18653/v1/W16-1703",
    pages = "16--21",
}
@inproceedings{webber-etal-2016-discourse,
    title = "A Discourse-Annotated Corpus of Conjoined {VP}s",
    author = "Webber, Bonnie  and
      Prasad, Rashmi  and
      Lee, Alan  and
      Joshi, Aravind",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1704",
    doi = "10.18653/v1/W16-1704",
    pages = "22--31",
}
@inproceedings{laarmann-quante-etal-2016-annotating,
    title = "Annotating Spelling Errors in {G}erman Texts Produced by Primary School Children",
    author = "Laarmann-Quante, Ronja  and
      Knichel, Lukas  and
      Dipper, Stefanie  and
      Betken, Carina",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1705",
    doi = "10.18653/v1/W16-1705",
    pages = "32--42",
}
@inproceedings{martinez-alonso-etal-2016-supersense,
    title = "Supersense tagging with inter-annotator disagreement",
    author = "Mart{\'\i}nez Alonso, H{\'e}ctor  and
      Johannsen, Anders  and
      Plank, Barbara",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1706",
    doi = "10.18653/v1/W16-1706",
    pages = "43--48",
}
@inproceedings{rohde-etal-2016-filling,
    title = "Filling in the Blanks in Understanding Discourse Adverbials: Consistency, Conflict, and Context-Dependence in a Crowdsourced Elicitation Task",
    author = "Rohde, Hannah  and
      Dickinson, Anna  and
      Schneider, Nathan  and
      Clark, Christopher N. L.  and
      Louis, Annie  and
      Webber, Bonnie",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1707",
    doi = "10.18653/v1/W16-1707",
    pages = "49--58",
}
@inproceedings{komiya-etal-2016-comparison,
    title = "Comparison of Annotating Methods for Named Entity Corpora",
    author = "Komiya, Kanako  and
      Suzuki, Masaya  and
      Iwakura, Tomoya  and
      Sasaki, Minoru  and
      Shinnou, Hiroyuki",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1708",
    doi = "10.18653/v1/W16-1708",
    pages = "59--67",
}
@inproceedings{zeldes-simonson-2016-different,
    title = "Different Flavors of {GUM}: Evaluating Genre and Sentence Type Effects on Multilayer Corpus Annotation Quality",
    author = "Zeldes, Amir  and
      Simonson, Dan",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1709",
    doi = "10.18653/v1/W16-1709",
    pages = "68--78",
}
@inproceedings{elfardy-diab-2016-addressing,
    title = "Addressing Annotation Complexity: The Case of Annotating Ideological Perspective in {E}gyptian Social Media",
    author = "Elfardy, Heba  and
      Diab, Mona",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1710",
    doi = "10.18653/v1/W16-1710",
    pages = "79--88",
}
@inproceedings{bollmann-etal-2016-evaluating,
    title = "Evaluating Inter-Annotator Agreement on Historical Spelling Normalization",
    author = "Bollmann, Marcel  and
      Dipper, Stefanie  and
      Petran, Florian",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1711",
    doi = "10.18653/v1/W16-1711",
    pages = "89--98",
}
@inproceedings{schneider-etal-2016-corpus,
    title = "A Corpus of Preposition Supersenses",
    author = "Schneider, Nathan  and
      Hwang, Jena D.  and
      Srikumar, Vivek  and
      Green, Meredith  and
      Suresh, Abhijit  and
      Conger, Kathryn  and
      O{'}Gorman, Tim  and
      Palmer, Martha",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1712",
    doi = "10.18653/v1/W16-1712",
    pages = "99--109",
}
@inproceedings{de-kuthy-etal-2016-focus,
    title = "Focus Annotation of Task-based Data: Establishing the Quality of Crowd Annotation",
    author = "De Kuthy, Kordula  and
      Ziai, Ramon  and
      Meurers, Detmar",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1713",
    doi = "10.18653/v1/W16-1713",
    pages = "110--119",
}
@inproceedings{cetinoglu-coltekin-2016-part,
    title = "Part of Speech Annotation of a {T}urkish-{G}erman Code-Switching Corpus",
    author = {{\c{C}}etino{\u{g}}lu, {\"O}zlem  and
      {\c{C}}{\"o}ltekin, {\c{C}}a{\u{g}}r{\i}},
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1714",
    doi = "10.18653/v1/W16-1714",
    pages = "120--130",
}
@inproceedings{gerdes-kahane-2016-dependency,
    title = "Dependency Annotation Choices: Assessing Theoretical and Practical Issues of Universal Dependencies",
    author = "Gerdes, Kim  and
      Kahane, Sylvain",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1715",
    doi = "10.18653/v1/W16-1715",
    pages = "131--140",
}
@inproceedings{tandon-etal-2016-conversion,
    title = "Conversion from Paninian Karakas to Universal Dependencies for {H}indi Dependency Treebank",
    author = "Tandon, Juhi  and
      Chaudhry, Himani  and
      Bhat, Riyaz Ahmad  and
      Sharma, Dipti",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1716",
    doi = "10.18653/v1/W16-1716",
    pages = "141--150",
}
@inproceedings{di-felippo-nenkova-2016-phrase,
    title = "Phrase Generalization: a Corpus Study in Multi-Document Abstracts and Original News Alignments",
    author = "Di-Felippo, Ariani  and
      Nenkova, Ani",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1717",
    doi = "10.18653/v1/W16-1717",
    pages = "151--159",
}
@inproceedings{duan-etal-2016-generating,
    title = "Generating Disambiguating Paraphrases for Structurally Ambiguous Sentences",
    author = "Duan, Manjuan  and
      Hill, Ethan  and
      White, Michael",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1718",
    doi = "10.18653/v1/W16-1718",
    pages = "160--170",
}
@inproceedings{wagner-etal-2016-applying,
    title = "Applying Universal Dependency to the {A}rapaho Language",
    author = "Wagner, Irina  and
      Cowell, Andrew  and
      Hwang, Jena D.",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1719",
    doi = "10.18653/v1/W16-1719",
    pages = "171--179",
}
@inproceedings{xue-etal-2016-annotating,
    title = "Annotating the discourse and dialogue structure of {SMS} message conversations",
    author = "Xue, Nianwen  and
      Su, Qishen  and
      Jeong, Sooyoung",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1720",
    doi = "10.18653/v1/W16-1720",
    pages = "180--187",
}
@inproceedings{delozier-etal-2016-creating,
    title = "Creating a Novel Geolocation Corpus from Historical Texts",
    author = "DeLozier, Grant  and
      Wing, Ben  and
      Baldridge, Jason  and
      Nesbit, Scott",
    booktitle = "Proceedings of the 10th Linguistic Annotation Workshop held in conjunction with {ACL} 2016 ({LAW}-X 2016)",
    month = aug,
    year = "2016",
    address = "Berlin, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W16-1721",
    doi = "10.18653/v1/W16-1721",
    pages = "188--198",
}

repository: emorynlp/nlprankings

repo_name: emorynlp/nlprankings

gha_license_id: NOASSERTION

gha_language: TeX


text:
package validator

import (
	"reflect"
	"strings"
)

const (
	jsonRequest   = "json"
	xmlRequest    = "xml"
	formRequest   = "form"
	queryRequest  = "query"
	paramsRequest = "params"
)

// Context to store request data.
type Context struct {
	Request HTTPRequest
	Name    string
	Type    string
	Errors  error
}

// NewContext constructor.
func NewContext(request HTTPRequest) *Context {
	context := &Context{
		Request: request,
	}

	context.Name = reflect.TypeOf(request).Elem().String()

	switch true {
	case strings.HasSuffix(context.Name, "JSON"):
		context.Type = jsonRequest
	case strings.HasSuffix(context.Name, "XML"):
		context.Type = xmlRequest
	case strings.HasSuffix(context.Name, "Form"):
		context.Type = formRequest
	case strings.HasSuffix(context.Name, "Query"):
		context.Type = queryRequest
	case strings.HasSuffix(context.Name, "Params"):
		context.Type = paramsRequest
	}

	return context
}

repository: mlanin/iris-middlewares

repo_name: mlanin/iris-middlewares


text:
SUMMARY = "Linux CAN network development utilities"
LICENSE = "GPLv2 & BSD-3-Clause"
LIC_FILES_CHKSUM = "file://include/linux/can.h;endline=44;md5=a9e1169c6c9a114a61329e99f86fdd31"

DEPENDS = "libsocketcan"

SRC_URI = "git://github.com/linux-can/${BPN}.git;protocol=git"

SRCREV = "da65fdfe0d1986625ee00af0b56ae17ec132e700"

PV = "2020.02.04"

S = "${WORKDIR}/git"

inherit autotools pkgconfig


text:
DESCRIPTION = "Gtk2 theme files to accompany default Matchbox themes"
LICENSE = "GPL"
RDEPENDS_${PN} = "matchbox-wm gtk2-theme-angelistic"
SECTION = "x11/base"
PR = "r1"

SRC_URI = "file://gtkrc"

FILES_${PN} = "${datadir}/themes"

do_install() {
	install -d ${D}${datadir}/themes/blondie/gtk-2.0
	install -d ${D}${datadir}/themes/MBOpus/gtk-2.0
	install -m 644 ${WORKDIR}/gtkrc ${D}${datadir}/themes/blondie/gtk-2.0/
	install -m 644 ${WORKDIR}/gtkrc ${D}${datadir}/themes/MBOpus/gtk-2.0/
}

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
@article{Frit2,
  author = {Fritz, U. and Corti, C. and Päckert, M.},
  date = {2012},
  doi = {10.1007/s13127-011-0069-8},
  journaltitle = {Actes du 4\textsuperscript{ème} Congrès Français d'Acoustique},
  pages = {71--80},
  shortjournal = {Actes 4supèmesup Congrès Fr. Acoust.},
  timestamp = {2015-02-24 12:14:36 +0100},
  title = {Test of markupconversion: Italics, bold, superscript, subscript, and small caps: Mitochondrial {DNA}\textsubscript{2} sequences suggest unexpected phylogenetic position of Corso-Sardinian grass snakes (\emph{Natrix cetti}) and \textbf{do not} support their \textsc{species status}, with notes on phylogeography and subspecies delineation of grass snakes.},
  volume = {12}
}

license: Unlicense

repository: egh/zotero-better-bibtex

repo_name: egh/zotero-better-bibtex

filename: Better BibLaTeX.007.bib


text:
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/ServiceRegistry/interface/RandomEngineSentry.h"

#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h"

#include "GeneratorInterface/CosmicMuonGenerator/interface/CosMuoGenProducer.h"

edm::CosMuoGenProducer::CosMuoGenProducer(const ParameterSet& pset)
    :  //RanS(pset.getParameter<int>("RanSeed", 123456)), //get seed now from Framework
      MinP(pset.getParameter<double>("MinP")),
      MinP_CMS(pset.getParameter<double>("MinP_CMS")),
      MaxP(pset.getParameter<double>("MaxP")),
      MinT(pset.getParameter<double>("MinTheta")),
      MaxT(pset.getParameter<double>("MaxTheta")),
      MinPh(pset.getParameter<double>("MinPhi")),
      MaxPh(pset.getParameter<double>("MaxPhi")),
      MinS(pset.getParameter<double>("MinT0")),
      MaxS(pset.getParameter<double>("MaxT0")),
      ELSF(pset.getParameter<double>("ElossScaleFactor")),
      RTarget(pset.getParameter<double>("RadiusOfTarget")),
      ZTarget(pset.getParameter<double>("ZDistOfTarget")),
      ZCTarget(pset.getParameter<double>("ZCentrOfTarget")),
      TrackerOnly(pset.getParameter<bool>("TrackerOnly")),
      MultiMuon(pset.getParameter<bool>("MultiMuon")),
      MultiMuonFileName(pset.getParameter<std::string>("MultiMuonFileName")),
      MultiMuonFileFirstEvent(pset.getParameter<int>("MultiMuonFileFirstEvent")),
      MultiMuonNmin(pset.getParameter<int>("MultiMuonNmin")),
      TIFOnly_constant(pset.getParameter<bool>("TIFOnly_constant")),
      TIFOnly_linear(pset.getParameter<bool>("TIFOnly_linear")),
      MTCCHalf(pset.getParameter<bool>("MTCCHalf")),
      PlugVtx(pset.getParameter<double>("PlugVx")),
      PlugVtz(pset.getParameter<double>("PlugVz")),
      VarRhoAir(pset.getParameter<double>("RhoAir")),
      VarRhoWall(pset.getParameter<double>("RhoWall")),
      VarRhoRock(pset.getParameter<double>("RhoRock")),
      VarRhoClay(pset.getParameter<double>("RhoClay")),
      VarRhoPlug(pset.getParameter<double>("RhoPlug")),
      ClayLayerWidth(pset.getParameter<double>("ClayWidth")),
      MinEn(pset.getParameter<double>("MinEnu")),
      MaxEn(pset.getParameter<double>("MaxEnu")),
      NuPrdAlt(pset.getParameter<double>("NuProdAlt")),
      AllMu(pset.getParameter<bool>("AcptAllMu")),
      extCrossSect(pset.getUntrackedParameter<double>("crossSection", -1.)),
      extFilterEff(pset.getUntrackedParameter<double>("filterEfficiency", -1.)),
      cmVerbosity_(pset.getParameter<bool>("Verbosity")),
      isInitialized_(false) {
  //if not specified (i.e. negative) then use MinP also for MinP_CMS
  if (MinP_CMS < 0)
    MinP_CMS = MinP;

  // set up the generator
  CosMuoGen = std::make_unique<CosmicMuonGenerator>();
  // Begin JMM change
  //  CosMuoGen->setNumberOfEvents(numberEventsInRun());
  CosMuoGen->setNumberOfEvents(999999999);
  // End of JMM change
  CosMuoGen->setRanSeed(RanS);
  CosMuoGen->setMinP(MinP);
  CosMuoGen->setMinP_CMS(MinP_CMS);
  CosMuoGen->setMaxP(MaxP);
  CosMuoGen->setMinTheta(MinT);
  CosMuoGen->setMaxTheta(MaxT);
  CosMuoGen->setMinPhi(MinPh);
  CosMuoGen->setMaxPhi(MaxPh);
  CosMuoGen->setMinT0(MinS);
  CosMuoGen->setMaxT0(MaxS);
  CosMuoGen->setElossScaleFactor(ELSF);
  CosMuoGen->setRadiusOfTarget(RTarget);
  CosMuoGen->setZDistOfTarget(ZTarget);
  CosMuoGen->setZCentrOfTarget(ZCTarget);
  CosMuoGen->setTrackerOnly(TrackerOnly);
  CosMuoGen->setMultiMuon(MultiMuon);
  CosMuoGen->setMultiMuonFileName(MultiMuonFileName);
  CosMuoGen->setMultiMuonFileFirstEvent(MultiMuonFileFirstEvent);
  CosMuoGen->setMultiMuonNmin(MultiMuonNmin);
  CosMuoGen->setTIFOnly_constant(TIFOnly_constant);
  CosMuoGen->setTIFOnly_linear(TIFOnly_linear);
  CosMuoGen->setMTCCHalf(MTCCHalf);
  CosMuoGen->setPlugVx(PlugVtx);
  CosMuoGen->setPlugVz(PlugVtz);
  CosMuoGen->setRhoAir(VarRhoAir);
  CosMuoGen->setRhoWall(VarRhoWall);
  CosMuoGen->setRhoRock(VarRhoRock);
  CosMuoGen->setRhoClay(VarRhoClay);
  CosMuoGen->setRhoPlug(VarRhoPlug);
  CosMuoGen->setClayWidth(ClayLayerWidth);
  CosMuoGen->setMinEnu(MinEn);
  CosMuoGen->setMaxEnu(MaxEn);
  CosMuoGen->setNuProdAlt(NuPrdAlt);
  CosMuoGen->setAcptAllMu(AllMu);
  produces<HepMCProduct>("unsmeared");
  produces<GenEventInfoProduct>();
  produces<GenRunInfoProduct, edm::Transition::EndRun>();
}

edm::CosMuoGenProducer::~CosMuoGenProducer() { clear(); }

void edm::CosMuoGenProducer::beginLuminosityBlock(LuminosityBlock const& lumi, EventSetup const&) {
  if (!isInitialized_) {
    isInitialized_ = true;
    RandomEngineSentry<CosmicMuonGenerator> randomEngineSentry(CosMuoGen.get(), lumi.index());
    CosMuoGen->initialize(randomEngineSentry.randomEngine());
  }
}

void edm::CosMuoGenProducer::endRunProduce(Run& run, const EventSetup& es) {
  std::unique_ptr<GenRunInfoProduct> genRunInfo(new GenRunInfoProduct());

  double cs = CosMuoGen->getRate();  // flux in Hz, not s^-1m^-2
  if (MultiMuon)
    genRunInfo->setInternalXSec(0.);
  else
    genRunInfo->setInternalXSec(cs);
  genRunInfo->setExternalXSecLO(extCrossSect);
  genRunInfo->setFilterEfficiency(extFilterEff);

  run.put(std::move(genRunInfo));

  CosMuoGen->terminate();
}

void edm::CosMuoGenProducer::clear() {}

void edm::CosMuoGenProducer::produce(Event& e, const edm::EventSetup& es) {
  RandomEngineSentry<CosmicMuonGenerator> randomEngineSentry(CosMuoGen.get(), e.streamID());

  // generate event
  if (!MultiMuon) {
    CosMuoGen->nextEvent();
  } else {
    bool success = CosMuoGen->nextMultiEvent();
    if (!success)
      std::cout << "CosMuoGenProducer.cc: CosMuoGen->nextMultiEvent() failed!" << std::endl;
  }

  if (Debug) {
    std::cout << "CosMuoGenProducer.cc: CosMuoGen->EventWeight=" << CosMuoGen->EventWeight
              << "  CosMuoGen: Nmuons=" << CosMuoGen->Id_sf.size() << std::endl;
    std::cout << "CosMuoGen->Id_at=" << CosMuoGen->Id_at << "  CosMuoGen->Vx_at=" << CosMuoGen->Vx_at
              << "  CosMuoGen->Vy_at=" << CosMuoGen->Vy_at << "  CosMuoGen->Vz_at=" << CosMuoGen->Vz_at
              << "  CosMuoGen->T0_at=" << CosMuoGen->T0_at << std::endl;
    std::cout << "  Px=" << CosMuoGen->Px_at << "  Py=" << CosMuoGen->Py_at << "  Pz=" << CosMuoGen->Pz_at << std::endl;
    for (unsigned int i = 0; i < CosMuoGen->Id_sf.size(); ++i) {
      std::cout << "Id_sf[" << i << "]=" << CosMuoGen->Id_sf[i] << "  Vx_sf[" << i << "]=" << CosMuoGen->Vx_sf[i]
                << "  Vy_sf=" << CosMuoGen->Vy_sf[i] << "  Vz_sf=" << CosMuoGen->Vz_sf[i]
                << "  T0_sf=" << CosMuoGen->T0_sf[i] << "  Px_sf=" << CosMuoGen->Px_sf[i]
                << "  Py_sf=" << CosMuoGen->Py_sf[i] << "  Pz_sf=" << CosMuoGen->Pz_sf[i] << std::endl;
      std::cout << "phi_sf=" << atan2(CosMuoGen->Px_sf[i], CosMuoGen->Pz_sf[i]) << std::endl;
      std::cout << "Id_ug[" << i << "]=" << CosMuoGen->Id_ug[i] << "  Vx_ug[" << i << "]=" << CosMuoGen->Vx_ug[i]
                << "  Vy_ug=" << CosMuoGen->Vy_ug[i] << "  Vz_ug=" << CosMuoGen->Vz_ug[i]
                << "  T0_ug=" << CosMuoGen->T0_ug[i] << "  Px_ug=" << CosMuoGen->Px_ug[i]
                << "  Py_ug=" << CosMuoGen->Py_ug[i] << "  Pz_ug=" << CosMuoGen->Pz_ug[i] << std::endl;
      std::cout << "phi_ug=" << atan2(CosMuoGen->Px_ug[i], CosMuoGen->Pz_ug[i]) << std::endl;
      ;
    }
  }

  auto fEvt = std::make_unique<HepMC::GenEvent>();

  HepMC::GenVertex* Vtx_at = new HepMC::GenVertex(HepMC::FourVector(CosMuoGen->Vx_at,    //[mm]
                                                                    CosMuoGen->Vy_at,    //[mm]
                                                                    CosMuoGen->Vz_at,    //[mm]
                                                                    CosMuoGen->T0_at));  //[mm]
  //cout << "CosMuoGenProducer.cc: Vy_at=" << CosMuoGen->Vy_at << endl;
  HepMC::FourVector p_at(CosMuoGen->Px_at, CosMuoGen->Py_at, CosMuoGen->Pz_at, CosMuoGen->E_at);
  HepMC::GenParticle* Part_at = new HepMC::GenParticle(p_at, CosMuoGen->Id_at, 3);  //Comment mother particle in
  Vtx_at->add_particle_in(Part_at);

  //loop here in case of multi muon events (else just one iteration)
  for (unsigned int i = 0; i < CosMuoGen->Id_sf.size(); ++i) {
    HepMC::FourVector p_sf(CosMuoGen->Px_sf[i], CosMuoGen->Py_sf[i], CosMuoGen->Pz_sf[i], CosMuoGen->E_sf[i]);
    HepMC::GenParticle* Part_sf_in = new HepMC::GenParticle(p_sf, CosMuoGen->Id_sf[i], 3);  //Comment daughter particle
    Vtx_at->add_particle_out(Part_sf_in);

    HepMC::GenVertex* Vtx_sf = new HepMC::GenVertex(
        HepMC::FourVector(CosMuoGen->Vx_sf[i], CosMuoGen->Vy_sf[i], CosMuoGen->Vz_sf[i], CosMuoGen->T0_sf[i]));  //[mm]
    HepMC::GenParticle* Part_sf_out = new HepMC::GenParticle(p_sf, CosMuoGen->Id_sf[i], 3);  //Comment daughter particle

    Vtx_sf->add_particle_in(Part_sf_in);
    Vtx_sf->add_particle_out(Part_sf_out);

    fEvt->add_vertex(Vtx_sf);  //one per muon

    HepMC::GenVertex* Vtx_ug = new HepMC::GenVertex(
        HepMC::FourVector(CosMuoGen->Vx_ug[i], CosMuoGen->Vy_ug[i], CosMuoGen->Vz_ug[i], CosMuoGen->T0_ug[i]));  //[mm]

    HepMC::FourVector p_ug(CosMuoGen->Px_ug[i], CosMuoGen->Py_ug[i], CosMuoGen->Pz_ug[i], CosMuoGen->E_ug[i]);
    HepMC::GenParticle* Part_ug = new HepMC::GenParticle(p_ug, CosMuoGen->Id_ug[i], 1);  //Final state daughter particle

    Vtx_ug->add_particle_in(Part_sf_out);
    Vtx_ug->add_particle_out(Part_ug);

    fEvt->add_vertex(Vtx_ug);  //one per muon
  }

  fEvt->add_vertex(Vtx_at);
  fEvt->set_signal_process_vertex(Vtx_at);

  fEvt->set_event_number(e.id().event());
  fEvt->set_signal_process_id(13);

  fEvt->weights().push_back(CosMuoGen->EventWeight);  // just one event weight
  fEvt->weights().push_back(CosMuoGen->Trials);       // int Trials number (unweighted)

  if (cmVerbosity_)
    fEvt->print();

  std::unique_ptr<GenEventInfoProduct> genEventInfo(new GenEventInfoProduct(fEvt.get()));
  e.put(std::move(genEventInfo));

  //This causes fEvt to be deleted
  std::unique_ptr<HepMCProduct> CMProduct(new HepMCProduct());
  CMProduct->addHepMCData(fEvt.release());
  e.put(std::move(CMProduct), "unsmeared");
}

repository: cms-sw/cmssw

repo_name: cms-sw/cmssw

extension: cc


text:
package loadaverage

import (
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
)

// DataRequest читает данные load average из файла.
func DataRequest() ([]float64, error) {
	const countData = 3 // Кол-во ожидаемых данных по средней загрузке (1 мин, 5 мин, 15 мин).
	var raw string
	val := []float64{0.0, 0.0, 0.0}

	b, err := ioutil.ReadFile("/proc/loadavg")
	if err != nil {
		return nil, fmt.Errorf("cannot read 'loadavg' file: %w", err)
	}
	raw = string(b)

	fray := strings.Split(raw, " ")
	for i := 0; i < countData; i++ {
		val[i], _ = strconv.ParseFloat(fray[i], 64)
	}
	return val, nil
}


text:
// +build darwin

package darwin

/*
#cgo LDFLAGS: -framework CoreFoundation
#include <CoreFoundation/CoreFoundation.h>
*/
import "C"

import (
	"unsafe"
)

///////////////////////////////////////////////////////////////////////////////
// TYPES

type (
	CFString C.CFStringRef
)

///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS

func NewCFString(value string) CFString {
	s := C.CString(value)
	defer C.free(unsafe.Pointer(s))
	this := C.CFStringCreateWithCString(C.kCFAllocatorDefault, s, C.kCFStringEncodingUTF8)
	return CFString(this)
}

func (this CFString) Free() {
	if this != 0 {
		C.CFRelease(C.CFTypeRef(this))
	}
}

func (this CFString) String() string {
	if this == 0 {
		return ""
	}
	// Quick version without allocation
	ptr := C.CFStringGetCStringPtr(C.CFStringRef(this), C.kCFStringEncodingUTF8)
	if ptr != nil {
		return C.GoString(ptr)
	}
	// Next find the buffer size necessary
	var length C.CFIndex
	length_ := C.CFStringGetLength(C.CFStringRef(this))
	range_ := C.CFRange{0, length_}
	if C.CFStringGetBytes(C.CFStringRef(this), range_, C.kCFStringEncodingUTF8, 0, C.false, nil, 0, &length) == 0 {
		return ""
	}
	bytes := make([]byte, length)
	if C.CFStringGetBytes(C.CFStringRef(this), range_, C.kCFStringEncodingUTF8, 0, C.false, (*C.uchar)(unsafe.Pointer(&bytes[0])), length, nil) == 0 {
		return ""
	}
	return string(bytes)
}

repository: wade-welles/gopi-hw

repo_name: wade-welles/gopi-hw


text:
// Code generated by counterfeiter. DO NOT EDIT.
package workerfakes

import (
	"context"
	"sync"

	"github.com/jace-ys/mobydick-action/bin/pkg/worker"
)

type FakeJob struct {
	ProcessStub        func(context.Context) error
	processMutex       sync.RWMutex
	processArgsForCall []struct {
		arg1 context.Context
	}
	processReturns struct {
		result1 error
	}
	processReturnsOnCall map[int]struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeJob) Process(arg1 context.Context) error {
	fake.processMutex.Lock()
	ret, specificReturn := fake.processReturnsOnCall[len(fake.processArgsForCall)]
	fake.processArgsForCall = append(fake.processArgsForCall, struct {
		arg1 context.Context
	}{arg1})
	fake.recordInvocation("Process", []interface{}{arg1})
	fake.processMutex.Unlock()
	if fake.ProcessStub != nil {
		return fake.ProcessStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.processReturns
	return fakeReturns.result1
}

func (fake *FakeJob) ProcessCallCount() int {
	fake.processMutex.RLock()
	defer fake.processMutex.RUnlock()
	return len(fake.processArgsForCall)
}

func (fake *FakeJob) ProcessCalls(stub func(context.Context) error) {
	fake.processMutex.Lock()
	defer fake.processMutex.Unlock()
	fake.ProcessStub = stub
}

func (fake *FakeJob) ProcessArgsForCall(i int) context.Context {
	fake.processMutex.RLock()
	defer fake.processMutex.RUnlock()
	argsForCall := fake.processArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakeJob) ProcessReturns(result1 error) {
	fake.processMutex.Lock()
	defer fake.processMutex.Unlock()
	fake.ProcessStub = nil
	fake.processReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeJob) ProcessReturnsOnCall(i int, result1 error) {
	fake.processMutex.Lock()
	defer fake.processMutex.Unlock()
	fake.ProcessStub = nil
	if fake.processReturnsOnCall == nil {
		fake.processReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.processReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeJob) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.processMutex.RLock()
	defer fake.processMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeJob) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ worker.Job = new(FakeJob)

repository: jace-ys/mobydick-action

repo_name: jace-ys/mobydick-action


text:
SECTION = "unknown"
require popt_${PV}.bb
inherit native

S = "${WORKDIR}/popt-${PV}"
FILESDIR = "${@os.path.dirname(bb.data.getVar('FILE',d,1))}/popt-${PV}"


text:
package store

type Metric struct {
	Metric     topSQLTags `json:"metric"`
	Timestamps []uint64   `json:"timestamps"` // in millisecond
	Values     []uint32   `json:"values"`
}

type topSQLTags struct {
	Name         string `json:"__name__"`
	Instance     string `json:"instance"`
	InstanceType string `json:"instance_type"`
	SQLDigest    string `json:"sql_digest"`
	PlanDigest   string `json:"plan_digest,omitempty"`
}

repository: isgasho/ng-monitoring

repo_name: isgasho/ng-monitoring


text:
// Copyright 2014 The Serviced 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 addressassignment

import (
	"fmt"
	"github.com/zenoss/elastigo/search"
	"github.com/control-center/serviced/datastore"
)

//NewStore creates a AddressAssignmentStore store
func NewStore() *Store {
	return &Store{}
}

//Store type for interacting with AddressAssignment persistent storage
type Store struct {
	datastore.DataStore
}

func (s *Store) GetServiceAddressAssignments(ctx datastore.Context, serviceID string) ([]AddressAssignment, error) {
	query := fmt.Sprintf("ServiceID:%s", serviceID)
	q := datastore.NewQuery(ctx)
	elasticQuery := search.Query().Search(query)
	search := search.Search("controlplane").Type(kind).Size("50000").Query(elasticQuery)
	results, err := q.Execute(search)
	if err != nil {
		return nil, err
	}
	return convert(results)
}

//Key creates a Key suitable for getting, putting and deleting AddressAssignment
func Key(id string) datastore.Key {
	return datastore.NewKey(kind, id)
}

func convert(results datastore.Results) ([]AddressAssignment, error) {
	assignments := make([]AddressAssignment, results.Len())
	for idx := range assignments {
		var aa AddressAssignment
		err := results.Get(idx, &aa)
		if err != nil {
			return nil, err
		}

		assignments[idx] = aa
	}
	return assignments, nil
}

var kind = "addressassignment"

repository: sramirezm/serviced

repo_name: sramirezm/serviced