text:
package jose

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"
	"testing"

	"github.com/smallstep/assert"
	"go.step.sm/crypto/pemutil"
)

const (
	ecdsaPublicKey keyType = iota
	ecdsaPrivateKey
	ed25519PublicKey
	ed25519PrivateKey
	rsaPublicKey
	rsaPrivateKey
	octKey
)

type testdata struct {
	typ       keyType
	encrypted bool
}

var files = map[string]testdata{
	"testdata/oct.json":           {octKey, false},
	"testdata/oct.enc.json":       {octKey, true},
	"testdata/okp.pub.json":       {ed25519PublicKey, false},
	"testdata/okp.priv.json":      {ed25519PrivateKey, false},
	"testdata/okp.enc.priv.json":  {ed25519PrivateKey, true},
	"testdata/p256.pub.json":      {ecdsaPublicKey, false},
	"testdata/p256.priv.json":     {ecdsaPrivateKey, false},
	"testdata/p256.enc.priv.json": {ecdsaPrivateKey, true},
	"testdata/rsa.pub.json":       {rsaPublicKey, false},
	"testdata/rsa.priv.json":      {rsaPrivateKey, false},
	"testdata/rsa.enc.priv.json":  {rsaPrivateKey, true},
}

var pemFiles = map[string]testdata{
	"../pemutil/testdata/openssl.p256.pem":              {ecdsaPrivateKey, false},
	"../pemutil/testdata/openssl.p256.pub.pem":          {ecdsaPublicKey, false},
	"../pemutil/testdata/openssl.p256.enc.pem":          {ecdsaPrivateKey, true},
	"../pemutil/testdata/openssl.p384.pem":              {ecdsaPrivateKey, false},
	"../pemutil/testdata/openssl.p384.pub.pem":          {ecdsaPublicKey, false},
	"../pemutil/testdata/openssl.p384.enc.pem":          {ecdsaPrivateKey, true},
	"../pemutil/testdata/openssl.p521.pem":              {ecdsaPrivateKey, false},
	"../pemutil/testdata/openssl.p521.pub.pem":          {ecdsaPublicKey, false},
	"../pemutil/testdata/openssl.p521.enc.pem":          {ecdsaPrivateKey, true},
	"../pemutil/testdata/openssl.rsa1024.pem":           {rsaPrivateKey, false},
	"../pemutil/testdata/openssl.rsa1024.pub.pem":       {rsaPublicKey, false},
	"../pemutil/testdata/openssl.rsa1024.enc.pem":       {rsaPrivateKey, true},
	"../pemutil/testdata/openssl.rsa2048.pem":           {rsaPrivateKey, false},
	"../pemutil/testdata/openssl.rsa2048.pub.pem":       {rsaPublicKey, false},
	"../pemutil/testdata/openssl.rsa2048.enc.pem":       {rsaPrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.ed25519.pem":     {ed25519PrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.ed25519.pub.pem": {ed25519PublicKey, false},
	"../pemutil/testdata/pkcs8/openssl.ed25519.enc.pem": {ed25519PrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.p256.pem":        {ecdsaPrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.p256.pub.pem":    {ecdsaPublicKey, false},
	"../pemutil/testdata/pkcs8/openssl.p256.enc.pem":    {ecdsaPrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.p384.pem":        {ecdsaPrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.p384.pub.pem":    {ecdsaPublicKey, false},
	"../pemutil/testdata/pkcs8/openssl.p384.enc.pem":    {ecdsaPrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.p521.pem":        {ecdsaPrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.p521.pub.pem":    {ecdsaPublicKey, false},
	"../pemutil/testdata/pkcs8/openssl.p521.enc.pem":    {ecdsaPrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.rsa2048.pem":     {rsaPrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.rsa2048.pub.pem": {rsaPublicKey, false},
	"../pemutil/testdata/pkcs8/openssl.rsa2048.enc.pem": {rsaPrivateKey, true},
	"../pemutil/testdata/pkcs8/openssl.rsa4096.pem":     {rsaPrivateKey, false},
	"../pemutil/testdata/pkcs8/openssl.rsa4096.pub.pem": {rsaPublicKey, false},
}

func validateReadKey(t *testing.T, fn, pass string, td testdata) {
	var err error
	var jwk *JSONWebKey

	if td.encrypted {
		jwk, err = ReadKey(fn, WithPassword([]byte(pass)))
	} else {
		jwk, err = ReadKey(fn)
	}
	assert.NoError(t, err)

	assert.NoError(t, ValidateJWK(jwk))

	switch td.typ {
	case ecdsaPublicKey:
		assert.Type(t, &ecdsa.PublicKey{}, jwk.Key)
	case ecdsaPrivateKey:
		assert.Type(t, &ecdsa.PrivateKey{}, jwk.Key)
	case ed25519PublicKey:
		assert.Type(t, ed25519.PublicKey{}, jwk.Key)
	case ed25519PrivateKey:
		assert.Type(t, ed25519.PrivateKey{}, jwk.Key)
	case rsaPublicKey:
		assert.Type(t, &rsa.PublicKey{}, jwk.Key)
	case rsaPrivateKey:
		assert.Type(t, &rsa.PrivateKey{}, jwk.Key)
	case octKey:
		assert.Type(t, []byte{}, jwk.Key)
	default:
		t.Errorf("type %T not supported", jwk.Key)
	}

	if jwk.IsPublic() == false && jwk.KeyID != "" {
		hash, err := jwk.Thumbprint(crypto.SHA256)
		assert.NoError(t, err)
		assert.Equals(t, base64.RawURLEncoding.EncodeToString(hash), jwk.KeyID)
	}

	if td.encrypted {
		jwkPriv, err := ReadKey(strings.Replace(fn, ".enc", "", 1))
		assert.NoError(t, err)
		assert.Equals(t, jwkPriv, jwk)
	}
}

func TestReadKey(t *testing.T) {
	for fn, td := range files {
		fn, td := fn, td
		t.Run(fn, func(t *testing.T) {
			validateReadKey(t, fn, "password", td)
		})
	}

	for fn, td := range pemFiles {
		fn, td := fn, td
		t.Run(fn, func(t *testing.T) {
			validateReadKey(t, fn, "mypassword", td)
		})
	}

	if _, err := ReadKey("testdata/missing.txt"); err == nil {
		t.Errorf("ReadKey() error = %v, wantErr true", err)
	}
}

func TestReadKey_https(t *testing.T) {
	ok, err := ioutil.ReadFile("testdata/okp.pub.json")
	assert.FatalError(t, err)
	key, err := base64.RawURLEncoding.DecodeString("L4WYxHsMVaspyhWuSp84v2meEYMEUdYnrn-w-jqP6iw")
	assert.FatalError(t, err)

	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.RequestURI {
		case "/ok":
			w.Header().Set("ContentType", "application/jwk-set+json")
			w.WriteHeader(http.StatusOK)
			fmt.Fprintln(w, string(ok))
		case "/empty":
			w.Header().Set("ContentType", "application/jwk-set+json")
			w.WriteHeader(http.StatusOK)
			fmt.Fprintln(w, "{}")
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprintln(w, http.StatusText(http.StatusNotFound))
		}
	}))
	srvClient := srv.Client()
	defer func() {
		srv.Close()
		http.DefaultClient = &http.Client{}
	}()

	type args struct {
		client   *http.Client
		filename string
		opts     []Option
	}
	tests := []struct {
		name    string
		args    args
		want    *JSONWebKey
		wantErr bool
	}{
		{"ok", args{srvClient, srv.URL + "/ok", nil}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "EdDSA",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"failWithKid", args{srvClient, srv.URL + "/ok", []Option{WithKid("foobar")}}, nil, true},
		{"failEmpty", args{srvClient, srv.URL + "/empty", nil}, nil, true},
		{"failNotFound", args{srvClient, srv.URL + "/notFound", nil}, nil, true},
		{"failClient", args{&http.Client{}, srv.URL + "/ok", nil}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			http.DefaultClient = tt.args.client
			got, err := ReadKey(tt.args.filename, tt.args.opts...)
			if (err != nil) != tt.wantErr {
				t.Errorf("ReadKeySet() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ReadKeySet() = \n%#v, want \n%#v", got, tt.want)
			}
		})
	}
}

func TestReadKeyPasswordFile(t *testing.T) {
	jwk, err := ReadKey("testdata/oct.txt", WithAlg("HS256"), WithUse("sig"), WithKid("the-kid"))
	assert.FatalError(t, err)
	assert.Equals(t, []byte("a true random password"), jwk.Key)
	assert.Equals(t, HS256, jwk.Algorithm)
	assert.Equals(t, "sig", jwk.Use)
	assert.Equals(t, "the-kid", jwk.KeyID)
}

func TestParseKey(t *testing.T) {
	marshal := func(i interface{}) []byte {
		b, err := json.Marshal(i)
		if err != nil {
			t.Fatal(err)
		}
		return b
	}
	read := func(filename string) []byte {
		b, err := ioutil.ReadFile(filename)
		if err != nil {
			t.Fatal(err)
		}
		return b
	}

	ecKey := fixJWK(mustGenerateJWK(t, "EC", "P-256", "ES256", "enc", "", 0))
	rsaKey := fixJWK(mustGenerateJWK(t, "RSA", "", "RS256", "sig", "", 1024))
	rsaPSSKey := fixJWK(mustGenerateJWK(t, "RSA", "", "PS256", "enc", "", 1024))
	edKey := fixJWK(mustGenerateJWK(t, "OKP", "Ed25519", "EdDSA", "sig", "", 0))
	octKey := fixJWK(mustGenerateJWK(t, "oct", "", "HS256", "sig", "", 64))

	encKey, err := EncryptJWK(edKey, testPassword)
	assert.FatalError(t, err)
	encKeyCompact, err := encKey.CompactSerialize()
	assert.FatalError(t, err)

	pemKey, err := pemutil.Read("../pemutil/testdata/pkcs8/openssl.ed25519.pem")
	assert.FatalError(t, err)

	ecKey.KeyID, err = Thumbprint(ecKey)
	assert.FatalError(t, err)

	type args struct {
		b    []byte
		opts []Option
	}
	tests := []struct {
		name    string
		args    args
		want    *JSONWebKey
		wantErr bool
	}{
		{"ec", args{marshal(ecKey), nil}, ecKey, false},
		{"rsa", args{marshal(rsaKey), nil}, rsaKey, false},
		{"rsa-pss", args{marshal(rsaPSSKey), nil}, rsaPSSKey, false},
		{"okp", args{marshal(edKey), nil}, edKey, false},
		{"oct", args{marshal(octKey), nil}, octKey, false},
		{"encryptedCompactWithPassword", args{[]byte(encKeyCompact), []Option{WithPassword(testPassword)}}, edKey, false},
		{"encryptedFullWithPasswordFile", args{[]byte(encKey.FullSerialize()), []Option{WithPasswordFile("testdata/passphrase.txt")}}, edKey, false},
		{"pemPrivate", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pem"), nil}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPublic", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pub.pem"), nil}, &JSONWebKey{
			Key:       pemKey.(ed25519.PrivateKey).Public(),
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithPassword", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.enc.pem"), []Option{WithPassword([]byte("mypassword"))}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithPasswordFile", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.enc.pem"), []Option{WithPasswordFile("../pemutil/testdata/password.txt")}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithPasswordPrompter", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.enc.pem"), []Option{WithPasswordPrompter("What's the password", func(s string) ([]byte, error) {
			return []byte("mypassword"), nil
		})}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithKid", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pem"), []Option{WithKid("foobarzar")}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "foobarzar",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithUse", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pem"), []Option{WithUse("enc")}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Use:       "enc",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithAlg", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pem"), []Option{WithAlg("EdDSA")}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "EdDSA",
		}, false},
		{"pemPrivateWithAlgWithSubtle", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.pem"), []Option{WithAlg("FOOBAR"), WithSubtle(true)}}, &JSONWebKey{
			Key:       pemKey,
			KeyID:     "vEk4UARa85PrW0eea2zeVLqGBF-n5Jzd9GVmKAc0AHQ",
			Algorithm: "FOOBAR",
		}, false},
		{"octPrivateWithAlg", args{testPassword, []Option{WithAlg("HS256")}}, &JSONWebKey{
			Key:       testPassword,
			Algorithm: "HS256",
		}, false},
		{"octPrivateWithAlgWithKid", args{testPassword, []Option{WithAlg("HS256"), WithKid("foobarzar")}}, &JSONWebKey{
			Key:       testPassword,
			KeyID:     "foobarzar",
			Algorithm: "HS256",
		}, false},
		{"failPassword", args{[]byte(encKeyCompact), []Option{WithPassword([]byte("bad password"))}}, nil, true},
		{"failMissingFile", args{[]byte(encKeyCompact), []Option{WithPasswordFile("testdata/missing.txt")}}, nil, true},
		{"failPEMPassword", args{read("../pemutil/testdata/pkcs8/openssl.ed25519.enc.pem"), []Option{WithPassword([]byte("bad password"))}}, nil, true},
		{"failECBWongAlg", args{marshal(ecKey), []Option{WithAlg("FOOBAR")}}, nil, true},
		{"failECWrongKid", args{marshal(ecKey), []Option{WithKid("foobarzar")}}, nil, true},
		{"failOCTMissingOptions", args{testPassword, nil}, nil, true},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			got, err := ParseKey(tt.args.b, tt.args.opts...)
			if (err != nil) != tt.wantErr {
				t.Errorf("ParseKey() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			// Make the rsa keys equal if they are
			if tt.want != nil {
				if k, ok := tt.want.Key.(*rsa.PrivateKey); ok {
					if !rsaEqual(k, got.Key) {
						t.Errorf("ParseKey() got = %v, want %v", got, tt.want)
						return
					}
					got.Key = k
				}
			}

			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ParseKey() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestReadKeySet(t *testing.T) {
	jwk, err := ReadKeySet("testdata/jwks.json", WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"))
	assert.NoError(t, err)
	assert.Type(t, ed25519.PublicKey{}, jwk.Key)
	assert.Equals(t, "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM", jwk.KeyID)

	jwk, err = ReadKeySet("testdata/jwks.json", WithKid("V93A-Yh7Bhw1W2E0igFciviJzX4PXPswoVgriehm9Co"))
	assert.NoError(t, err)
	assert.Type(t, &ecdsa.PublicKey{}, jwk.Key)
	assert.Equals(t, "V93A-Yh7Bhw1W2E0igFciviJzX4PXPswoVgriehm9Co", jwk.KeyID)

	jwk, err = ReadKeySet("testdata/jwks.json", WithKid("duplicated"))
	assert.Error(t, err)
	assert.Equals(t, "multiple keys with kid duplicated have been found on testdata/jwks.json", err.Error())
	assert.Nil(t, jwk)

	jwk, err = ReadKeySet("testdata/jwks.json", WithKid("missing"))
	assert.Error(t, err)
	assert.Equals(t, "cannot find key with kid missing on testdata/jwks.json", err.Error())
	assert.Nil(t, jwk)

	jwk, err = ReadKeySet("testdata/empty.json", WithKid("missing"))
	assert.Error(t, err)
	assert.Equals(t, "cannot find key with kid missing on testdata/empty.json", err.Error())
	assert.Nil(t, jwk)
}

func TestReadKeySet_https(t *testing.T) {
	ok, err := ioutil.ReadFile("testdata/jwks.json")
	assert.FatalError(t, err)
	key, err := base64.RawURLEncoding.DecodeString("L4WYxHsMVaspyhWuSp84v2meEYMEUdYnrn-w-jqP6iw")
	assert.FatalError(t, err)

	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.RequestURI {
		case "/ok":
			w.Header().Set("ContentType", "application/jwk-set+json")
			w.WriteHeader(http.StatusOK)
			fmt.Fprintln(w, string(ok))
		case "/empty":
			w.Header().Set("ContentType", "application/jwk-set+json")
			w.WriteHeader(http.StatusOK)
			fmt.Fprintln(w, "{}")
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprintln(w, http.StatusText(http.StatusNotFound))
		}
	}))
	srvClient := srv.Client()
	defer func() {
		srv.Close()
		http.DefaultClient = &http.Client{}
	}()

	type args struct {
		client   *http.Client
		filename string
		opts     []Option
	}
	tests := []struct {
		name    string
		args    args
		want    *JSONWebKey
		wantErr bool
	}{
		{"ok", args{srvClient, srv.URL + "/ok", []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "EdDSA",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"failEmpty", args{srvClient, srv.URL + "/empty", []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, nil, true},
		{"failNotFound", args{srvClient, srv.URL + "/notFound", []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, nil, true},
		{"failClient", args{&http.Client{}, srv.URL + "/ok", []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, nil, true},
		{"failNoOptions", args{srvClient, srv.URL + "/ok", nil}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			http.DefaultClient = tt.args.client
			got, err := ReadKeySet(tt.args.filename, tt.args.opts...)
			if (err != nil) != tt.wantErr {
				t.Errorf("ReadKeySet() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ReadKeySet() = \n%#v, want \n%#v", got, tt.want)
			}
		})
	}
}

func TestGuessJWKAlgorithm(t *testing.T) {
	p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	assert.FatalError(t, err)
	p384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	assert.FatalError(t, err)
	p521, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
	assert.FatalError(t, err)
	rsa, err := rsa.GenerateKey(rand.Reader, 2048)
	assert.FatalError(t, err)
	edPub, edPriv, err := ed25519.GenerateKey(rand.Reader)
	assert.FatalError(t, err)

	tests := []struct {
		jwk      *JSONWebKey
		expected string
	}{
		{&JSONWebKey{Key: []byte{}, Use: ""}, HS256},
		{&JSONWebKey{Key: []byte{}, Use: "sig"}, HS256},
		{&JSONWebKey{Key: []byte{}, Use: "enc"}, "A256GCMKW"},
		{&JSONWebKey{Key: p256, Use: ""}, ES256},
		{&JSONWebKey{Key: p384, Use: "sig"}, ES384},
		{&JSONWebKey{Key: p521, Use: "enc"}, "ECDH-ES"},
		{&JSONWebKey{Key: p256.Public(), Use: ""}, ES256},
		{&JSONWebKey{Key: p384.Public(), Use: "sig"}, ES384},
		{&JSONWebKey{Key: p521.Public(), Use: "enc"}, "ECDH-ES"},
		{&JSONWebKey{Key: rsa, Use: ""}, RS256},
		{&JSONWebKey{Key: rsa, Use: "sig"}, RS256},
		{&JSONWebKey{Key: rsa, Use: "enc"}, "RSA-OAEP-256"},
		{&JSONWebKey{Key: rsa.Public(), Use: ""}, RS256},
		{&JSONWebKey{Key: rsa.Public(), Use: "sig"}, RS256},
		{&JSONWebKey{Key: rsa.Public(), Use: "enc"}, "RSA-OAEP-256"},
		{&JSONWebKey{Key: edPub, Use: ""}, EdDSA},
		{&JSONWebKey{Key: edPub, Use: "sig"}, EdDSA},
		{&JSONWebKey{Key: edPriv, Use: ""}, EdDSA},
		{&JSONWebKey{Key: edPriv, Use: "sig"}, EdDSA},
	}

	// With context
	ctx, err := new(context).apply(WithAlg(HS256))
	assert.NoError(t, err)
	jwk := &JSONWebKey{Key: []byte("password")}
	guessJWKAlgorithm(ctx, jwk)
	assert.Equals(t, HS256, jwk.Algorithm)

	// With algorithm set
	ctx, err = new(context).apply(WithAlg(HS256))
	assert.NoError(t, err)
	jwk = &JSONWebKey{Key: []byte("password"), Algorithm: HS384}
	guessJWKAlgorithm(ctx, jwk)
	assert.Equals(t, HS384, jwk.Algorithm)

	// With no defaults
	ctx, err = new(context).apply(WithNoDefaults(true))
	assert.NoError(t, err)
	jwk = mustGenerateJWK(t, "EC", "P-256", "ES256", "sig", "", 0)
	jwk.Algorithm = ""
	guessJWKAlgorithm(ctx, jwk)
	assert.Equals(t, ES256, jwk.Algorithm)

	pub := jwk.Public()
	pub.Algorithm = ""
	guessJWKAlgorithm(ctx, &pub)
	assert.Equals(t, ES256, pub.Algorithm)

	jwk = mustGenerateJWK(t, "OKP", "Ed25519", "EdDSA", "sig", "", 0)
	jwk.Algorithm = ""
	guessJWKAlgorithm(ctx, jwk)
	assert.Equals(t, EdDSA, jwk.Algorithm)

	pub = jwk.Public()
	pub.Algorithm = ""
	guessJWKAlgorithm(ctx, &pub)
	assert.Equals(t, EdDSA, pub.Algorithm)

	// Defaults
	for _, tc := range tests {
		guessJWKAlgorithm(new(context), tc.jwk)
		assert.Equals(t, tc.expected, tc.jwk.Algorithm)
	}
}

func TestParseKeySet(t *testing.T) {
	b, err := ioutil.ReadFile("testdata/jwks.json")
	assert.FatalError(t, err)
	key, err := base64.RawURLEncoding.DecodeString("L4WYxHsMVaspyhWuSp84v2meEYMEUdYnrn-w-jqP6iw")
	assert.FatalError(t, err)

	jwe := mustEncryptData(t, b, testPassword)
	encryptedJSON := []byte(jwe.FullSerialize())
	encryptedCompact, err := jwe.CompactSerialize()
	assert.FatalError(t, err)

	type args struct {
		b    []byte
		opts []Option
	}
	tests := []struct {
		name    string
		args    args
		want    *JSONWebKey
		wantErr bool
	}{
		{"ok", args{b, []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "EdDSA",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"okEncryptedJSON", args{encryptedJSON, []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"), WithPassword(testPassword)}}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "EdDSA",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"okEncryptedCompact", args{[]byte(encryptedCompact), []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"), WithPasswordFile("testdata/passphrase.txt")}}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "EdDSA",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"okWithAlgSubtle", args{b, []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"), WithSubtle(true), WithAlg("FOOBAR")}}, &JSONWebKey{
			Key:                         ed25519.PublicKey(key),
			KeyID:                       "qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM",
			Algorithm:                   "FOOBAR",
			Use:                         "sig",
			Certificates:                []*x509.Certificate{},
			CertificateThumbprintSHA1:   []byte{},
			CertificateThumbprintSHA256: []byte{},
		}, false},
		{"failOptions", args{b, []Option{WithPasswordFile("testdata/missing.txt")}}, nil, true},
		{"failDecrypt", args{encryptedJSON, []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"), WithPassword([]byte("bad-password"))}}, nil, true},
		{"failNoOptions", args{b, []Option{}}, nil, true},
		{"failBadData", args{[]byte("foo"), []Option{}}, nil, true},
		{"failEmpty", args{[]byte("{}"), []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM")}}, nil, true},
		{"failDuplicated", args{b, []Option{WithKid("duplicated")}}, nil, true},
		{"failWithAlg", args{b, []Option{WithKid("qiCJG7r2L80rmWRrZMPfpanQHmZRcncOG7A7MBWn9qM"), WithAlg("FOOBAR")}}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := ParseKeySet(tt.args.b, tt.args.opts...)
			if (err != nil) != tt.wantErr {
				t.Errorf("ParseKeySet() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ParseKeySet() = %v, want %v", got, tt.want)
			}
		})
	}
}

func Test_guessKeyType(t *testing.T) {
	marshal := func(i interface{}) []byte {
		b, err := json.Marshal(i)
		if err != nil {
			t.Fatal(err)
		}
		return b
	}

	ecKey := mustGenerateJWK(t, "EC", "P-256", "ES256", "enc", "", 0)
	rsaKey := mustGenerateJWK(t, "RSA", "", "RS256", "sig", "", 1024)
	rsaPSSKey := mustGenerateJWK(t, "RSA", "", "PS256", "enc", "", 1024)
	edKey := mustGenerateJWK(t, "OKP", "Ed25519", "EdDSA", "sig", "", 0)
	octKey := mustGenerateJWK(t, "oct", "", "HS256", "sig", "", 64)
	octHS384 := mustGenerateJWK(t, "oct", "", "HS384", "sig", "", 64)

	rsaPEM, err := ioutil.ReadFile("../pemutil/testdata/openssl.p256.pem")
	assert.FatalError(t, err)

	type args struct {
		ctx  *context
		data []byte
	}
	tests := []struct {
		name string
		args args
		want keyType
	}{
		{"ec", args{&context{}, marshal(ecKey)}, jwkKeyType},
		{"rsaKey", args{&context{}, marshal(rsaKey)}, jwkKeyType},
		{"rsaPSSKey", args{&context{}, marshal(rsaPSSKey)}, jwkKeyType},
		{"edKey", args{&context{}, marshal(edKey)}, jwkKeyType},
		{"octKey", args{&context{}, marshal(octKey)}, jwkKeyType},
		{"encrypted", args{&context{}, marshal(mustEncryptJWK(t, ecKey, testPassword))}, jwkKeyType},
		{"rsaPEM", args{&context{}, rsaPEM}, pemKeyType},
		{"encryptedAlgHS256", args{&context{alg: "HS256"}, []byte(mustEncryptJWK(t, octKey, testPassword).FullSerialize())}, jwkKeyType},
		{"jwkAlgHS384", args{&context{alg: "HS384"}, marshal(octHS384)}, jwkKeyType},
		{"bloblAlgHS512", args{&context{alg: "HS512"}, testPassword}, octKeyType},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := guessKeyType(tt.args.ctx, tt.args.data); got != tt.want {
				t.Errorf("guessKeyType() = %v, want %v", got, tt.want)
			}
		})
	}
}

repository: thalesfsp/crypto

repo_name: thalesfsp/crypto


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/demo_OptimalPlanning.dir/OptimalPlanning.cpp.o"
  "../bin/demo_OptimalPlanning.pdb"
  "../bin/demo_OptimalPlanning"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/demo_OptimalPlanning.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)

repository: Insightque/DesiredOrientationRRT

license_type: permissive

repo_name: Insightque/DesiredOrientationRRT

branch_name: refs/heads/master

gha_license_id: NOASSERTION

extension: cmake


text:
@article{decelle_inference_2011,
 abstract = {We present an asymptotically exact analysis of the problem of detecting communities in sparse random networks generated by stochastic block models. Using the cavity method of statistical physics and its relationship to belief propagation, we unveil a phase transition from a regime where we can infer the correct group assignments of the nodes to one where these groups are undetectable. Our approach yields an optimal inference algorithm for detecting modules, including both assortative and disassortative functional modules, assessing their significance, and learning the parameters of the underlying block model. Our algorithm is scalable and applicable to real-world networks, as long as they are well described by the block model.},
 author = {Decelle, Aurelien and Krzakala, Florent and Moore, Cristopher and Zdeborová, Lenka},
 doi = {10.1103/PhysRevLett.107.065701},
 file = {APS Snapshot:/Users/florentkrzakala/Zotero/storage/FVYQD7LW/PhysRevLett.107.html:text/html;Full Text PDF:/Users/florentkrzakala/Zotero/storage/LRWBQWAD/Decelle et al. - 2011 - Inference and Phase Transitions in the Detection o.pdf:application/pdf},
 journal = {Phys. Rev. Lett.},
 month = {August},
 number = {6},
 pages = {065701},
 title = {Inference and Phase Transitions in the Detection of Modules in Sparse Networks},
 url = {https://link.aps.org/doi/10.1103/PhysRevLett.107.065701},
 urldate = {2019-07-01},
 volume = {107},
 year = {2011}
}

license: MIT

repository: krzakala/academic-kickstart

repo_name: krzakala/academic-kickstart

extension: bib


text:
SUMMARY = "Python 2 wrapper around the OpenSSL library"
DESCRIPTION = "High-level wrapper around a subset of the OpenSSL library, includes \n\
.\n\
  * SSL.Connection objects, wrapping the methods of Python's portable\n\
    sockets\n\
  * Callbacks written in Python\n\
  * Extensive error-handling mechanism, mirroring OpenSSL's error\n\
    codes\n\
.\n\
A lot of the object methods do nothing more than calling a\n\
corresponding function in the OpenSSL library."
HOMEPAGE = "https://github.com/pyca/pyopenssl"
LICENSE = "Apache-2.0"
SECTION = "python"
DEPENDS = "python openssl"
LIC_FILES_CHKSUM = "file://LICENSE;md5=3b83ef96387f14655fc854ddc3c6bd57"

PR = "r0"
inherit debian-package
PV = "0.14"
DPN = "pyopenssl"

inherit allarch setuptools

RDEPENDS_${PN} += "python-cryptography python-six"

BBCLASSEXTEND = "native"

repository: manut/meta-combo

repo_name: manut/meta-combo

branch_name: refs/heads/morty

gha_language: BitBake

extension: bb


text:
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://COPYING;md5=344895f253c32f38e182dcaf30fe8a35"

PV = "0.1.0+svnr${SRCPV}"
PR = "${INC_PR}.0"

require e-module.inc

do_configure_prepend() {
    autopoint || touch config.rpath
}

# Calls /usr/bin/eject for media
RRECOMMENDS_${PN} += "eject"

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace

gha_language: Python


text:
@incollection{aubin_committee_2018,
 author = {Aubin, Benjamin and Maillard, Antoine and barbier, jean and Krzakala, Florent and Macris, Nicolas and Zdeborová, Lenka},
 booktitle = {Advances in Neural Information Processing Systems 31},
 editor = {Bengio, S. and Wallach, H. and Larochelle, H. and Grauman, K. and Cesa-Bianchi, N. and Garnett, R.},
 file = {NIPS Full Text PDF:/Users/florentkrzakala/Zotero/storage/A5GWZ2A4/Aubin et al. - 2018 - The committee machine Computational to statistica.pdf:application/pdf;NIPS Snapshot:/Users/florentkrzakala/Zotero/storage/27VYTKG4/7584-the-committee-machine-computational-to-statistical-gaps-in-learning-a-two-layers-neural-ne.html:text/html},
 pages = {3223--3234},
 publisher = {Curran Associates, Inc.},
 shorttitle = {The committee machine},
 title = {The committee machine: Computational to statistical gaps in learning a two-layers neural network},
 url = {http://papers.nips.cc/paper/7584-the-committee-machine-computational-to-statistical-gaps-in-learning-a-two-layers-neural-network.pdf},
 urldate = {2019-07-01},
 year = {2018}
}


text:
SECTION = "devel/chicken"
DESCRIPTION = "Automatically compile Scheme scripts on demand"
LICENSE = "PD"
LIC_FILES_CHKSUM = "file://autocompile.meta;md5=5106ce847311ac5221a5b72d0bd9bde9"
DEPENDS_append_class-cross = " chicken-egg-matchable-cross chicken-egg-regex-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-matchable-crosssdk chicken-egg-regex-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-matchable nativesdk-chicken-egg-regex chicken-egg-matchable-crosssdk chicken-egg-regex-crosssdk"
DEPENDS = " chicken-egg-matchable chicken-egg-regex chicken-egg-matchable-cross chicken-egg-regex-cross"
RDEPENDS_${PN} = " chicken-egg-matchable chicken-egg-regex"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/autocompile/autocompile-${PV}.tar.gz"

SRC_URI[md5sum] = "0fdef45464e3e554eef5e8f26321a151"
SRC_URI[sha256sum] = "abff67c228b2d96ab9d604585c8b20f661b40dc5d3dc1a565cda1d2233039640"

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

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
SUMMARY = "Composable style cycles"
HOMEPAGE = "http://github.com/matplotlib/cycler"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=7713fe42cd766b15c710e19392bfa811"

SRC_URI[sha256sum] = "9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f"

inherit pypi setuptools3

RDEPENDS:${PN} += "\
    python3-core \
    python3-six \
"

BBCLASSEXTEND = "native nativesdk"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_license_id: MIT


text:
@Misc{oecd,
  author       = {{OECD}},
  title        = {Database on Immigrants in OECD and non-OECD Countries: DIOC},
  howpublished = {Data Repository: http://www.oecd.org/els/mig/dioc.htm},
  owner        = {Yee Sern Tan},
  url          = {http://www.oecd.org/els/mig/dioc.htm},
}

@Misc{worldbank_migr,
  author       = {{World Bank Group}},
  title        = {Global Bilateral Migration},
  howpublished = {Database: http://databank.worldbank.org/data/reports.aspx?
  \\source=global-bilateral-migration},
  owner        = {Yee Sern Tan},
  url          = {http://databank.worldbank.org/data/reports.aspx?source=global-bilateral-migration},
}

@Misc{color,
  author       = {{Strager}},
  title        = {How to automatically generate N "distinct" colors?},
  howpublished = {Online forum: http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors},
  owner        = {Yee Sern Tan},
  url          = {http://stackoverflow.com/questions/470690/how-to-automatically-generate-n-distinct-colors},
}

@Misc{hamerly,
  author       = {Greg Hamerly},
  title        = {Population-weighted European state centers},
  howpublished = {Website: http://cs.baylor.edu/~hamerly/software/
  \\europe\_population\_weighted\_centers.html},
  owner        = {Yee Sern Tan},
  url          = {http://cs.baylor.edu/~hamerly/software/europe_population_weighted_centers.html},
}

@Misc{worldbank_other,
  author       = {{World Bank Group}},
  title        = {World Development Indicators},
  howpublished = {Database: http://databank.worldbank.org/data/reports.aspx?
  \\source=world-development-indicators},
  owner        = {Yee Sern Tan},
  url          = {http://databank.worldbank.org/data/reports.aspx?source=world-development-indicators},
}

@Misc{vida,
  author       = {{VIDA}},
  title        = {World Map},
  howpublished = {Online code repository: https://vida.io/gists/TWNbJrHvRcR3DeAZq},
  owner        = {Yee Sern Tan},
  url          = {https://vida.io/gists/TWNbJrHvRcR3DeAZq},
}

@Misc{html,
  author       = {{Scott Stensland}},
  title        = {"Cross origin requests are only supported for HTTP." error when loading a local file},
  howpublished = {Online forum: http://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local},
  owner        = {Yee Sern Tan},
  url          = {http://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local},
}

@Misc{million,
  author       = {Madeline Chambers},
  title        = {More than one million migrants registered in Germany in 2015: newspaper},
  howpublished = {News website: http://www.reuters.com/article/us-europe-migrants-germany-idUSKBN0UD19I20151230},
  month        = dec,
  year         = {2015},
  owner        = {Yee Sern Tan},
  url          = {http://www.reuters.com/article/us-europe-migrants-germany-idUSKBN0UD19I20151230},
}

@Misc{xlrd,
  author       = {R. Prasad},
  title        = {Reading Excel with Python (xlrd)},
  howpublished = {Website: https://blogs.harvard.edu/rprasad/2014/06/16/reading-excel-with-python-xlrd/},
  month        = jun,
  year         = {2014},
  owner        = {Yee Sern Tan},
  url          = {https://blogs.harvard.edu/rprasad/2014/06/16/reading-excel-with-python-xlrd/},
}

@Article{scikit-learn,
  author  = {Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  title   = {Scikit-learn: Machine Learning in {P}ython},
  journal = {Journal of Machine Learning Research},
  year    = {2011},
  volume  = {12},
  pages   = {2825--2830},
  owner   = {Yee Sern Tan},
}

@Article{clauset,
  author  = {Aaron Clauset and Cosma Rohilla Shalizi and Mark E. J. Newman},
  title   = {Power-Law Distributions in Empirical Data},
  journal = {SIAM Rev},
  year    = {2009},
  volume  = {51},
  number  = {4},
  pages   = {661-703},
  doi     = {10.1137/070710111},
  owner   = {Yee Sern Tan},
  url     = {http://epubs.siam.org/doi/abs/10.1137/070710111},
}

@Article{louvain,
  author  = {Vincent D Blondel and Jean-Loup Guillaume and Renaud Lambiotte and Etienne Lefebvre},
  title   = {Fast unfolding of communities in large networks},
  journal = {J. Stat. Mech: Theory Exp.},
  year    = {2008},
  volume  = {2008},
  number  = {10},
  pages   = {P10008 (12pp.)},
  month   = oct,
  owner   = {Yee Sern Tan},
  url     = {http://iopscience.iop.org/article/10.1088/1742-5468/2008/10/P10008/meta},
}

@Article{newman06,
  author  = {Mark E. J. Newman},
  title   = {Modularity and community structure in networks},
  journal = {PNAS},
  year    = {2006},
  volume  = {103},
  number  = {23},
  pages   = {8577-8582},
  doi     = {10.1073/pnas.0601602103},
  owner   = {Yee Sern Tan},
  url     = {http://www.pnas.org/content/103/23/8577.full},
}

@Article{newman05,
  author  = {Mark E. J. Newman},
  title   = {Power laws, Pareto distributions and Zipf's law},
  journal = {Contemp. Phys.},
  year    = {2005},
  volume  = {46},
  number  = {5},
  pages   = {323-351},
  doi     = {10.1080/00107510500052444},
  owner   = {Yee Sern Tan},
  url     = {http://www.tandfonline.com/toc/tcph20/46/5?nav=tocList},
}

@Misc{drc,
  author       = {{Development Research Centre on Migration, Globalisation \& Poverty}},
  title        = {Global Migrant Origin Database},
  howpublished = {Excel file: http://www.migrationdrc.org/research/
  \\typesofmigration/global\_migrant\_origin\_database.html
  \\Version 4},
  month        = mar,
  year         = {2007},
  owner        = {Yee Sern Tan},
  url          = {http://www.migrationdrc.org/research/typesofmigration/global_migrant_origin_database.html},
}

@Misc{mpi,
  author       = {Jie Zong and Jeanne Batalova},
  title        = {Mexican Immigrants in the United States},
  howpublished = {Website: http://www.migrationpolicy.org/article/mexican-immigrants-united-states},
  month        = mar,
  year         = {2016},
  owner        = {Yee Sern Tan},
  url          = {http://www.migrationpolicy.org/article/mexican-immigrants-united-states},
}

@Misc{osw,
  author       = {Marta Jaroszewicz},
  title        = {The migration of Ukrainians in times of crisis},
  howpublished = {Website: https://www.osw.waw.pl/en/publikacje/osw-commentary/2015-10-19/migration-ukrainians-times-crisis},
  month        = oct,
  year         = {2015},
  owner        = {Yee Sern Tan},
  url          = {https://www.osw.waw.pl/en/publikacje/osw-commentary/2015-10-19/migration-ukrainians-times-crisis},
}


text:
package heapprofiler

// Code generated by cdproto-gen. DO NOT EDIT.

// EventAddHeapSnapshotChunk [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-addHeapSnapshotChunk
type EventAddHeapSnapshotChunk struct {
	Chunk string `json:"chunk"`
}

// EventHeapStatsUpdate if heap objects tracking has been started then
// backend may send update for one or more fragments.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-heapStatsUpdate
type EventHeapStatsUpdate struct {
	StatsUpdate []int64 `json:"statsUpdate"` // An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment.
}

// EventLastSeenObjectID if heap objects tracking has been started then
// backend regularly sends a current value for last seen object id and
// corresponding timestamp. If the were changes in the heap since last event
// then one or more heapStatsUpdate events will be sent before a new
// lastSeenObjectId event.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-lastSeenObjectId
type EventLastSeenObjectID struct {
	LastSeenObjectID int64   `json:"lastSeenObjectId"`
	Timestamp        float64 `json:"timestamp"`
}

// EventReportHeapSnapshotProgress [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-reportHeapSnapshotProgress
type EventReportHeapSnapshotProgress struct {
	Done     int64 `json:"done"`
	Total    int64 `json:"total"`
	Finished bool  `json:"finished,omitempty"`
}

// EventResetProfiles [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#event-resetProfiles
type EventResetProfiles struct{}

repository: chromedp/cdproto

repo_name: chromedp/cdproto

extension: go


text:
package bot

import (
	"fmt"
	"gamma-rho-bot/bing"
	"strings"
)

type corrector struct {
	spellCheckerAPIClient bing.SpellCheckAPIClient
	error                 chan error
}

func (c *corrector) checkAndCorrect(message string) (bool, string) {
	message = strings.TrimSpace(message)
	if message == "" {
		return false, ""
	}

	checkingResult, err := c.spellCheckerAPIClient.Check(message)
	if err != nil {
		c.error <- err
		return false, ""
	}

	if len(checkingResult.FlaggedTokens) == 0 {
		return false, ""
	}

	var oldNewStrings []string
	for _, flaggedToken := range checkingResult.FlaggedTokens {
		if len(flaggedToken.Suggestions) == 0 {
			c.error <- fmt.Errorf("there is no suggestions for token \"%s\"", flaggedToken.Token)
			return false, ""
		}

		suggestion := fmt.Sprintf("_%s_", flaggedToken.Suggestions[0].Suggestion)
		oldNewStrings = append(oldNewStrings, flaggedToken.Token)
		oldNewStrings = append(oldNewStrings, suggestion)
	}
	replacer := strings.NewReplacer(oldNewStrings...)

	message = replacer.Replace(message)

	return true, message
}

repository: mchechulnikov/gamma-rho-bot

repo_name: mchechulnikov/gamma-rho-bot


text:
// Copyright (c) 2016 Intel Corporation. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package status

import (
	"os"
	"sync"

	"github.com/edwardsp/go-lustre"
	"github.com/edwardsp/go-lustre/fs"
	"github.com/edwardsp/go-lustre/llapi"
	"github.com/edwardsp/go-lustre/pkg/pool"
)

type mountDir struct {
	path fs.RootDir
	f    *os.File
}

// A cache of file handles per lustre mount point. Currently used to fetch the host Mdt for a file,
// and in future used with openat to open relative paths.
// Could merge with RootDir and ensure RootDir is a singleton per client.
var mountPools map[fs.RootDir]*pool.Pool
var mapLock sync.Mutex

func init() {
	mountPools = make(map[fs.RootDir]*pool.Pool)
}

func (m *mountDir) String() string {
	return m.path.String()
}

func (m *mountDir) Close() error {
	return m.f.Close()
}

func (m *mountDir) GetMdt(in *lustre.Fid) (int, error) {
	mdtIndex, err := llapi.GetMdtIndexByFid(int(m.f.Fd()), in)
	if err != nil {
		return 0, err
	}
	return mdtIndex, nil
}

func openMount(root fs.RootDir) (mnt *mountDir, err error) {
	m := &mountDir{path: root}
	m.f, err = root.Open()
	if err != nil {
		return
	}
	mnt = m
	return
}

func getOpenMount(root fs.RootDir) (mnt *mountDir, err error) {
	mapLock.Lock()
	defer mapLock.Unlock()
	p, ok := mountPools[root]

	if !ok {
		alloc := func() (interface{}, error) {
			return openMount(root)
		}

		p, err = pool.New(root.String(), 1, 10, alloc)
		if err != nil {
			return
		}
		mountPools[root] = p
	}

	o, err := p.Get()
	if err != nil {
		return
	}
	mnt = o.(*mountDir)
	return
}

func putMount(mnt *mountDir) {
	mapLock.Lock()
	defer mapLock.Unlock()
	p := mountPools[mnt.path]
	p.Put(mnt)
}

// GetMdt returns the MDT index for a given Fid
func GetMdt(root fs.RootDir, f *lustre.Fid) (int, error) {
	// mnt, err := getOpenMount(root)
	// if err != nil {
	// 	return 0, err
	// }
	// defer putMount(mnt)
	// return mnt.GetMdt(f)
	fp, err := os.Open(root.Path())
	if err != nil {
		return 0, err
	}
	defer fp.Close()
	return llapi.GetMdtIndexByFid(int(fp.Fd()), f)
}

repository: edwardsp/go-lustre

repo_name: edwardsp/go-lustre


text:
@article{RuprechtEtAl2010,
	author = {D. Ruprecht and R. Klein and A. J. Majda},
	title = {Modulation of Internal Gravity Waves in a Multiscale Model for Deep Convection on Mesoscales},
	journal = {Journal of the Atmospheric Sciences},
	volume = {67},
	number = {8},
	pages = {2504--2519},
  URL={http://dx.doi.org/10.1175/2010JAS3269.1},
	year = {2010}
}

repository: comp-maths/website

repo_name: comp-maths/website


text:
package cowatchbenchmark

import "time"

// ---------------------------------------- for statistics --------------------------------------------

func (p *RoomManager) GetCreatedRooms() int {
	return len(p.Rooms)
}

func (p *RoomManager) GetTotalUsers() int {
	total := 0
	for i := 0; i < len(p.Rooms); i++ {
		total += len(p.Rooms[i].Users)
	}
	return total
}

// GetCreatingRoomAvgDuration return the average time consumption of all rooms which are created successfully
func (p *RoomManager) GetCreatingRoomAvgDuration() time.Duration {
	if len(p.Rooms) == 0 {
		return time.Duration(0)
	}
	var totalDuration time.Duration = 0
	for i := 0; i < len(p.Rooms); i++ {
		totalDuration += p.Rooms[i].ConnectionDuration
	}
	return time.Duration(int64(totalDuration) / int64(len(p.Rooms)))
}

func (p *RoomManager) GetCreatingUsersAvgDuration() time.Duration {
	if len(p.Rooms) == 0 {
		return time.Duration(0)
	}
	var totalDuration time.Duration = 0
	for i := 0; i < len(p.Rooms); i++ {
		totalDuration += p.Rooms[i].usersAvgConnectionDuration()
	}
	return time.Duration(int64(totalDuration) / int64(len(p.Rooms)))
}

// usersAvgConnectionDuration return the average time consumption of all rooms which are created successfully
func (p *RoomUnit) usersAvgConnectionDuration() time.Duration {
	var totalDuration time.Duration = 0
	usersSize := len(p.Users)
	if usersSize == 0 {
		return totalDuration
	}
	for i := 0; i < usersSize; i++ {
		totalDuration += p.Users[i].ConnectionDuration
	}
	return time.Duration(int64(totalDuration) / int64(usersSize))
}

branch_name: refs/heads/main


text:
DESCRIPTION = "ConsoleKit is a framework for defining and tracking users, login sessions, and seats."
LICENSE = "GPLv2"
DEPENDS = "policykit libpam dbus"

PR = "r3"

inherit gnome

SRC_URI = "http://people.freedesktop.org/~mccann/dist/ConsoleKit-${PV}.tar.bz2"
S = "${WORKDIR}/ConsoleKit-${PV}"

EXTRA_OECONF += "--enable-pam-module --with-pam-module-dir=${libdir}/security"

PACKAGES += "pam-plugin-ck-connector"
FILES_${PN} += "${libdir}/ConsoleKit ${datadir}/dbus-1 ${datadir}/PolicyKit"
FILES_${PN}-dbg += ""${libdir}/security/.debug/*.so"
FILES_pam-plugin-ck-connector += "${libdir}/security/*.so"
RDEPENDS_pam-plugin-ck-connector += "${PN}"

SRC_URI[md5sum] = "43b02a52212330b54cfb34c4044d9ce0"
SRC_URI[sha256sum] = "cbcfbb3df2dc76855c99c1cdff04a257ec5270fa62e1d21b0d057b08d88c0fd4"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package main

import (
	"flag"

	_ "github.com/lib/pq"
	"github.com/opencars/govdata"

	"github.com/opencars/wanted/pkg/bom"
	"github.com/opencars/wanted/pkg/config"
	"github.com/opencars/wanted/pkg/logger"
	"github.com/opencars/wanted/pkg/model"
	"github.com/opencars/wanted/pkg/store/postgres"
	"github.com/opencars/wanted/pkg/worker"
)

func main() {
	var path string

	flag.StringVar(&path, "config", "./config/config.yaml", "Path to the configuration file")

	flag.Parse()

	// Get configuration.
	conf, err := config.New(path)
	if err != nil {
		logger.Fatal(err)
	}

	// Register postgres adapter.
	db, err := postgres.New(conf)
	if err != nil {
		logger.Fatal(err)
	}

	resource, err := govdata.ResourceShow(conf.Worker.ResourceID)
	if err != nil {
		logger.Fatal(err)
	}

	w := worker.New()
	if err := w.Load(db); err != nil {
		logger.Fatal(err)
	}

	last, err := db.Revision().Last()
	if err != nil {
		logger.Fatal(err)
	}

	logger.Info("Last revision: %s", last.ID)
	revisions := govdata.Subscribe(conf.Worker.ResourceID, last.CreatedAt)

	// Listen for new revisions.
	for revision := range revisions {
		record := model.RevisionFromGov(&revision)

		logger.WithFields(logger.Fields{
			"revision": record.ID,
		}).Info("Started processing revision")

		body, err := govdata.ResourceRevision(resource.PackageID, conf.Worker.ResourceID, record.ID)
		if err != nil {
			logger.WithFields(logger.Fields{
				"revision": record.ID,
			}).Fatal(err)
		}

		reader, err := bom.NewReader(body)
		if err != nil {
			logger.WithFields(logger.Fields{
				"revision": revision,
				"err":      err,
			}).Error("Broken bom encoding. Skipped")
			continue
		}

		added, removed, err := w.Parse(record.ID, reader)
		if err == worker.ErrEmptyArr {
			logger.WithFields(logger.Fields{
				"revision": revision,
			}).Error("Revision is empty. Skipped")
			continue
		}

		if err != nil {
			logger.WithFields(logger.Fields{
				"revision": revision,
				"err":      err,
			}).Error("Revision is broken. Skipped")
			continue
		}

		if err := body.Close(); err != nil {
			logger.WithFields(logger.Fields{
				"revision": revision,
				"err":      err,
			}).Error("Failed to close body. Skipped")
			continue
		}

		record.Added = len(added)
		record.Removed = len(removed)

		// Save vehicles and revision.
		if err := db.Vehicle().Create(record, added, removed); err != nil {
			logger.WithFields(logger.Fields{
				"revision": revision,
			}).Fatal(err)
		}

		logger.WithFields(logger.Fields{
			"revision": record.ID,
			"added":    len(added),
			"removed":  len(removed),
		}).Info("Finished processing revision")
	}
}

repository: GithubOleksandr/wanted

repo_name: GithubOleksandr/wanted


text:
include zephyr-sample.inc

ZEPHYR_SRC_DIR = "${ZEPHYR_BASE}/samples/subsys/display/lvgl"

# TODO Once more machines and displays are supported, add a PACKAGECONFIG.
EXTRA_OECMAKE:append =" -DSHIELD=adafruit_2_8_tft_touch_v2"

COMPATIBLE_MACHINE = "(nrf52840dk-nrf52840)"

repository: saininav/meta-zephyr

repo_name: saininav/meta-zephyr

gha_language: NASL


text:
@article{yucheTRB21,
 abstract = {Reliable and accurate estimation of electric bus energy consumption is critical for electric bus operation and planning. But energy prediction for electric buses is challenging because of diversified driving cycles of transit services. We propose to establish a data-partition based artificial neural network model to predict energy consumption of electric buses at microscopic level and link level. The purpose of data partitioning is to separate data into charging and discharging modes and then develop most efficient prediction for each mode. We utilize a long-term transit operation and energy consumption monitoring dataset from Chattanooga, SC to train and test our neural network models. The microscopic model  estimates energy consumption of electric bus at 1Hz frequency based on instantaneous driving and road environment data. The prediction errors of micro model ranges between 8% and 15% on various instantaneous power demand, vehicle specific power, bins. The link-level model is to predict average energy consumption rate based on aggregated traffic pattern parameters derived from instantaneous driving data at second level. The prediction errors of link-level model are around 15% on various average speed, temperature and road grade conditions. The validation results demonstrate our models’ capability to capture impacts of driving, meteorology and road grade on electric bus energy consumption at different temporal and spatial resolution.},
 author = {Yunteng Zhang and Yuche Chen and Ruixiao Sun and Abhishek Dubey and Philip Pugliese},
 journal = {Transportation Research Board 100th Annual Meeting},
 title = {A Data Partitioning-based Artificial Neural Network Model to Estimate Real-driving Energy Consumption of Electric Buses},
 year = {2021}
}


text:
EXTRA_OECONF = " \
  --enable-threads \
  --enable-ethernet \
  --enable-wifi \
  --enable-bluetooth \
  --enable-modemmgr \
  --enable-udhcp \
  --enable-dhclient \
  --enable-resolvconf \
  --enable-loopback \
  --enable-dnsproxy \
  --enable-novatel \
  --enable-huawei \
  --enable-hso \
  --enable-mbm \
  --enable-ppp \
  --disable-polkit \
  --enable-client \
  --enable-tools \
  --enable-fake \
"

EXTRA_OECONF_append_shr += "--disable-tools"

require connman.inc

SRCREV = "1a94db417ecaba20a609ff4b4431a3f67c5dcbc6"

PV = "0.42+git"
PR = "r2"
PR_append = ".gitr${SRCREV}"

DEFAULT_PREFERENCE = "-1"

SRC_URI = "\
  git://git.kernel.org/pub/scm/network/connman/connman.git;protocol=git \
  file://connman \
"

S = "${WORKDIR}/git"


text:
package store

import "github.com/dgraph-io/badger/v3"

var _ KVStore = &BadgerKV{}

type BadgerKV struct {
	db *badger.DB
}

func (b *BadgerKV) Get(key []byte) ([]byte, error) {
	txn := b.db.NewTransaction(false)
	defer txn.Discard()
	item, err := txn.Get(key)
	if err != nil {
		return nil, err
	}
	return item.ValueCopy(nil)
}

func (b *BadgerKV) Set(key []byte, value []byte) error {
	txn := b.db.NewTransaction(true)
	err := txn.Set(key, value)
	if err != nil {
		txn.Discard()
		return err
	}
	return txn.Commit()
}

func (b *BadgerKV) Delete(key []byte) error {
	txn := b.db.NewTransaction(true)
	err := txn.Delete(key)
	if err != nil {
		txn.Discard()
		return err
	}
	return txn.Commit()
}

repository: evan-forbes/optimint

repo_name: evan-forbes/optimint


text:
package admin

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"kangg/models/admin"
)

type BannerController struct {
	BaseController
}

func (c *BannerController) List() {

	o := orm.NewOrm()
	banner := new(admin.Banner)

	var banners []*admin.Banner
	qs := o.QueryTable(banner)
	qs = qs.Filter("Article__Title__isnull", false)

	// 获取数据
	_, err := qs.OrderBy("id").RelatedSel().All(&banners)

	if err != nil {
		c.Abort("404")
	}

	c.Data["Banner"] = &banners

	c.TplName = "admin/banner.html"
}

func (c *BannerController) Update() {
	id, _ := c.GetInt("id", 0)
	name := c.GetString("name")
	image := c.GetString("image")
	aid,_ := c.GetInt("aid")

	response := make(map[string]interface{})

	o := orm.NewOrm()

	banner := admin.Banner{Id: id}
	if o.Read(&banner) == nil {
		banner.Name = name
		banner.Image = image

		valid := validation.Validation{}
		valid.Required(banner.Image, "Image")
		valid.Required(banner.Article, "Article")

		if valid.HasErrors() {
			// 如果有错误信息，证明验证没通过
			// 打印错误信息
			for _, err := range valid.Errors {
				//log.Println(err.Key, err.Message)
				response["msg"] = "新增失败！"
				response["code"] = 500
				response["err"] = err.Key + " " + err.Message
				c.Data["json"] = response
				c.ServeJSON()
				c.StopRun()
			}
		}

		banner.Article = &admin.Article{Id:aid,Title: ""}

		if _, err := o.Update(&banner); err == nil {
			response["msg"] = "修改成功！"
			response["code"] = 200
			response["id"] = id
		} else {
			response["msg"] = "修改失败！"
			response["code"] = 500
			response["err"] = err.Error()
		}
	} else {
		response["msg"] = "修改失败！"
		response["code"] = 500
		response["err"] = "ID 不能为空！"
	}

	c.Data["json"] = response
	c.ServeJSON()
	c.StopRun()
}

func (c *BannerController) Put() {
	id, err := c.GetInt("id", 0)

	if id == 0 {
		c.Abort("404")
	}

	// 基础数据
	o := orm.NewOrm()
	banner := new(admin.Banner)
	var banners []*admin.Banner
	qs := o.QueryTable(banner)
	err = qs.Filter("id", id).One(&banners)
	if err != nil {
		c.Abort("404")
	}
	c.Data["Data"] = banners[0]

	// 文章数据
	o = orm.NewOrm()
	article := new(admin.Article)
	var articles []*admin.Article
	qs = o.QueryTable(article)
	qs = qs.Filter("status", 1)
	qs.All(&articles)

	c.Data["Article"] = articles

	c.TplName = "admin/banner-edit.html"

}

repository: egocan/kangg

repo_name: egocan/kangg


text:
package gofeed_test

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/mmcdole/gofeed"
	"github.com/stretchr/testify/assert"
)

func TestDetectFeedType(t *testing.T) {
	var feedTypeTests = []struct {
		file     string
		expected gofeed.FeedType
	}{
		{"atom03_feed.xml", gofeed.FeedTypeAtom},
		{"atom10_feed.xml", gofeed.FeedTypeAtom},
		{"rss_feed.xml", gofeed.FeedTypeRSS},
		{"rdf_feed.xml", gofeed.FeedTypeRSS},
		{"unknown_feed.xml", gofeed.FeedTypeUnknown},
		{"empty_feed.xml", gofeed.FeedTypeUnknown},
	}

	for _, test := range feedTypeTests {
		fmt.Printf("Testing %s... ", test.file)

		// Get feed content
		path := fmt.Sprintf("testdata/parser/feed/%s", test.file)
		f, _ := ioutil.ReadFile(path)

		// Get actual value
		actual := gofeed.DetectFeedType(bytes.NewReader(f))

		if assert.Equal(t, actual, test.expected, "Feed file %s did not match expected type %d", test.file, test.expected) {
			fmt.Printf("OK\n")
		} else {
			fmt.Printf("Failed\n")
		}
	}
}

func TestParser_Parse(t *testing.T) {
	var feedTests = []struct {
		file      string
		feedType  string
		feedTitle string
		hasError  bool
	}{
		{"atom03_feed.xml", "atom", "Atom Title", false},
		{"atom10_feed.xml", "atom", "Atom Title", false},
		{"rss_feed.xml", "rss", "RSS Title", false},
		{"rdf_feed.xml", "rss", "RDF Title", false},
		{"unknown_feed.xml", "", "", true},
		{"empty_feed.xml", "", "", true},
	}

	for _, test := range feedTests {
		fmt.Printf("Testing %s... ", test.file)

		// Get feed content
		path := fmt.Sprintf("testdata/parser/feed/%s", test.file)
		f, _ := ioutil.ReadFile(path)

		// Get actual value
		fp := gofeed.NewParser()
		feed, err := fp.Parse(bytes.NewReader(f))

		if test.hasError {
			assert.NotNil(t, err)
			assert.Nil(t, feed)
		} else {
			assert.NotNil(t, feed)
			assert.Nil(t, err)
			assert.Equal(t, feed.FeedType, test.feedType)
			assert.Equal(t, feed.Title, test.feedTitle)
		}
	}
}

func TestParser_ParseString(t *testing.T) {
	var feedTests = []struct {
		file      string
		feedType  string
		feedTitle string
		hasError  bool
	}{
		{"atom03_feed.xml", "atom", "Atom Title", false},
		{"atom10_feed.xml", "atom", "Atom Title", false},
		{"rss_feed.xml", "rss", "RSS Title", false},
		{"rdf_feed.xml", "rss", "RDF Title", false},
		{"unknown_feed.xml", "", "", true},
		{"empty_feed.xml", "", "", true},
	}

	for _, test := range feedTests {
		fmt.Printf("Testing %s... ", test.file)

		// Get feed content
		path := fmt.Sprintf("testdata/parser/feed/%s", test.file)
		f, _ := ioutil.ReadFile(path)

		// Get actual value
		fp := gofeed.NewParser()
		feed, err := fp.ParseString(string(f))

		if test.hasError {
			assert.NotNil(t, err)
			assert.Nil(t, feed)
		} else {
			assert.NotNil(t, feed)
			assert.Nil(t, err)
			assert.Equal(t, feed.FeedType, test.feedType)
			assert.Equal(t, feed.Title, test.feedTitle)
		}
	}
}

func TestParser_ParseURL_Success(t *testing.T) {
	var feedTests = []struct {
		file      string
		feedType  string
		feedTitle string
		hasError  bool
	}{
		{"atom03_feed.xml", "atom", "Atom Title", false},
		{"atom10_feed.xml", "atom", "Atom Title", false},
		{"rss_feed.xml", "rss", "RSS Title", false},
		{"rdf_feed.xml", "rss", "RDF Title", false},
		{"unknown_feed.xml", "", "", true},
	}

	for _, test := range feedTests {
		fmt.Printf("Testing %s... ", test.file)

		// Get feed content
		path := fmt.Sprintf("testdata/parser/feed/%s", test.file)
		f, _ := ioutil.ReadFile(path)

		// Get actual value
		server, client := mockServerResponse(200, string(f))
		fp := gofeed.NewParser()
		fp.Client = client
		feed, err := fp.ParseURL(server.URL)

		if test.hasError {
			assert.NotNil(t, err)
			assert.Nil(t, feed)
		} else {
			assert.NotNil(t, feed)
			assert.Nil(t, err)
			assert.Equal(t, feed.FeedType, test.feedType)
			assert.Equal(t, feed.Title, test.feedTitle)
		}
	}
}

func TestParser_ParseURL_Failure(t *testing.T) {
	server, client := mockServerResponse(404, "")
	fp := gofeed.NewParser()
	fp.Client = client
	feed, err := fp.ParseURL(server.URL)

	assert.NotNil(t, err)
	assert.Nil(t, feed)
}

// Test Helpers

func mockServerResponse(code int, body string) (*httptest.Server, *http.Client) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(code)
		w.Header().Set("Content-Type", "application/xml")
		io.WriteString(w, body)
	}))

	transport := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			return url.Parse(server.URL)
		},
	}

	client := &http.Client{Transport: transport}
	return server, client
}

// Examples

func ExampleDetectFeedType() {
	feedData := `<rss version="2.0">
<channel>
<title>Sample Feed</title>
</channel>
</rss>`
	feedType := gofeed.DetectFeedType(strings.NewReader(feedData))
	if feedType == gofeed.FeedTypeRSS {
		fmt.Println("Wow! This is an RSS feed!")
	}
}

func ExampleParser_Parse() {
	feedData := `<rss version="2.0">
<channel>
<title>Sample Feed</title>
</channel>
</rss>`
	fp := gofeed.NewParser()
	feed, err := fp.Parse(strings.NewReader(feedData))
	if err != nil {
		panic(err)
	}
	fmt.Println(feed.Title)
}

func ExampleParser_ParseURL() {
	fp := gofeed.NewParser()
	feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml")
	if err != nil {
		panic(err)
	}
	fmt.Println(feed.Title)
}

func ExampleParser_ParseString() {
	feedData := `<rss version="2.0">
<channel>
<title>Sample Feed</title>
</channel>
</rss>`
	fp := gofeed.NewParser()
	feed, err := fp.ParseString(feedData)
	if err != nil {
		panic(err)
	}
	fmt.Println(feed.Title)
}

repository: bestwpw/gofeed

repo_name: bestwpw/gofeed


text:
@article{kalbitzer_social_2015,
 author = {Kalbitzer, Urs and Heistermann, Michael and Cheney, Dorothy and Seyfarth, Robert and Fischer, Julia},
 doi = {10.1016/j.yhbeh.2015.08.013},
 file = {Kalbitzer et al. - 2015 - Social behavior and patterns of testosterone and g.pdf:/Users/Urs/Zotero/storage/7FB9PQ6Z/Kalbitzer et al. - 2015 - Social behavior and patterns of testosterone and g.pdf:application/pdf;mmc1.docx:/Users/Urs/Zotero/storage/IJR8UEGH/mmc1.docx:application/vnd.openxmlformats-officedocument.wordprocessingml.document;mmc2.docx:/Users/Urs/Zotero/storage/EPMR8HXP/mmc2.docx:application/vnd.openxmlformats-officedocument.wordprocessingml.document;mmc3.docx:/Users/Urs/Zotero/storage/WUFS78P9/mmc3.docx:application/vnd.openxmlformats-officedocument.wordprocessingml.document;mmc4.docx:/Users/Urs/Zotero/storage/7U8JN5RJ/mmc4.docx:application/vnd.openxmlformats-officedocument.wordprocessingml.document},
 issn = {0018506X},
 journal = {Hormones and Behavior},
 language = {en},
 month = {September},
 pages = {100--110},
 title = {Social behavior and patterns of testosterone and glucocorticoid levels differ between male chacma and Guinea baboons},
 url = {http://linkinghub.elsevier.com/retrieve/pii/S0018506X15300453},
 urldate = {2015-10-01},
 volume = {75},
 year = {2015}
}

gha_language: TeX


text:
@article{Clunie_2004,
  doi = {10.1093/rheumatology/keg442},
  url = {https://doi.org/10.1093\%2Frheumatology\%2Fkeg442},
  year = 2004,
  month = {jan},
  publisher = {Oxford University Press ({OUP})},
  volume = {43},
  number = {1},
  pages = {13--18},
  author = {G. P. R. Clunie},
  title = {Relevance of thiopurine methyltransferase status in rheumatology patients receiving azathioprine},
  journal = {Rheumatology}
}

repository: larmcr/px

repo_name: larmcr/px


text:
@phdthesis{Asano2015,
  author       = {Asano, Yuta},
  school       = {R.I.T.},
  title        = {{Individual Colorimetric Observers for Personalized
    Color Imaging}},
  year         = 2015,
}
@article{Breneman1987b,
  abstract     = {While each of his or her two eyes was independently
    adapted to a different illuminant in viewing a complex visual
    field, each of a number of observers matched a series of test
    colors seen by one eye with a juxtaposed variable stimulus seen by
    the other eye. The 2 degrees test and matching stimuli were
    located centrally in the complex adapting field, which subtended
    an angle of 31 degrees X 24 degrees. In making the matches, the
    observer viewed the test and matching stimuli for a series of
    brief intervals (approximately 1 sec) while viewing the complex
    adapting field with normal eye movements. Nine experiments were
    performed with different pairs of illuminants and different
    illuminances ranging from that of an average living room to that
    of a scene illuminated with hazy sunlight. In three other
    experiments each of the observer's two eyes was adapted to a
    different illuminance of D55. The amount of adaptation was more
    nearly complete at high levels of illuminance than at low levels,
    and the proportional amount of adaptation was less for the "blue"
    receptors. When adaptation coefficients were determined from the
    actual adaptation differences (e.g., from corresponding
    tristimulus values for matching neutrals) rather than from the
    adapting illuminants, a linear von Kries transformation based on
    experimentally determined visual primaries gave corresponding
    chromaticities that were in good agreement with the results
    obtained in each of the chromatic-adaptation experiments, except
    at the lowest illuminances. The results of the experiments in
    which each eye was adapted to different levels of the same
    illuminant indicated again that adaptation to the different levels
    was incomplete, the proportional amount of adaptation being less
    at low illuminances and for the "blue" receptors. This caused a
    change in chromatic adaptation with the level of illuminance even
    when the chromaticities of the adapting lights were equal. The
    results of these experiments also indicated that higher purities
    are needed in order to produce the same absolute color appearances
    at low levels of illuminance.},
  author       = {Breneman, Edwin J.},
  doi          = {10.1364/JOSAA.4.001115},
  issn         = {1084-7529},
  journal      = {Journal of the Optical Society of America A},
  month        = jun,
  number       = 6,
  pages        = 1115,
  pmid         = 3598755,
  title        = {{Corresponding chromaticities for different states
    of adaptation to complex visual fields}},
  url          = {https://www.osapublishing.org/abstract.cfm?URI=josaa-4-6-1115
    http://www.opticsinfobase.org/josaa/fulltext.cfm?uri=josaa-4-6-1115\&id=2783},
  volume       = 4,
  year         = 1987,
}
@misc{Dyer2017,
  author       = {Dyer, Scott and Forsythe, Alexander and Irons,
    Jonathon and Mansencal, Thomas and Zhu, Miaoqi},
  title        = {{RAW to ACES Utility Data}},
  year         = 2017,
}
@inproceedings{Ebner1998,
  author       = {Ebner, Fritz and Fairchild, Mark D.},
  booktitle    = {Proc. SPIE 3300, Color Imaging: Device-Independent
    Color, Color Hardcopy, and Graphic Arts III, (2 January 1998)},
  doi          = {10.1117/12.298269},
  editor       = {Beretta, Giordano B. and Eschbach, Reiner},
  month        = jan,
  pages        = {107--117},
  title        = {{Finding constant hue surfaces in color space}},
  url          = {http://proceedings.spiedigitallibrary.org/proceeding.aspx?articleid=936964},
  year         = 1998,
}
@misc{Haanpaloa,
  author       = {Haanpalo, Jouni and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269922},
  title        = {{Paper Spectra}},
  url          = {http://www.uef.fi/web/spectral/paper-spectra},
}
@misc{Haanpalo,
  author       = {Haanpalo, Jouni and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269916},
  title        = {{Munsell Colors Glossy (Spectrofotometer Measured)}},
  url          = {http://www.uef.fi/web/spectral/munsell-colors-glossy-spectrofotometer-measured},
}
@misc{Hauta-Kasaria,
  author       = {Hauta-Kasari, Markku and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269914},
  title        = {{Munsell Colors Matt (AOTF Measured)}},
  url          = {http://www.uef.fi/web/spectral/munsell-colors-matt-aotf-measured-},
}
@misc{Hauta-Kasari,
  author       = {Hauta-Kasari, Markku and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269912},
  title        = {{Munsell Colors Matt (Spectrofotometer Measured)}},
  url          = {http://www.uef.fi/web/spectral/munsell-colors-matt-spectrofotometer-measured},
}
@misc{Hiltunen,
  author       = {Hiltunen, Jouni and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269924},
  title        = {{Lumber Spectra}},
  url          = {http://www.uef.fi/web/spectral/lumber-spectra},
}
@article{Hung1995,
  author       = {Hung, Po-Chieh and Berns, Roy S.},
  doi          = {10.1002/col.5080200506},
  issn         = 03612317,
  journal      = {Color Research \& Application},
  keywords     = {color appearance spaces,experiments to evaluate
    color space hue linearity,perceived hue},
  month        = oct,
  number       = 5,
  pages        = {285--295},
  title        = {{Determination of constant Hue Loci for a CRT gamut
    and their predictions using color appearance spaces}},
  url          = {http://doi.wiley.com/10.1002/col.5080200506},
  volume       = 20,
  year         = 1995,
}
@inproceedings{Jiang2013,
  abstract     = {Camera spectral sensitivity functions relate scene
    radiance with captured RGB triplets. They are important for many
    computer vision tasks that use color information, such as
    multispectral imaging, color rendering, and color constancy. In
    this paper, we aim to explore the space of spectral sensitivity
    functions for digital color cameras. After collecting a database
    of 28 cameras covering a variety of types, we find this space
    convex and two-dimensional. Based on this statistical model, we
    propose two methods to recover camera spectral sensitivities using
    regular reflective color targets (e.g., color checker) from a
    single image with and without knowing the illumination. We show
    the proposed model is more accurate and robust for estimating
    camera spectral sensitivities than other basis functions. We also
    show two applications for the recovery of camera spectral
    sensitivities - simulation of color rendering for cameras and
    computational color constancy.},
  author       = {Jiang, Jun and Liu, Dengyu and Gu, Jinwei and
    Susstrunk, Sabine},
  booktitle    = {2013 IEEE Workshop on Applications of Computer
    Vision (WACV)},
  doi          = {10.1109/WACV.2013.6475015},
  isbn         = {978-1-4673-5054-9},
  issn         = 21583978,
  month        = jan,
  pages        = {168--179},
  publisher    = {IEEE},
  title        = {{What is the space of spectral sensitivity functions
    for digital color cameras?}},
  url          = {http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=6475015},
  year         = 2013,
}
@misc{Labsphere2019,
  author       = {Labsphere},
  doi          = {10.5281/zenodo.3245875},
  title        = {{Labsphere SRS-99-020}},
  year         = 2019,
}
@article{Luo1999,
  abstract     = {Predicting the binding mode of flexible polypeptides
    to proteins is an important task that falls outside the domain of
    applicability of most small molecule and protein−protein docking
    tools. Here, we test the small molecule flexible ligand docking
    program Glide on a set of 19 non-$\alpha$-helical peptides and
    systematically improve pose prediction accuracy by enhancing Glide
    sampling for flexible polypeptides. In addition, scoring of the
    poses was improved by post-processing with physics-based implicit
    solvent MM- GBSA calculations. Using the best RMSD among the top
    10 scoring poses as a metric, the success rate (RMSD ≤ 2.0 {\AA}
    for the interface backbone atoms) increased from 21% with default
    Glide SP settings to 58% with the enhanced peptide sampling and
    scoring protocol in the case of redocking to the native protein
    structure. This approaches the accuracy of the recently developed
    Rosetta FlexPepDock method (63% success for these 19 peptides)
    while being over 100 times faster. Cross-docking was performed for
    a subset of cases where an unbound receptor structure was
    available, and in that case, 40% of peptides were docked
    successfully. We analyze the results and find that the optimized
    polypeptide protocol is most accurate for extended peptides of
    limited size and number of formal charges, defining a domain of
    applicability for this approach.},
  author       = {Luo, M. Ronnier and Rhodes, Peter A.},
  doi          = {10.1002/(SICI)1520-6378(199908)24:4<295::AID-COL10>3.0.CO;2-K},
  issn         = {0361-2317},
  journal      = {Color Research \& Application},
  month        = aug,
  number       = 4,
  pages        = {295--296},
  title        = {{Corresponding-colour datasets}},
  url          = {http://doi.wiley.com/10.1002/%28SICI%291520-6378%28199908%2924%3A4%3C295%3A%3AAID-COL10%3E3.0.CO%3B2-K},
  volume       = 24,
  year         = 1999,
}
@misc{Marszalec,
  author       = {Marszalec, Elzbieta and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269926},
  title        = {{Agfa IT8.7/2 Set}},
  url          = {http://www.uef.fi/web/spectral/agfa-it8.7/2-set},
}
@misc{OpenpyxlDevelopers2019,
  author       = {{Openpyxl Developers}},
  title        = {openpyxl},
  url          = {https://bitbucket.org/openpyxl/openpyxl/},
  year         = 2019,
}
@misc{Orava,
  author       = {Orava, Joni and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269918},
  title        = {{Munsell Colors Glossy (All) (Spectrofotometer
    Measured)}},
  url          = {http://www.uef.fi/web/spectral/munsell-colors-glossy-all-spectrofotometer-measured},
}
@misc{Silvennoinen,
  author       = {Silvennoinen, Raimo and {University of Kuopio}},
  doi          = {10.5281/zenodo.3269920},
  title        = {{Forest Colors}},
  url          = {http://www.uef.fi/web/spectral/forest-colors},
}
@misc{X-Rite2016,
  author       = {X-Rite},
  title        = {{New Color Specifications for ColorChecker SG and
    Classic Charts}},
  url          = {https://xritephoto.com/ph_product_overview.aspx?ID=938\&Action=Support\&SupportID=5884},
  urldate      = {2019-06-14},
  year         = 2016,
}


text:
// Copyright Project Harbor 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 model

import (
	"encoding/json"
	"time"

	"github.com/beego/beego/v2/client/orm"

	"github.com/goharbor/harbor/src/lib/errors"
)

func init() {
	orm.RegisterModel(&Robot{})
}

// Robot holds the details of a robot.
type Robot struct {
	ID           int64     `orm:"pk;auto;column(id)" json:"id"`
	Name         string    `orm:"column(name)" json:"name" sort:"default"`
	Description  string    `orm:"column(description)" json:"description"`
	Secret       string    `orm:"column(secret)" json:"secret"`
	Salt         string    `orm:"column(salt)" json:"-"`
	Duration     int64     `orm:"column(duration)" json:"duration"`
	ProjectID    int64     `orm:"column(project_id)" json:"project_id"`
	ExpiresAt    int64     `orm:"column(expiresat)" json:"expires_at"`
	Disabled     bool      `orm:"column(disabled)" json:"disabled"`
	Visible      bool      `orm:"column(visible)" json:"-"`
	CreationTime time.Time `orm:"column(creation_time);auto_now_add" json:"creation_time"`
	UpdateTime   time.Time `orm:"column(update_time);auto_now" json:"update_time"`
}

// TableName ...
func (r *Robot) TableName() string {
	return "robot"
}

// FromJSON parses robot from json data
func (r *Robot) FromJSON(jsonData string) error {
	if len(jsonData) == 0 {
		return errors.New("empty json data to parse")
	}

	return json.Unmarshal([]byte(jsonData), r)
}

// ToJSON marshals Robot to JSON data
func (r *Robot) ToJSON() (string, error) {
	data, err := json.Marshal(r)
	if err != nil {
		return "", err
	}

	return string(data), nil
}

repository: goharbor/harbor

repo_name: goharbor/harbor

gha_language: Go


text:
package cmd

/*
Copyright © 2020 Giuseppe Lavagetto

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.
*/

import (
	"fmt"
	"os"

	"image/gif"

	"github.com/lavagetto/memeoid/img"
	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string
var gifPath string
var topText string
var bottomText string
var outFile string
var fontName string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "memeoid",
	Short: "A non-cloud-native meme generator",
	Long: `Memeoid is a simple CLI or HTTP meme generator.
  	 Currently only CLI works, and it's extremely crude!`,
	Run: func(cmd *cobra.Command, args []string) {
		meme, err := img.MemeFromFile(
			gifPath,
			topText,
			bottomText,
			fontName,
		)
		if err != nil {
			panic(err)
		}
		// Uncomment for debugging
		/*
			meme.GifMetaData()
			return
		*/
		err = meme.Generate()
		if err != nil {
			panic(err)
		}
		out, err := os.Create(outFile)
		if err != nil {
			panic(err)
		}
		err = gif.EncodeAll(out, meme.Gif)
		if err != nil {
			panic(err)
		}
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.memeoid.yaml)")
	rootCmd.Flags().StringVar(&gifPath, "gif", "homer.gif", "The gif to use as a base for your meme")
	rootCmd.Flags().StringVarP(&topText, "top", "t", "", "The text to add at the top")
	rootCmd.Flags().StringVarP(&bottomText, "bottom", "b", "", "The text to insert at the bottom")
	rootCmd.Flags().StringVarP(&outFile, "out", "o", "meme.gif", "File to output to.")
	rootCmd.PersistentFlags().StringVarP(&fontName, "font", "f", "DejaVuSans", "Name of the ttf font on your system you want to use (default: impact).")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".memeoid" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".memeoid")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}

repository: lavagetto/memeoid

repo_name: lavagetto/memeoid


text:
@article{da2018evolutionary,
 author = {da Silva, Alexandre Sawczuk and Mei, Yi and Ma, Hui and Zhang, Mengjie},
 doi = {10.1007/s10732-017-9330-4},
 journal = {Journal of Heuristics},
 month = {jun},
 number = {3},
 pages = {425--456},
 pdf = {papers/HEUR17-Alex.pdf},
 publisher = {Springer},
 title = {Evolutionary computation for automatic Web service composition: an indirect representation approach},
 volume = {24},
 year = {2018}
}


text:
SUMMARY = "Kernel dump file access library"
DESCRIPTION = "A library that provides an abstraction layer for reading kernel dump \
core files.  It supports different kernel dump core formats, virtual \
to physical translation, Xen mappings and more."

HOMEPAGE = "https://github.com/ptesarik/libkdumpfile"

LICENSE = "GPLv2 & GPLv3 & LGPLv3"
LIC_FILES_CHKSUM = "file://COPYING;md5=4ca7e035a55f25a55e4a1fde7c9d621c \
                    file://COPYING.GPLv2;md5=751419260aa954499f7abaabaa882bbe \
                    file://COPYING.GPLv3;md5=d32239bcb673463ab874e80d47fae504 \
                    file://COPYING.LGPLv3;md5=e6a600fd5e1d9cbde2d983680233ad02"

SRCBRANCH ?= "tip"
SRCREV = "fedbe7f66561754782165be2512bca0ed1b775e9"

PV = "v0.4.0+git${SRCPV}"

SRC_URI = "git://github.com/ptesarik/libkdumpfile;branch=${SRCBRANCH} \
           file://0001-added-way-to-read-NUMBER-values-from-vmcoreinfo.patch \
           file://0002-addrxlat-aarch64-add-linux-vmcore-support-for-kernel.patch \
          "

S = "${WORKDIR}/git"

DEPENDS = "zlib python3"

inherit autotools pkgconfig python3native python3-dir

PACKAGECONFIG ??= ""
PACKAGECONFIG[lzo] = "--with-lzo,--without-lzo,lzo"
PACKAGECONFIG[snappy] = "--with-snappy,--without-snappy,snappy"

# remove examples binaries
do_install_append () {
        rm -rf "${D}${bindir}"
}

PACKAGES += "python3-libkdumpfile"
FILES_python3-libkdumpfile += "${PYTHON_SITEPACKAGES_DIR}"

COMPATIBLE_HOST = '(x86_64.*|aarch64.*)'

BBCLASSEXTEND = "native"

repository: AlexanderKamensky/meta-kcrash

repo_name: AlexanderKamensky/meta-kcrash