text:
package cas

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"testing"

	uuid "github.com/nu7hatch/gouuid"
	"golang.org/x/net/context"
	"google.golang.org/genproto/googleapis/bytestream"
	remoteexecution "google.golang.org/genproto/googleapis/devtools/remoteexecution/v1test"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/twitter/scoot/bazel"
	"github.com/twitter/scoot/snapshot/store"
)

var testHash1 string = "ce58a4479be1d32816ee82e57eae04415dc2bda173fa7b0f11d18aa67856f242"
var testSize1 int64 = 7
var testData1 []byte = []byte("abc1234")

func TestFindMissingBlobsStub(t *testing.T) {
	f := &store.FakeStore{}
	s := casServer{storeConfig: &store.StoreConfig{Store: f}}

	// Create 2 digests, write 1 to Store, check both for missing, expect other 1 back
	dExists := &remoteexecution.Digest{Hash: "abc123", SizeBytes: 1}
	dMissing := &remoteexecution.Digest{Hash: "efg456", SizeBytes: 9}
	digests := []*remoteexecution.Digest{dExists, dMissing}
	expected := []*remoteexecution.Digest{dMissing}

	resourceName := bazel.DigestStoreName(dExists)
	err := f.Write(resourceName, bytes.NewReader([]byte("")), nil)
	if err != nil {
		t.Fatalf("Failed to write into FakeStore: %v", err)
	}

	ctx := context.Background()
	req := &remoteexecution.FindMissingBlobsRequest{BlobDigests: digests}

	res, err := s.FindMissingBlobs(ctx, req)
	if err != nil {
		t.Fatalf("Error response from FindMissingBlobs: %v", err)
	}

	if len(expected) != len(res.MissingBlobDigests) {
		t.Fatalf("Length of missing blobs mismatch, expected %d got %d", len(expected), len(res.MissingBlobDigests))
	}
	for i, d := range res.MissingBlobDigests {
		if expected[i] != d {
			t.Fatalf("Non-match iterating through missing digests, expected %s got: %s", expected[i], d)
		}
	}
}

func TestRead(t *testing.T) {
	f := &store.FakeStore{}
	s := casServer{storeConfig: &store.StoreConfig{Store: f}}

	// Write a resource to underlying store
	d := &remoteexecution.Digest{Hash: testHash1, SizeBytes: testSize1}
	resourceName := bazel.DigestStoreName(d)
	err := f.Write(resourceName, bytes.NewReader(testData1), nil)
	if err != nil {
		t.Fatalf("Failed to write into FakeStore: %v", err)
	}

	// Make a ReadRequest that exercises read limits and offsets
	offset, limit := int64(2), int64(2)
	req := &bytestream.ReadRequest{ResourceName: fmt.Sprintf("blobs/%s/-1", testHash1), ReadOffset: offset, ReadLimit: limit}
	r := makeFakeReadServer()

	// Make actual Read request
	err = s.Read(req, r)
	if err != nil {
		t.Fatalf("Error response from Read: %v", err)
	}

	// Get data sent/captured by fake server, and compare with expected based on testdata, limit, and offset
	b, err := ioutil.ReadAll(r.buffer)
	if err != nil {
		t.Fatalf("Error reading from fake server data: %v", err)
	}
	if bytes.Compare(b, testData1[offset:]) != 0 {
		t.Fatalf("Data read from fake server did not match - expected: %s, got: %s", testData1[offset:], b)
	}
	sends := int((testSize1-offset)/limit + (testSize1-offset)%limit)
	if r.sendCount != sends {
		t.Fatalf("Fake server Send() count mismatch - expected %d times based on - data len: %d ReadOffset: %d ReadLimit %d. got: %d", sends, testSize1, offset, limit, r.sendCount)
	}
	r.reset()
}

func TestWrite(t *testing.T) {
	f := &store.FakeStore{}
	s := casServer{storeConfig: &store.StoreConfig{Store: f}}

	w := makeFakeWriteServer(testHash1, testSize1, testData1, 3)

	// Make Write request with test data
	err := s.Write(w)
	if err != nil {
		t.Fatalf("Error response from Write: %v", err)
	}

	// Verify that fake write server was invoked as expected
	if w.committedSize != testSize1 {
		t.Fatalf("Size committed to fake server did not match - expected: %d, got: %d", testSize1, w.committedSize)
	}
	if w.recvCount != w.recvChunks {
		t.Fatalf("Number of write chunks to fake server did not match - expected: %d, got: %d", w.recvChunks, w.recvCount)
	}

	// Verify Write by reading directly from underlying Store
	d := &remoteexecution.Digest{Hash: testHash1, SizeBytes: testSize1}
	resourceName := bazel.DigestStoreName(d)
	r, err := f.OpenForRead(resourceName)
	if err != nil {
		t.Fatalf("Failed to open expected resource for reading: %s: %v", resourceName, err)
	}
	b, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatalf("Error reading from fake store: %v", err)
	}
	if bytes.Compare(b, testData1) != 0 {
		t.Fatalf("Data read from store did not match - expected: %s, got: %s", testData1, b)
	}
}

func TestWriteExisting(t *testing.T) {
	f := &store.FakeStore{}
	s := casServer{storeConfig: &store.StoreConfig{Store: f}}

	// Pre-write data directly to underlying Store
	d := &remoteexecution.Digest{Hash: testHash1, SizeBytes: testSize1}

	resourceName := bazel.DigestStoreName(d)
	err := f.Write(resourceName, bytes.NewReader(testData1), nil)
	if err != nil {
		t.Fatalf("Failed to write into FakeStore: %v", err)
	}

	w := makeFakeWriteServer(testHash1, testSize1, testData1, 3)

	// Make Write request with test data matching pre-written data
	err = s.Write(w)
	if err != nil {
		t.Fatalf("Error response from Write: %v", err)
	}

	// Verify that fake write server was invoked as expected - recv was called only once
	if w.committedSize != testSize1 {
		t.Fatalf("Size committed to fake server did not match - expected: %d, got: %d", testSize1, w.committedSize)
	}
	if w.recvCount != 1 {
		t.Fatalf("Number of write chunks to fake server did not match - expected: %d, got: %d", 1, w.recvCount)
	}
}

func TestQueryWriteStatusStub(t *testing.T) {
	f := &store.FakeStore{}
	s := casServer{storeConfig: &store.StoreConfig{Store: f}}

	ctx := context.Background()
	req := &bytestream.QueryWriteStatusRequest{}

	_, err := s.QueryWriteStatus(ctx, req)
	if err == nil {
		t.Fatal("Expected error response from QueryWriteStatus, got nil")
	}
	st, ok := status.FromError(err)
	if !ok {
		t.Fatalf("Not ok reading grpc status from error")
	}
	if st.Code() != codes.Unimplemented {
		t.Fatalf("Expected status code %d, got: %d", codes.Unimplemented, st.Code())
	}
}

func TestBatchUpdateBlobsStub(t *testing.T) {
	s := casServer{}
	ctx := context.Background()
	req := &remoteexecution.BatchUpdateBlobsRequest{}

	_, err := s.BatchUpdateBlobs(ctx, req)
	if err == nil {
		t.Fatalf("Non-error response from BatchUpdateBlobs")
	}
	st, ok := status.FromError(err)
	if !ok {
		t.Fatalf("Not ok reading grpc status from error")
	}
	if st.Code() != codes.Unimplemented {
		t.Fatalf("Expected status code %d, got: %d", codes.Unimplemented, st.Code())
	}
}

func TestGetTree(t *testing.T) {
	s := casServer{}
	ctx := context.Background()
	req := &remoteexecution.GetTreeRequest{}

	_, err := s.GetTree(ctx, req)
	if err == nil {
		t.Fatalf("Non-error response from GetTree")
	}
	st, ok := status.FromError(err)
	if !ok {
		t.Fatalf("Not ok reading grpc status from error")
	}
	if st.Code() != codes.Unimplemented {
		t.Fatalf("Expected status code %d, got: %d", codes.Unimplemented, st.Code())
	}
}

// Fake Read/Write Servers

// Read server that fakes sending data to a client.
// 	sendCount - tracks times the server invokes Send for verification
// Implements bytestream.ByteStream_ReadServer interface
type fakeReadServer struct {
	buffer    *bytes.Buffer
	sendCount int
	grpc.ServerStream
}

func makeFakeReadServer() *fakeReadServer {
	return &fakeReadServer{
		buffer: new(bytes.Buffer),
	}
}

func (s *fakeReadServer) Send(r *bytestream.ReadResponse) error {
	s.buffer.Write(r.GetData())
	s.sendCount++
	return nil
}

func (s *fakeReadServer) reset() {
	s.buffer.Reset()
	s.sendCount = 0
}

// Write server that fakes receiving specified data from a client.
// One instance will fake-write one piece of data identified by Digest(hash, size),
// []byte data. Chunks supports Recv'ing data in chunks to exercise the CAS server.
//	recvCount - tracks times the server invokes Recv for verification
//	committedSize - tracks the total data len Recv'd by the server for verification
// Implements bytestream.ByteStream_WriteServer interface
type fakeWriteServer struct {
	resourceName  string
	data          []byte
	recvChunks    int
	recvCount     int
	offset        int64
	committedSize int64
	grpc.ServerStream
}

func makeFakeWriteServer(hash string, size int64, data []byte, chunks int) *fakeWriteServer {
	uid, _ := uuid.NewV4()
	return &fakeWriteServer{
		resourceName:  fmt.Sprintf("uploads/%s/blobs/%s/%d", uid, hash, size),
		data:          data,
		recvChunks:    chunks,
		offset:        0,
		committedSize: 0,
	}
}

func (s *fakeWriteServer) SendAndClose(res *bytestream.WriteResponse) error {
	s.committedSize = res.GetCommittedSize()
	return nil
}

func (s *fakeWriteServer) Recv() (*bytestream.WriteRequest, error) {
	// Format a WriteRequest based on the chunks requested and the offset of what has been recvd
	recvLen := int64(len(s.data) / s.recvChunks)
	if s.recvCount+1 >= s.recvChunks {
		recvLen = int64(len(s.data)) - s.offset
	}
	finished := false
	if recvLen+s.offset >= int64(len(s.data)) {
		finished = true
	}
	r := &bytestream.WriteRequest{
		ResourceName: s.resourceName,
		WriteOffset:  0,
		FinishWrite:  finished,
		Data:         s.data[s.offset : s.offset+recvLen],
	}
	s.offset = s.offset + recvLen
	s.recvCount++
	return r, nil
}

repository: AesirMachina/scoot

repo_name: AesirMachina/scoot


text:
inherit pypi python_flit_core

SUMMARY = "Discover and load entry points from installed packages"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=b6f7f5bd22a5dc0397c806c4e5f8cbd3"

PYPI_PACKAGE = "entrypoints"

SRC_URI[sha256sum] = "b706eddaa9218a19ebcd67b56818f05bb27589b1ca9e8d797b74affad4ccacd4"
BBCLASSEXTEND = "native"

license: MIT

repository: Xilinx/meta-jupyter

license_type: permissive

repo_name: Xilinx/meta-jupyter

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
// Copyright (c) 2012-present Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package stats

import (
	"runtime"
	"sync"
	"testing"

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

func TestConcurrentUpdate(t *testing.T) {
	t.Parallel()
	ps := &ProxyStats{}
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for v := 0; v < 100000; v++ {
				ps.AddServed()
				ps.AddBytes(1024)
				runtime.Gosched()
			}
		}()
	}

	wg.Wait()
	c, b := ps.GetStats()
	assert.Equal(t, 10000000, int(c), "unexpected client count")
	assert.Equal(t, 10240000000, int(b), "unexpected bytes count")
}

repository: arachnys/go-camo

repo_name: arachnys/go-camo

gha_language: Go

extension: go


text:
package internal

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/julienschmidt/httprouter"
	log "github.com/sirupsen/logrus"
	"github.com/vcraescu/go-paginator"
	"github.com/vcraescu/go-paginator/adapter"

	"git.mills.io/yarnsocial/yarn"
	"git.mills.io/yarnsocial/yarn/internal/passwords"
	"git.mills.io/yarnsocial/yarn/types"
)

// ContextKey ...
type ContextKey int

const (
	TokenContextKey ContextKey = iota
	UserContextKey
)

var (
	// ErrInvalidCredentials is returned for invalid credentials against /auth
	ErrInvalidCredentials = errors.New("error: invalid credentials")

	// ErrInvalidToken is returned for expired or invalid tokens used in Authorizeation headers
	ErrInvalidToken = errors.New("error: invalid token")
)

// API ...
type API struct {
	router  *Router
	config  *Config
	cache   *Cache
	archive Archiver
	db      Store
	pm      passwords.Passwords
	tasks   *Dispatcher
}

// NewAPI ...
func NewAPI(router *Router, config *Config, cache *Cache, archive Archiver, db Store, pm passwords.Passwords, tasks *Dispatcher) *API {
	api := &API{router, config, cache, archive, db, pm, tasks}

	api.initRoutes()

	return api
}

func (a *API) initRoutes() {
	router := a.router.Group("/api/v1")

	router.GET("/ping", a.PingEndpoint())
	router.POST("/auth", a.AuthEndpoint())
	router.POST("/register", a.RegisterEndpoint())
	router.POST("/config", a.PodConfigEndpoint())

	router.POST("/post", a.isAuthorized(a.PostEndpoint()))
	router.POST("/upload", a.isAuthorized(a.UploadMediaEndpoint()))

	router.GET("/settings", a.isAuthorized(a.SettingsEndpoint()))
	router.POST("/settings", a.isAuthorized(a.SettingsEndpoint()))

	router.POST("/follow", a.isAuthorized(a.FollowEndpoint()))
	router.POST("/unfollow", a.isAuthorized(a.UnfollowEndpoint()))

	router.POST("/mute", a.isAuthorized(a.MuteEndpoint()))
	router.POST("/unmute", a.isAuthorized(a.UnmuteEndpoint()))

	router.POST("/timeline", a.isAuthorized(a.TimelineEndpoint()))
	router.POST("/discover", a.DiscoverEndpoint())

	router.GET("/profile/:nick", a.ProfileEndpoint())
	router.POST("/fetch-twts", a.FetchTwtsEndpoint())
	router.POST("/conv", a.ConversationEndpoint())

	router.POST("/external", a.ExternalProfileEndpoint())

	router.POST("/mentions", a.isAuthorized(a.MentionsEndpoint()))

	// Support / Report endpoints
	router.POST("/support", a.isAuthorized(a.SupportEndpoint()))
	router.POST("/report", a.isAuthorized(a.ReportEndpoint()))
}

// CreateToken ...
func (a *API) CreateToken(user *User, r *http.Request) (*Token, error) {
	claims := jwt.MapClaims{}
	claims["username"] = user.Username
	createdAt := time.Now()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(a.config.APISigningKey))
	if err != nil {
		log.WithError(err).Error("error creating signed token")
		return nil, err
	}

	signedToken, err := jwt.Parse(tokenString, a.jwtKeyFunc)
	if err != nil {
		log.WithError(err).Error("error creating signed token")
		return nil, err
	}

	tkn := &Token{
		Signature: signedToken.Signature,
		Value:     tokenString,
		UserAgent: r.UserAgent(),
		CreatedAt: createdAt,
	}

	return tkn, nil
}

func (a *API) jwtKeyFunc(token *jwt.Token) (interface{}, error) {
	if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
		return nil, fmt.Errorf("There was an error")
	}
	return []byte(a.config.APISigningKey), nil
}

func (a *API) getLoggedInUser(r *http.Request) *User {
	token, err := jwt.Parse(r.Header.Get("Token"), a.jwtKeyFunc)
	if err != nil {
		return nil
	}

	if !token.Valid {
		return nil
	}

	claims := token.Claims.(jwt.MapClaims)

	username := claims["username"].(string)

	user, err := a.db.GetUser(username)
	if err != nil {
		log.WithError(err).Error("error loading user object")
		return nil
	}

	// Every registered new user follows themselves
	// TODO: Make  this configurable server behaviour?
	if user.Following == nil {
		user.Following = make(map[string]string)
	}

	user.Following[user.Username] = user.URL

	return user

}

func (a *API) isAuthorized(endpoint httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		if r.Header.Get("Token") == "" {
			http.Error(w, "No Token Provided", http.StatusUnauthorized)
			return
		}

		token, err := jwt.Parse(r.Header.Get("Token"), a.jwtKeyFunc)
		if err != nil {
			log.WithError(err).Error("error parsing token")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		if token.Valid {
			claims := token.Claims.(jwt.MapClaims)

			username := claims["username"].(string)

			user, err := a.db.GetUser(username)
			if err != nil {
				log.WithError(err).Error("error loading user object")
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}

			// Every registered new user follows themselves
			// TODO: Make  this configurable server behaviour?
			if user.Following == nil {
				user.Following = make(map[string]string)
			}
			user.Following[user.Username] = user.URL

			ctx := context.WithValue(r.Context(), TokenContextKey, token)
			ctx = context.WithValue(ctx, UserContextKey, user)

			endpoint(w, r.WithContext(ctx), p)
		} else {
			http.Error(w, "Invalid Token", http.StatusUnauthorized)
			return
		}
	}
}

// PingEndpoint ...
func (a *API) PingEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// RegisterEndpoint ...
func (a *API) RegisterEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		req, err := types.NewRegisterRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing register request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		username := NormalizeUsername(req.Username)
		password := req.Password
		// XXX: We DO NOT store this! (EVER)
		email := strings.TrimSpace(req.Email)

		if err := ValidateUsername(username); err != nil {
			http.Error(w, "Bad Username", http.StatusBadRequest)
			return
		}

		if a.db.HasUser(username) || a.db.HasFeed(username) {
			http.Error(w, "Username Exists", http.StatusBadRequest)
			return
		}

		fn := filepath.Join(a.config.Data, feedsDir, username)
		if _, err := os.Stat(fn); err == nil {
			http.Error(w, "Feed Exists", http.StatusBadRequest)
			return
		}

		if err := ioutil.WriteFile(fn, []byte{}, 0644); err != nil {
			log.WithError(err).Error("error creating new user feed")
			http.Error(w, "Feed Creation Failed", http.StatusInternalServerError)
			return
		}

		hash, err := a.pm.CreatePassword(password)
		if err != nil {
			log.WithError(err).Error("error creating password hash")
			http.Error(w, "Passwrod Creation Failed", http.StatusInternalServerError)
			return
		}

		recoveryHash := fmt.Sprintf("email:%s", FastHash(email))

		user := &User{
			Username:  username,
			Password:  hash,
			Recovery:  recoveryHash,
			URL:       URLForUser(a.config.BaseURL, username),
			CreatedAt: time.Now(),
		}

		if err := a.db.SetUser(username, user); err != nil {
			log.WithError(err).Error("error saving user object for new user")
			http.Error(w, "User Creation Failed", http.StatusInternalServerError)
			return
		}

		log.Infof("user registered: %v", user)
	}
}

// AuthEndpoint ...
func (a *API) AuthEndpoint() httprouter.Handle {
	// #239: Throttle failed login attempts and lock user  account.
	failures := NewTTLCache(5 * time.Minute)

	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		req, err := types.NewAuthRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing auth request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		username := NormalizeUsername(req.Username)
		password := req.Password

		// Error: no username or password provided
		if username == "" || password == "" {
			log.Warn("no username or password provided")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		// Lookup user
		user, err := a.db.GetUser(username)
		if err != nil {
			log.WithField("username", username).Warn("login attempt from non-existent user")
			http.Error(w, "Invalid Credentials", http.StatusUnauthorized)
			return
		}

		// #239: Throttle failed login attempts and lock user  account.
		if failures.Get(user.Username) > MaxFailedLogins {
			http.Error(w, "Account Locked", http.StatusTooManyRequests)
			return
		}

		// Validate cleartext password against KDF hash
		err = a.pm.CheckPassword(user.Password, password)
		if err != nil {
			// #239: Throttle failed login attempts and lock user  account.
			failed := failures.Inc(user.Username)
			time.Sleep(time.Duration(IntPow(2, failed)) * time.Second)

			log.WithField("username", username).Warn("login attempt with invalid credentials")
			http.Error(w, "Invalid Credentials", http.StatusUnauthorized)
			return
		}

		// #239: Throttle failed login attempts and lock user  account.
		failures.Reset(user.Username)

		// Login successful
		log.WithField("username", username).Info("login successful")

		token, err := a.CreateToken(user, r)
		if err != nil {
			log.WithError(err).Error("error creating token")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		user.AddToken(token)
		if err := a.db.SetToken(token.Signature, token); err != nil {
			log.WithError(err).Error("error saving token object")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Error("error saving user object")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.AuthResponse{Token: token.Value}

		body, err := res.Bytes()
		if err != nil {
			log.WithError(err).Error("error serializing response")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(body)
	}
}

// PostEndpoint ...
func (a *API) PostEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		user := r.Context().Value(UserContextKey).(*User)

		req, err := types.NewPostRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing post request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		text := CleanTwt(req.Text)
		if text == "" {
			log.Warn("no text provided for post")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		switch req.PostAs {
		case "", me:
			_, err = AppendTwt(a.config, a.db, user, text)
		default:
			if user.OwnsFeed(req.PostAs) {
				_, err = AppendSpecial(a.config, a.db, req.PostAs, text)
			} else {
				err = ErrFeedImposter
			}
		}

		if err != nil {
			log.WithError(err).Error("error posting twt")
			if err == ErrFeedImposter {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
			} else {
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			}
			return
		}

		// Update user's own timeline with their own new post.
		a.cache.FetchTwts(a.config, a.archive, user.Source(), nil)

		// Re-populate/Warm cache with local twts for this pod
		a.cache.GetByPrefix(a.config.BaseURL, true)

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// TimelineEndpoint ...
func (a *API) TimelineEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		user := r.Context().Value(UserContextKey).(*User)

		req, err := types.NewPagedRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing post request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		var twts types.Twts

		for feed := range user.Sources() {
			twts = append(twts, a.cache.GetByURL(feed.URL)...)
		}

		sort.Sort(twts)

		var pagedTwts types.Twts

		pager := paginator.New(adapter.NewSliceAdapter(twts), a.config.TwtsPerPage)
		pager.SetPage(req.Page)

		if err = pager.Results(&pagedTwts); err != nil {
			log.WithError(err).Error("error loading timeline")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.PagedResponse{
			Twts: FilterTwts(user, pagedTwts),
			Pager: types.PagerResponse{
				Current:   pager.Page(),
				MaxPages:  pager.PageNums(),
				TotalTwts: pager.Nums(),
			},
		}

		body, err := res.Bytes()
		if err != nil {
			log.WithError(err).Error("error serializing response")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(body)
	}
}

// DiscoverEndpoint ...
func (a *API) DiscoverEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		loggedInUser := a.getLoggedInUser(r)

		req, err := types.NewPagedRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing post request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		twts := a.cache.GetByPrefix(a.config.BaseURL, false)

		var pagedTwts types.Twts

		pager := paginator.New(adapter.NewSliceAdapter(twts), a.config.TwtsPerPage)
		pager.SetPage(req.Page)

		if err = pager.Results(&pagedTwts); err != nil {
			log.WithError(err).Error("error loading discover")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.PagedResponse{
			Twts: FilterTwts(loggedInUser, pagedTwts),
			Pager: types.PagerResponse{
				Current:   pager.Page(),
				MaxPages:  pager.PageNums(),
				TotalTwts: pager.Nums(),
			},
		}

		body, err := res.Bytes()
		if err != nil {
			log.WithError(err).Error("error serializing response")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(body)
	}
}

// MentionsEndpoint ...
func (a *API) MentionsEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		req, err := types.NewPagedRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing post request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		user := r.Context().Value(UserContextKey).(*User)

		twts := a.cache.GetMentions(user)
		sort.Sort(twts)

		var pagedTwts types.Twts

		pager := paginator.New(adapter.NewSliceAdapter(twts), a.config.TwtsPerPage)
		pager.SetPage(req.Page)

		if err = pager.Results(&pagedTwts); err != nil {
			log.WithError(err).Error("error loading discover")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.PagedResponse{
			Twts: FilterTwts(user, pagedTwts),
			Pager: types.PagerResponse{
				Current:   pager.Page(),
				MaxPages:  pager.PageNums(),
				TotalTwts: pager.Nums(),
			},
		}

		body, err := res.Bytes()
		if err != nil {
			log.WithError(err).Error("error serializing response")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(body)
	}
}

// FollowEndpoint ...
func (a *API) FollowEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		user := r.Context().Value(UserContextKey).(*User)

		req, err := types.NewFollowRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing follow request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := strings.TrimSpace(req.Nick)
		url := NormalizeURL(req.URL)

		if nick == "" || url == "" {
			log.Warn("no nick or url provided")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		if err := user.FollowAndValidate(a.config, nick, url); err != nil {
			log.WithError(err).Errorf("error validating new feed @<%s %s>", nick, url)
			http.Error(w, "Invalid Feed", http.StatusBadRequest)
			return
		}

		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Error("error saving user object")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		if strings.HasPrefix(url, a.config.BaseURL) {
			url = UserURL(url)
			nick := NormalizeUsername(filepath.Base(url))

			if a.db.HasUser(nick) {
				followee, err := a.db.GetUser(nick)
				if err != nil {
					log.WithError(err).Errorf("error loading user object for %s", nick)
					http.Error(w, "Internal Server Error", http.StatusInternalServerError)
					return
				}

				if followee.Followers == nil {
					followee.Followers = make(map[string]string)
				}

				followee.Followers[user.Username] = user.URL

				if err := a.db.SetUser(followee.Username, followee); err != nil {
					log.WithError(err).Warnf("error updating user object for followee %s", followee.Username)
					http.Error(w, "Internal Server Error", http.StatusInternalServerError)
					return
				}

				if _, err := AppendSpecial(
					a.config, a.db,
					twtxtBot,
					fmt.Sprintf(
						"FOLLOW: @<%s %s> from @<%s %s> using %s/%s",
						followee.Username, URLForUser(a.config.BaseURL, followee.Username),
						user.Username, URLForUser(a.config.BaseURL, user.Username),
						"yarnd", yarn.FullVersion(),
					),
				); err != nil {
					log.WithError(err).Warnf("error appending special FOLLOW post")
				}
			} else if a.db.HasFeed(nick) {
				feed, err := a.db.GetFeed(nick)
				if err != nil {
					log.WithError(err).Errorf("error loading feed object for %s", nick)
					http.Error(w, "Internal Server Error", http.StatusInternalServerError)
					return
				}

				feed.Followers[user.Username] = user.URL

				if err := a.db.SetFeed(feed.Name, feed); err != nil {
					log.WithError(err).Warnf("error updating user object for followee %s", feed.Name)
					http.Error(w, "Internal Server Error", http.StatusInternalServerError)
					return
				}

				if _, err := AppendSpecial(
					a.config, a.db,
					twtxtBot,
					fmt.Sprintf(
						"FOLLOW: @<%s %s> from @<%s %s> using %s/%s",
						feed.Name, URLForUser(a.config.BaseURL, feed.Name),
						user.Username, URLForUser(a.config.BaseURL, user.Username),
						"yarnd", yarn.FullVersion(),
					),
				); err != nil {
					log.WithError(err).Warnf("error appending special FOLLOW post")
				}
			}
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// UnfollowEndpoint ...
func (a *API) UnfollowEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		req, err := types.NewUnfollowRequest(r.Body)

		if err != nil {
			log.WithError(err).Error("error parsing follow request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := req.Nick

		if nick == "" {
			log.Error("no nick provided")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		user := r.Context().Value(UserContextKey).(*User)

		if user == nil {
			log.Fatalf("user not found in context")
		}

		url, ok := user.Following[nick]
		if !ok {
			log.Errorf("user %s is not following %s", nick, url)
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		delete(user.Following, nick)

		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Warnf("error updating user object for user  %s", user.Username)
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		if strings.HasPrefix(url, a.config.BaseURL) {
			url = UserURL(url)
			nick := NormalizeUsername(filepath.Base(url))
			followee, err := a.db.GetUser(nick)
			if err != nil {
				log.WithError(err).Warnf("error loading user object for followee %s", nick)
			} else {
				if followee.Followers != nil {
					delete(followee.Followers, user.Username)
					if err := a.db.SetUser(followee.Username, followee); err != nil {
						log.WithError(err).Warnf("error updating user object for followee %s", followee.Username)
					}
				}
				if _, err := AppendSpecial(
					a.config, a.db,
					twtxtBot,
					fmt.Sprintf(
						"UNFOLLOW: @<%s %s> from @<%s %s> using %s/%s",
						followee.Username, URLForUser(a.config.BaseURL, followee.Username),
						user.Username, URLForUser(a.config.BaseURL, user.Username),
						"yarnd", yarn.FullVersion(),
					),
				); err != nil {
					log.WithError(err).Warnf("error appending special FOLLOW post")
				}
			}
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// SettingsEndpoint ...
func (a *API) SettingsEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		// Limit request body to to abuse
		r.Body = http.MaxBytesReader(w, r.Body, a.config.MaxUploadSize)
		defer r.Body.Close()

		user := r.Context().Value(UserContextKey).(*User)

		if r.Method == http.MethodGet {
			data, err := json.Marshal(user)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_, _ = w.Write(data)
			return
		}

		// XXX: We DO NOT store this! (EVER)
		email := strings.TrimSpace(r.FormValue("email"))
		tagline := strings.TrimSpace(r.FormValue("tagline"))
		password := r.FormValue("password")

		isFollowersPubliclyVisible := r.FormValue("isFollowersPubliclyVisible") == "on"
		isFollowingPubliclyVisible := r.FormValue("isFollowingPubliclyVisible") == "on"

		avatarFile, _, err := r.FormFile("avatar_file")
		if err != nil && err != http.ErrMissingFile {
			log.WithError(err).Error("error parsing form file")
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if password != "" {
			hash, err := a.pm.CreatePassword(password)
			if err != nil {
				log.WithError(err).Error("error creating password hash")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			user.Password = hash
		}

		if avatarFile != nil {
			opts := &ImageOptions{
				Resize: true,
				Width:  AvatarResolution,
				Height: AvatarResolution,
			}
			_, err = StoreUploadedImage(
				a.config, avatarFile,
				avatarsDir, user.Username,
				opts,
			)
			if err != nil {
				log.WithError(err).Error("error updating user avatar")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		recoveryHash := fmt.Sprintf("email:%s", FastHash(email))

		user.Recovery = recoveryHash
		user.Tagline = tagline

		// XXX: Commented out as these are more specific to the Web App currently.
		// API clients such as Goryon (the Flutter iOS/Android app) have their own mechanisms.
		// user.Theme = theme
		// user.DisplayDatesInTimezone = displayDatesInTimezone

		user.IsFollowersPubliclyVisible = isFollowersPubliclyVisible
		user.IsFollowingPubliclyVisible = isFollowingPubliclyVisible

		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Error("error updating user object")
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// OldUploadMediaEndpoint ...
// TODO: Remove when the api_old_upload_media counter nears zero
// XXX: Used for Goryon < v1.0.3
func (a *API) OldUploadMediaEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		// Limit request body to to abuse
		r.Body = http.MaxBytesReader(w, r.Body, a.config.MaxUploadSize)
		defer r.Body.Close()

		mediaFile, _, err := r.FormFile("media_file")
		if err != nil && err != http.ErrMissingFile {
			log.WithError(err).Error("error parsing form file")
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		var mediaURI string

		if mediaFile != nil {
			opts := &ImageOptions{Resize: true, Width: MediaResolution, Height: 0}
			mediaURI, err = StoreUploadedImage(
				a.config, mediaFile,
				mediaDir, "",
				opts,
			)

			if err != nil {
				log.WithError(err).Error("error storing the file")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		uri := URI{"mediaURI", mediaURI}
		data, err := json.Marshal(uri)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

// UploadMediaHandler ...
func (a *API) UploadMediaEndpoint() httprouter.Handle {
	oldUploadMediaEndpoint := a.OldUploadMediaEndpoint()
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		// Support for older clients pre v1.0.3 (See: OldMediaEndpoint)
		//
		if strings.HasPrefix(r.UserAgent(), "Dart") {
			oldUploadMediaEndpoint(w, r, p)
			return
		}

		// Limit request body to to abuse
		r.Body = http.MaxBytesReader(w, r.Body, a.config.MaxUploadSize)

		mfile, headers, err := r.FormFile("media_file")
		if err != nil && err != http.ErrMissingFile {
			if err.Error() == "http: request body too large" {
				log.Warnf("request too large for media upload from %s", FormatRequest(r))
				http.Error(w, "Media Upload Too Large", http.StatusRequestEntityTooLarge)
				return
			}
			log.WithError(err).Error("error parsing form file")
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if mfile == nil || headers == nil {
			log.Warn("no valid media file uploaded")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		ctype := headers.Header.Get("Content-Type")

		var uri URI

		if strings.HasPrefix(ctype, "image/") {
			fn, err := ReceiveImage(mfile)
			if err != nil {
				log.WithError(err).Error("error writing uploaded image")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			uuid, err := a.tasks.Dispatch(NewImageTask(a.config, fn))
			if err != nil {
				log.WithError(err).Error("error dispatching image processing task")
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			uri.Type = "taskURI"
			uri.Path = URLForTask(a.config.BaseURL, uuid)
		}

		if strings.HasPrefix(ctype, "audio/") {
			fn, err := ReceiveAudio(mfile)
			if err != nil {
				log.WithError(err).Error("error writing uploaded audio")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			uuid, err := a.tasks.Dispatch(NewAudioTask(a.config, fn))
			if err != nil {
				log.WithError(err).Error("error dispatching audio transcoding task")
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			uri.Type = "taskURI"
			uri.Path = URLForTask(a.config.BaseURL, uuid)
		}

		if strings.HasPrefix(ctype, "video/") {
			fn, err := ReceiveVideo(mfile)
			if err != nil {
				log.WithError(err).Error("error writing uploaded video")
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			uuid, err := a.tasks.Dispatch(NewVideoTask(a.config, fn))
			if err != nil {
				log.WithError(err).Error("error dispatching vodeo transcode task")
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			uri.Type = "taskURI"
			uri.Path = URLForTask(a.config.BaseURL, uuid)
		}

		if uri.IsZero() {
			log.Warn("no media file provided or unsupported media type")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		data, err := json.Marshal(uri)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		if uri.Type == "taskURI" {
			w.WriteHeader(http.StatusAccepted)
		}
		_, _ = w.Write(data)
	}
}

// ProfileEndpoint ...
func (a *API) ProfileEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		loggedInUser := a.getLoggedInUser(r)

		nick := NormalizeUsername(p.ByName("nick"))
		if nick == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick = NormalizeUsername(nick)

		var profile types.Profile

		if a.db.HasUser(nick) {
			user, err := a.db.GetUser(nick)
			if err != nil {
				log.WithError(err).Errorf("error loading user object for %s", nick)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			profile = user.Profile(a.config.BaseURL, loggedInUser)

			if loggedInUser == nil {
				if !user.IsFollowersPubliclyVisible {
					profile.Followers = map[string]string{}
				}
				if !user.IsFollowingPubliclyVisible {
					profile.Following = map[string]string{}
				}
			}
		} else if a.db.HasFeed(nick) {
			feed, err := a.db.GetFeed(nick)
			if err != nil {
				log.WithError(err).Errorf("error loading feed object for %s", nick)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			profile = feed.Profile(a.config.BaseURL, loggedInUser)
		} else {
			http.Error(w, "User/Feed not found", http.StatusNotFound)
			return
		}

		profileResponse := types.ProfileResponse{}

		profileResponse.Profile = profile

		profileResponse.Links = types.Links{types.Link{
			Href: fmt.Sprintf("%s/webmention", UserURL(profile.URL)),
			Rel:  "webmention",
		}}

		profileResponse.Alternatives = types.Alternatives{
			types.Alternative{
				Type:  "application/atom+xml",
				Title: fmt.Sprintf("%s local feed", a.config.Name),
				URL:   fmt.Sprintf("%s/atom.xml", a.config.BaseURL),
			},
			types.Alternative{
				Type:  "text/plain",
				Title: fmt.Sprintf("%s's Twtxt Feed", profile.Username),
				URL:   profile.URL,
			},
			types.Alternative{
				Type:  "application/atom+xml",
				Title: fmt.Sprintf("%s's Atom Feed", profile.Username),
				URL:   fmt.Sprintf("%s/atom.xml", UserURL(profile.URL)),
			},
		}

		profileResponse.Twter = types.Twter{
			Nick:   profile.Username,
			Avatar: URLForAvatar(a.config.BaseURL, profile.Username),
			URL:    URLForUser(a.config.BaseURL, profile.Username),
		}

		data, err := json.Marshal(profileResponse)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

// ConversationEndpoint ...
func (a *API) ConversationEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		loggedInUser := a.getLoggedInUser(r)

		req, err := types.NewConversationRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing conversation request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		hash := req.Hash

		if hash == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		twt, ok := a.cache.Lookup(hash)
		if !ok {
			// If the twt is not in the cache look for it in the archive
			if a.archive.Has(hash) {
				twt, err = a.archive.Get(hash)
				if err != nil {
					log.WithError(err).Errorf("error fetching twt %s from archive", hash)
					http.Error(w, "Bad Request", http.StatusBadRequest)
					return
				}
			}
		}

		if twt.IsZero() {
			http.Error(w, "Conversation Not Found", http.StatusNotFound)
			return
		}

		getTweetsByHash := func(hash string, replyTo types.Twt) types.Twts {
			var result types.Twts
			seen := make(map[string]bool)
			// TODO: Improve this by making this an O(1) lookup on the tag
			for _, twt := range a.cache.GetAll() {
				var lis types.TagList = twt.Tags()
				if HasString(UniqStrings(lis.Tags()), hash) && !seen[twt.Hash()] {
					result = append(result, twt)
					seen[twt.Hash()] = true
				}
			}
			if !seen[replyTo.Hash()] {
				result = append(result, replyTo)
			}
			return result
		}

		twts := getTweetsByHash(hash, twt)
		sort.Sort(sort.Reverse(twts))

		var pagedTwts types.Twts

		pager := paginator.New(adapter.NewSliceAdapter(twts), a.config.TwtsPerPage)
		pager.SetPage(req.Page)

		if err = pager.Results(&pagedTwts); err != nil {
			log.WithError(err).Error("error loading twts")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.PagedResponse{
			Twts: FilterTwts(loggedInUser, pagedTwts),
			Pager: types.PagerResponse{
				Current:   pager.Page(),
				MaxPages:  pager.PageNums(),
				TotalTwts: pager.Nums(),
			},
		}

		data, err := json.Marshal(res)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

// FetchTwtsEndpoint ...
func (a *API) FetchTwtsEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		loggedInUser := a.getLoggedInUser(r)

		req, err := types.NewFetchTwtsRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing fetch twts request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := NormalizeUsername(req.Nick)
		if nick == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		var profile types.Profile
		var twts types.Twts

		if a.db.HasUser(nick) {
			user, err := a.db.GetUser(nick)
			if err != nil {
				log.WithError(err).Errorf("error loading user object for %s", nick)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			profile = user.Profile(a.config.BaseURL, loggedInUser)
			twts = a.cache.GetByURL(profile.URL)
		} else if a.db.HasFeed(nick) {
			feed, err := a.db.GetFeed(nick)
			if err != nil {
				log.WithError(err).Errorf("error loading feed object for %s", nick)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			profile = feed.Profile(a.config.BaseURL, loggedInUser)

			twts = a.cache.GetByURL(profile.URL)
		} else if req.URL != "" {
			if !a.cache.IsCached(req.URL) {
				sources := make(types.Feeds)
				sources[types.Feed{Nick: nick, URL: req.URL}] = true
				a.cache.FetchTwts(a.config, a.archive, sources, nil)
			}

			twts = a.cache.GetByURL(req.URL)
		} else {
			http.Error(w, "User/Feed not found", http.StatusNotFound)
			return
		}

		var pagedTwts types.Twts

		pager := paginator.New(adapter.NewSliceAdapter(twts), a.config.TwtsPerPage)
		pager.SetPage(req.Page)

		if err = pager.Results(&pagedTwts); err != nil {
			log.WithError(err).Error("error loading twts")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		res := types.PagedResponse{
			Twts: FilterTwts(loggedInUser, pagedTwts),
			Pager: types.PagerResponse{
				Current:   pager.Page(),
				MaxPages:  pager.PageNums(),
				TotalTwts: pager.Nums(),
			},
		}

		data, err := json.Marshal(res)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

// ExternalProfileEndpoint ...
func (a *API) ExternalProfileEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		loggedInUser := a.getLoggedInUser(r)
		req, err := types.NewExternalProfileRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing external profile request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		url := req.URL
		nick := req.Nick

		if url == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		if nick == "" {
			log.Warn("no nick given to external profile request")
			nick = "unknown"
		}

		profileResponse := types.ProfileResponse{}

		profileResponse.Profile = types.Profile{
			Username: nick,
			TwtURL:   url,
			URL:      url,

			Follows:    loggedInUser.Follows(url),
			FollowedBy: loggedInUser.FollowedBy(url),
			Muted:      loggedInUser.HasMuted(url),
		}

		profileResponse.Twter = types.Twter{
			Nick:   nick,
			Avatar: URLForExternalAvatar(a.config, url),
			URL:    URLForExternalProfile(a.config, nick, url),
		}

		data, err := json.Marshal(profileResponse)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

// MuteEndpoint ...
func (a *API) MuteEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		user := r.Context().Value(UserContextKey).(*User)

		req, err := types.NewMuteRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing mute request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := req.Nick
		url := req.URL

		if nick == "" || url == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		user.Mute(nick, url)

		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Error("error updating user object")
			http.Error(w, "User Update Failed", http.StatusInternalServerError)
			return
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))

	}
}

// UnmuteEndpoint ...
func (a *API) UnmuteEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		user := r.Context().Value(UserContextKey).(*User)

		req, err := types.NewUnmuteRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing unmute request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := req.Nick

		if nick == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		user.Unmute(nick)

		if err := a.db.SetUser(user.Username, user); err != nil {
			log.WithError(err).Error("error updating user object")
			http.Error(w, "User Update Failed", http.StatusInternalServerError)
			return
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))
	}
}

// SupportEndpoint ...
func (a *API) SupportEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		req, err := types.NewSupportRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing support request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		name := req.Name
		email := req.Email
		subject := req.Subject
		message := req.Message

		if err := SendSupportRequestEmail(a.config, name, email, subject, message); err != nil {
			log.WithError(err).Errorf("unable to send support email for %s", email)
			log.WithError(err).Error("error sending support request")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		log.Infof("support message email sent for %s", email)

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))

	}
}

// ReportEndpoint ...
func (a *API) ReportEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		req, err := types.NewReportRequest(r.Body)
		if err != nil {
			log.WithError(err).Error("error parsing report request")
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		nick := req.Nick
		url := req.URL

		if nick == "" || url == "" {
			http.Error(w, "Bad Request", http.StatusBadRequest)
			return
		}

		name := req.Name
		email := req.Email
		category := req.Category
		message := req.Message

		if err := SendReportAbuseEmail(a.config, nick, url, name, email, category, message); err != nil {
			log.WithError(err).Errorf("unable to send report email for %s", email)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		// No real response
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{}`))

	}
}

// PodConfigEndpoint ...
func (a *API) PodConfigEndpoint() httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		data, err := json.Marshal(a.config.Settings())
		if err != nil {
			log.WithError(err).Error("error serializing pod config response")
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}
}

repository: hugefiver/twi-yarn

repo_name: hugefiver/twi-yarn


text:
/*
// TCS230 color recognition sensor
// Sensor connection pins to Arduino are shown in comments

Color Sensor      Arduino
-----------      --------
 VCC               5V
 GND               GND
 s0                8
 s1                9
 s2                12
 s3                11
 OUT               10
 OE                GND
*/
#include <Servo.h>
Servo m1;
Servo m2;
Servo m3;
Servo m4;

int pos = 0;
const int s0 = 8;
const int s1 = 9;
const int s2 = 12;
const int s3 = 11;
const int out = 10;
// Variables
int red = 0;
int green = 0;
int blue = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(out, INPUT);
  digitalWrite(s0, HIGH);
  digitalWrite(s1, HIGH);

   m1.attach (2);
   m2.attach (3);
   m3.attach (4);
   m4.attach (5);
}

void loop()
{
  color();
  Serial.print("R Intensity:");
  Serial.print(red, DEC);
  Serial.print(" G Intensity: ");
  Serial.print(green, DEC);
  Serial.print(" B Intensity : ");
  Serial.print(blue, DEC);
  //Serial.println();

  if (red < blue && red < green && red < 20)
  {
   Serial.println(" - (Red Color)");
   m2.write (90);
   delay (30);

   m3.write (0);
   delay (30);
   m4.write (180);
   delay (30);
   m1.write (0);
   delay (600);

// Pengambilan Kotak

  for (pos=0; pos<= 66; pos +=1 ){
  m3.write (pos);
  delay (12);
}
  m3.write (45);
  delay (200);

   m2.write (50);
   delay (500);
   m2.write (60);
   delay (500);

// Pencengkraman Gripper
  m1.write (90);
  delay (2000);

// peletakan objek
  for (pos=45 ; pos>= 0; pos -=1){

  m3.write (pos);
  delay (10);
}
  m4.write (40);
  delay (80);

  for (pos=0 ; pos<=40 ; pos +=1){
   m3.write (pos);
   delay (10);
    }
    m3.write (45);
    delay (500);

    m1.write (0);
    delay (500);
  for (pos=45 ; pos>= 0; pos -=1){

  m3.write (pos);
  delay (10);
}
  for (pos = 75; pos<= 90; pos += 1){
  m2.write (pos);
  delay (50);
}
  m4.write (180);
  delay (100);
  }

  else if (blue < red && blue < green)
  {
   Serial.println(" - (Blue Color)");

   m2.write (90);
   delay (30);

   m3.write (0);
   delay (30);
   m4.write (180);
   delay (30);
   m1.write (0);
   delay (600);

// Pengambilan Kotak

for (pos=0; pos<= 66; pos +=1 ){
  m3.write (pos);
  delay (12);
}
  m3.write (45);
  delay (200);

   m2.write (50);
   delay (500);
   m2.write (54);
   delay (500);

// Pencengkraman Gripper
  m1.write (90);
  delay (2000);

// peletakan objek
  for (pos=45 ; pos>= 0; pos -=1){

  m3.write (pos);
  delay (10);
  }
 m4.write (100);
 // m4.write (120);
  delay (350);

  for (pos=0 ; pos<=40 ; pos +=1){
   m3.write (pos);
   delay (10);
    }
    m3.write (45);
    delay (500);

    m1.write (0);
    delay (500);
  for (pos=45 ; pos>= 0; pos -=1){

  m3.write (pos);
  delay (10);
  }
  for (pos = 75; pos<= 90; pos += 1){
  m2.write (pos);
  delay (50);
  }
  m4.write (180);
  delay (800);

    }

  else if (green < red && green < blue)
  {
   Serial.println(" - (Green Color)");

  m2.write (90);
  delay (30);
  m3.write (0);
  delay (30);
  m4.write (180);
  delay (30);
  m1.write (0);
  delay (600);

  for (pos=0; pos<= 66; pos += 1){
  m3.write (pos);
  delay (12);
  }
  m3.write (45);
  delay (700);

  m2.write (40);
  delay (10);
  m2.write (50);
  delay (700);

  m1.write (90);
  delay (2000);

for (pos = 45; pos>=0; pos -=1){
  m3.write (pos);
  delay (10);
}
  m3.write (0);
  delay (500);

  m4.write (60);
  delay (350);

for (pos = 0; pos <= 40; pos+=1){
  m3.write (pos);
  delay (20);
}
  m3.write (45);
  delay (500);

  m1.write (0);
  delay (500);

for (pos = 45; pos>= 0; pos-=1){
  m3.write (20);
}

for (pos = 80; pos <= 90; pos+=1 ){
  m2.write (pos);
  delay (50);
}
  m4.write (180);
  delay (800);
  }

  else{
  Serial.println();
  }
  delay(300);
}

void color()
{
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  //count OUT, pRed, RED
  red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);
  digitalWrite(s3, HIGH);
  //count OUT, pBLUE, BLUE
  blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);
  digitalWrite(s2, HIGH);
  //count OUT, pGreen, GREEN
  green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);
}

branch_name: refs/heads/main

extension: ino


text:
package db

import (
	"strings"
	"testing"
)

var dao DaoImpl

func init() {
	dao = DaoImpl{nil, false}
}

func TestColumns(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id")
	sel.Columns("name")
	sel.From("tbl_user")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, name FROM tbl_user"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
}

func TestWhere1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id", 10)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id = $1"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestWhere2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id > ", 10)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id > $1"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
}

func TestWhere3(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id >= 10", nil)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id >= 10"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestWhereAnd1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id", 10)
	sel.Where("nid", 30)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id = $1 AND nid = $2"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 2 {
		t.Errorf("Param count: expected(2), found(%d)", len(params))
	}
}

func TestWhereAnd2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id", 10)
	sel.Where("nid", 30)
	sel.Where("name LIKE 'who%'", nil)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id = $1 AND nid = $2 AND name LIKE 'who%'"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 2 {
		t.Errorf("Param count: expected(2), found(%d)", len(params))
	}
}

func TestWhereOr(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "name")
	sel.From("tbl_user")
	sel.Where("id", 10)
	sel.OrWhere("id", 30)
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, name FROM tbl_user WHERE id = $1 OR id = $2"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 2 {
		t.Errorf("Param count: expected(2), found(%d)", len(params))
	}
}

func TestWhereBlock1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.Where("country", "10")
	sel.BlockBegin()
	sel.Where("state", "100")
	sel.OrWhere("state", "200")
	sel.BlockEnd()
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE country = $1 AND ( state = $2 OR state = $3 )"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 3 {
		t.Errorf("Param count: expected(3), found(%d)", len(params))
	}
}

func TestWhereBlock2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.Where("country", "10")
	sel.BlockBegin()
	sel.OrWhere("state", "100")
	sel.Where("city", "1000")
	sel.BlockEnd()
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE country = $1 OR ( state = $2 AND city = $3 )"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 3 {
		t.Errorf("Param count: expected(3), found(%d)", len(params))
	}
}

func TestWhereBlock3(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.BlockBegin()
	sel.Where("country", "10")
	sel.Where("state", "20")
	sel.BlockEnd()
	sel.OrWhere("first_name LIKE", "Who%")
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE ( country = $1 AND state = $2 ) OR first_name LIKE $3"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 3 {
		t.Errorf("Param count: expected(3), found(%d)", len(params))
	}
}

func TestWhereBlock4(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.Where("country", "10")
	sel.BlockBegin()
	sel.Where("state", "100")
	sel.OrWhere("state", "200")
	sel.BlockEnd()
	sel.Where("first_name LIKE", "who%")
	query := standardizeString(sel.GetQuery())
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE country = $1 AND ( state = $2 OR state = $3 ) AND first_name LIKE $4"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 4 {
		t.Errorf("Param count: expected(4), found(%d)", len(params))
	}
}

func TestLimit1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id")
	sel.Columns("name")
	sel.From("tbl_user")
	sel.Limit(1)
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, name FROM tbl_user LIMIT 1"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
}

func TestLimit2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id")
	sel.Columns("name")
	sel.From("tbl_user")
	sel.Where("country", "10")
	sel.Limit(1)
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, name FROM tbl_user WHERE country = $1 LIMIT 1"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestOffset1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id")
	sel.Columns("name")
	sel.From("tbl_user")
	sel.Limit(10)
	sel.Offset(20)
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, name FROM tbl_user LIMIT 10 OFFSET 20"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
}

func TestOffset2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id")
	sel.Columns("name")
	sel.From("tbl_user")
	sel.Where("country", "10")
	sel.Limit(10)
	sel.Offset(20)
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, name FROM tbl_user WHERE country = $1 LIMIT 10 OFFSET 20"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestGroupBy1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("country", "COUNT(*) AS cnt")
	sel.From("tbl_user")
	sel.GroupBy("country")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT country, COUNT(*) AS cnt FROM tbl_user GROUP BY country"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestGroupBy2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("country", "COUNT(*) AS cnt")
	sel.From("tbl_user")
	sel.Where("id > 200", nil)
	sel.GroupBy("country")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT country, COUNT(*) AS cnt FROM tbl_user WHERE id > 200 GROUP BY country"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestHaving1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("country", "COUNT(*) AS cnt")
	sel.From("tbl_user")
	sel.GroupBy("country")
	sel.Having("cnt > 10")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT country, COUNT(*) AS cnt FROM tbl_user GROUP BY country HAVING cnt > 10"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestHaving2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("country", "COUNT(*) AS cnt")
	sel.From("tbl_user")
	sel.Where("id > ", 200)
	sel.GroupBy("country")
	sel.Having("cnt > 10")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT country, COUNT(*) AS cnt FROM tbl_user WHERE id > $1 GROUP BY country HAVING cnt > 10"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestOrderBy1(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.OrderBy("first_name")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, first_name, last_name FROM tbl_user ORDER BY first_name"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestOrderBy2(t *testing.T) {
	sel := GetSelect()
	sel.Columns("id", "first_name", "last_name")
	sel.From("tbl_user")
	sel.Where("id > ", 10)
	sel.OrderBy("first_name")
	sel.OrderBy("last_name")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE id > $1 ORDER BY first_name, last_name"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestJoin(t *testing.T) {
	sel := GetSelect()
	sel.Columns("tu.id", "tu.first_name", "tu.last_name", "td.name")
	sel.From("tbl_user AS tu")
	sel.Join("tbl_department AS td", "tu.department_id = td.id")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT tu.id, tu.first_name, tu.last_name, td.name FROM tbl_user AS tu INNER JOIN tbl_department AS td ON tu.department_id = td.id"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestLeftJoin(t *testing.T) {
	sel := GetSelect()
	sel.Columns("tu.id", "tu.first_name", "tu.last_name", "td.name")
	sel.From("tbl_user AS tu")
	sel.LeftJoin("tbl_department AS td", "tu.department_id = td.id")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT tu.id, tu.first_name, tu.last_name, td.name FROM tbl_user AS tu LEFT OUTER JOIN tbl_department AS td ON tu.department_id = td.id"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestRightJoin(t *testing.T) {
	sel := GetSelect()
	sel.Columns("tu.id", "tu.first_name", "tu.last_name", "td.name")
	sel.From("tbl_user AS tu")
	sel.RightJoin("tbl_department AS td", "tu.department_id = td.id")
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT tu.id, tu.first_name, tu.last_name, td.name FROM tbl_user AS tu RIGHT OUTER JOIN tbl_department AS td ON tu.department_id = td.id"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 0 {
		t.Errorf("Param count: expected(0), found(%d)", len(params))
	}
}

func TestAll(t *testing.T) {
	sel := GetSelect()
	sel.Columns("tu.id", "tu.first_name", "tu.last_name", "td.name")
	sel.From("tbl_user AS tu")
	sel.Join("tbl_department AS td", "td.id = tu.department_id")
	sel.Where("tu.id >", 10)
	sel.Where("td.id = 3", nil)
	sel.OrderBy("tu.first_name")
	sel.Limit(10)
	sel.Offset(20)
	query := sel.GetQuery()
	query = standardizeString(query)
	expected := "SELECT tu.id, tu.first_name, tu.last_name, td.name " +
		"FROM tbl_user AS tu " +
		"INNER JOIN tbl_department AS td ON td.id = tu.department_id " +
		"WHERE tu.id > $1 AND td.id = 3 ORDER BY tu.first_name LIMIT 10 OFFSET 20"
	if query != expected {
		t.Errorf("Expected: %s\nFound: %s\n", expected, query)
	}
	params := sel.GetParams()
	if len(params) != 1 {
		t.Errorf("Param count: expected(1), found(%d)", len(params))
	}
}

func TestSQSelect(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"*"},
		nil,
		"",
		0,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT * FROM tbl_user"
	if query != expected {
		t.Errorf("SQSelect. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 0 {
		t.Errorf("SQSelect. Param count: expected(0), found(%d)", len(params))
	}
}

func TestSQSelectWhere1(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"*"},
		map[string]interface{}{"id": 10},
		"",
		0,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT * FROM tbl_user WHERE id = $1"
	if query != expected {
		t.Errorf("SQSelectWhere1. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 1 {
		t.Errorf("SQSelectWhere1. Param count: expected(1), found(%d)", len(params))
	}
}

func TestSQSelectWhere2(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"id", "first_name", "last_name"},
		map[string]interface{}{"country": 10, "state": 20},
		"",
		0,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected1 := "SELECT id, first_name, last_name FROM tbl_user WHERE country = $1 AND state = $2"
	expected2 := "SELECT id, first_name, last_name FROM tbl_user WHERE state = $1 AND country = $2"
	// map is not ordered, so country or state might appear first in the WHERE clause
	if query != expected1 && query != expected2 {
		t.Errorf("SQSelectWhere2. Expected ('%v' OR '%v'), found('%v')", expected1, expected2, query)
	}
	if len(params) != 2 {
		t.Errorf("SQSelectWhere2. Param count: expected(2), found(%d)", len(params))
	}
}

func TestSQSelectWhereOrder(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"id", "first_name", "last_name"},
		map[string]interface{}{"country": 10},
		"first_name",
		0,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT id, first_name, last_name FROM tbl_user WHERE country = $1 ORDER BY first_name"
	if query != expected {
		t.Errorf("SQSelectWhereOrder. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 1 {
		t.Errorf("SQSelectWhereOrder. Param count: expected(1), found(%d)", len(params))
	}
}

func TestSQSelectWhereOrderLimit(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"*"},
		map[string]interface{}{"country": 10, "state": 12},
		"first_name",
		10,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected1 := "SELECT * FROM tbl_user WHERE country = $1 AND state = $2 ORDER BY first_name LIMIT 10"
	expected2 := "SELECT * FROM tbl_user WHERE state = $1 AND country = $2 ORDER BY first_name LIMIT 10"
	// map is not ordered, so country or state might appear first in the WHERE clause
	if query != expected1 && query != expected2 {
		t.Errorf("SQSelectWhereOrderLimit. Expected ('%v' or '%v'), found(%v)", expected1, expected2, query)
	}
	if len(params) != 2 {
		t.Errorf("SQSelectWhereOrderLimit. Param count: expected(2), found(%d)", len(params))
	}
}

func TestSQSelectWhereOrderLimitOffset(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"*"},
		map[string]interface{}{"state": 10, "country": 12},
		"first_name",
		10,
		20,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected1 := "SELECT * FROM tbl_user WHERE country = $1 AND state = $2 ORDER BY first_name LIMIT 10 OFFSET 20"
	expected2 := "SELECT * FROM tbl_user WHERE state = $1 AND country = $2 ORDER BY first_name LIMIT 10 OFFSET 20"
	if query != expected1 && query != expected2 {
		t.Errorf("SQSelectWhereOrderLimitOffset. Expected ('%v' or '%v'), found(%v)", expected1, expected2, query)
	}
	if len(params) != 2 {
		t.Errorf("SQSelectWhereOrderLimitOffset. Param count: expected(2), found(%d)", len(params))
	}
}

func TestSQSelectOrder(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"*"},
		nil,
		"first_name",
		0,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT * FROM tbl_user ORDER BY first_name"
	if query != expected {
		t.Errorf("SQSelectOrder. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 0 {
		t.Errorf("SQSelectOrder. Param count: expected(0), found(%d)", len(params))
	}
}

func TestSQSelectOrderLimit(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"id", "name", "city", "state", "country"},
		nil,
		"name",
		20,
		0,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT id, name, city, state, country FROM tbl_user ORDER BY name LIMIT 20"
	if query != expected {
		t.Errorf("SQSelectOrderLimit. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 0 {
		t.Errorf("SQSelectOrderLimit. Param count: expected(0), found(%d)", len(params))
	}
}

func TestSQSelectOrderLimitOffset(t *testing.T) {
	sq := SelectQuery{
		"tbl_user",
		[]string{"id", "name", "city", "state", "country"},
		nil,
		"name",
		20,
		100,
	}
	query, params := dao.buildSelectQuery(sq)
	query = standardizeString(query)
	expected := "SELECT id, name, city, state, country FROM tbl_user ORDER BY name LIMIT 20 OFFSET 100"
	if query != expected {
		t.Errorf("SQSelectOrderLimitOffset. Expected (%v), found(%v)", expected, query)
	}
	if len(params) != 0 {
		t.Errorf("SQSelectOrderLimitOffset. Param count: expected(0), found(%d)", len(params))
	}
}

func standardizeString(str string) string {
	str = strings.TrimSpace(str)
	parts := strings.Fields(str)
	return strings.Join(parts, " ")
}

repository: sri-soham/nakshadb-server

repo_name: sri-soham/nakshadb-server


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: model.proto

#ifndef GOOGLE_PROTOBUF_INCLUDED_model_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_model_2eproto

#include <limits>
#include <string>

#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>  // IWYU pragma: export
#include <google/protobuf/extension_set.h>  // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_model_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
}  // namespace internal
PROTOBUF_NAMESPACE_CLOSE

// Internal implementation detail -- do not use these members.
struct TableStruct_model_2eproto {
  static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
    PROTOBUF_SECTION_VARIABLE(protodesc_cold);
  static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
    PROTOBUF_SECTION_VARIABLE(protodesc_cold);
  static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
    PROTOBUF_SECTION_VARIABLE(protodesc_cold);
  static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
  static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
  static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_model_2eproto;
namespace wzbgame {
namespace model {
class Position;
struct PositionDefaultTypeInternal;
extern PositionDefaultTypeInternal _Position_default_instance_;
}  // namespace model
}  // namespace wzbgame
PROTOBUF_NAMESPACE_OPEN
template<> ::wzbgame::model::Position* Arena::CreateMaybeMessage<::wzbgame::model::Position>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace wzbgame {
namespace model {

// ===================================================================

class Position final :
    public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:wzbgame.model.Position) */ {
 public:
  inline Position() : Position(nullptr) {}
  ~Position() override;
  explicit constexpr Position(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);

  Position(const Position& from);
  Position(Position&& from) noexcept
    : Position() {
    *this = ::std::move(from);
  }

  inline Position& operator=(const Position& from) {
    CopyFrom(from);
    return *this;
  }
  inline Position& operator=(Position&& from) noexcept {
    if (this == &from) return *this;
    if (GetOwningArena() == from.GetOwningArena()) {
      InternalSwap(&from);
    } else {
      CopyFrom(from);
    }
    return *this;
  }

  static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
    return GetDescriptor();
  }
  static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
    return default_instance().GetMetadata().descriptor;
  }
  static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
    return default_instance().GetMetadata().reflection;
  }
  static const Position& default_instance() {
    return *internal_default_instance();
  }
  static inline const Position* internal_default_instance() {
    return reinterpret_cast<const Position*>(
               &_Position_default_instance_);
  }
  static constexpr int kIndexInFileMessages =
    0;

  friend void swap(Position& a, Position& b) {
    a.Swap(&b);
  }
  inline void Swap(Position* other) {
    if (other == this) return;
    if (GetOwningArena() == other->GetOwningArena()) {
      InternalSwap(other);
    } else {
      ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
    }
  }
  void UnsafeArenaSwap(Position* other) {
    if (other == this) return;
    GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
    InternalSwap(other);
  }

  // implements Message ----------------------------------------------

  inline Position* New() const final {
    return new Position();
  }

  Position* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
    return CreateMaybeMessage<Position>(arena);
  }
  using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
  void CopyFrom(const Position& from);
  using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
  void MergeFrom(const Position& from);
  private:
  static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
  public:
  PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
  bool IsInitialized() const final;

  size_t ByteSizeLong() const final;
  const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
  ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
      ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
  int GetCachedSize() const final { return _cached_size_.Get(); }

  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const final;
  void InternalSwap(Position* other);
  friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
  static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
    return "wzbgame.model.Position";
  }
  protected:
  explicit Position(::PROTOBUF_NAMESPACE_ID::Arena* arena,
                       bool is_message_owned = false);
  private:
  static void ArenaDtor(void* object);
  inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
  public:

  static const ClassData _class_data_;
  const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;

  ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  enum : int {
    kPointXFieldNumber = 1,
    kPointYFieldNumber = 2,
    kPointZFieldNumber = 3,
  };
  // float point_x = 1;
  void clear_point_x();
  float point_x() const;
  void set_point_x(float value);
  private:
  float _internal_point_x() const;
  void _internal_set_point_x(float value);
  public:

  // float point_y = 2;
  void clear_point_y();
  float point_y() const;
  void set_point_y(float value);
  private:
  float _internal_point_y() const;
  void _internal_set_point_y(float value);
  public:

  // float point_z = 3;
  void clear_point_z();
  float point_z() const;
  void set_point_z(float value);
  private:
  float _internal_point_z() const;
  void _internal_set_point_z(float value);
  public:

  // @@protoc_insertion_point(class_scope:wzbgame.model.Position)
 private:
  class _Internal;

  template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
  typedef void InternalArenaConstructable_;
  typedef void DestructorSkippable_;
  float point_x_;
  float point_y_;
  float point_z_;
  mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
  friend struct ::TableStruct_model_2eproto;
};
// ===================================================================

// ===================================================================

#ifdef __GNUC__
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif  // __GNUC__
// Position

// float point_x = 1;
inline void Position::clear_point_x() {
  point_x_ = 0;
}
inline float Position::_internal_point_x() const {
  return point_x_;
}
inline float Position::point_x() const {
  // @@protoc_insertion_point(field_get:wzbgame.model.Position.point_x)
  return _internal_point_x();
}
inline void Position::_internal_set_point_x(float value) {

  point_x_ = value;
}
inline void Position::set_point_x(float value) {
  _internal_set_point_x(value);
  // @@protoc_insertion_point(field_set:wzbgame.model.Position.point_x)
}

// float point_y = 2;
inline void Position::clear_point_y() {
  point_y_ = 0;
}
inline float Position::_internal_point_y() const {
  return point_y_;
}
inline float Position::point_y() const {
  // @@protoc_insertion_point(field_get:wzbgame.model.Position.point_y)
  return _internal_point_y();
}
inline void Position::_internal_set_point_y(float value) {

  point_y_ = value;
}
inline void Position::set_point_y(float value) {
  _internal_set_point_y(value);
  // @@protoc_insertion_point(field_set:wzbgame.model.Position.point_y)
}

// float point_z = 3;
inline void Position::clear_point_z() {
  point_z_ = 0;
}
inline float Position::_internal_point_z() const {
  return point_z_;
}
inline float Position::point_z() const {
  // @@protoc_insertion_point(field_get:wzbgame.model.Position.point_z)
  return _internal_point_z();
}
inline void Position::_internal_set_point_z(float value) {

  point_z_ = value;
}
inline void Position::set_point_z(float value) {
  _internal_set_point_z(value);
  // @@protoc_insertion_point(field_set:wzbgame.model.Position.point_z)
}

#ifdef __GNUC__
  #pragma GCC diagnostic pop
#endif  // __GNUC__

// @@protoc_insertion_point(namespace_scope)

}  // namespace model
}  // namespace wzbgame

// @@protoc_insertion_point(global_scope)

#include <google/protobuf/port_undef.inc>
#endif  // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_model_2eproto

license: Unlicense

repository: wissunpower/WeizenbierGame

repo_name: wissunpower/WeizenbierGame

gha_license_id: Unlicense

extension: h


text:
// Code generated by protoc-gen-go.
// source: greet.proto
// DO NOT EDIT!

/*
Package unary is a generated protocol buffer package.

It is generated from these files:
	greet.proto

It has these top-level messages:
	Request
	Response
*/
package unary

import (
	"fmt"
	"math"

	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

type Request struct {
	Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
}

func (m *Request) Reset()                    { *m = Request{} }
func (m *Request) String() string            { return proto.CompactTextString(m) }
func (*Request) ProtoMessage()               {}
func (*Request) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

func (m *Request) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

type Response struct {
	Greet string `protobuf:"bytes,1,opt,name=greet" json:"greet,omitempty"`
}

func (m *Response) Reset()                    { *m = Response{} }
func (m *Response) String() string            { return proto.CompactTextString(m) }
func (*Response) ProtoMessage()               {}
func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }

func (m *Response) GetGreet() string {
	if m != nil {
		return m.Greet
	}
	return ""
}

func init() {
	proto.RegisterType((*Request)(nil), "unary.Request")
	proto.RegisterType((*Response)(nil), "unary.Response")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// Client API for Greeter service

type GreeterClient interface {
	Greet(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}

type greeterClient struct {
	cc *grpc.ClientConn
}

func NewGreeterClient(cc *grpc.ClientConn) GreeterClient {
	return &greeterClient{cc}
}

func (c *greeterClient) Greet(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
	out := new(Response)
	err := grpc.Invoke(ctx, "/unary.Greeter/greet", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for Greeter service

type GreeterServer interface {
	Greet(context.Context, *Request) (*Response, error)
}

func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) {
	s.RegisterService(&_Greeter_serviceDesc, srv)
}

func _Greeter_Greet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(Request)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(GreeterServer).Greet(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/unary.Greeter/Greet",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(GreeterServer).Greet(ctx, req.(*Request))
	}
	return interceptor(ctx, in, info, handler)
}

var _Greeter_serviceDesc = grpc.ServiceDesc{
	ServiceName: "unary.Greeter",
	HandlerType: (*GreeterServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "greet",
			Handler:    _Greeter_Greet_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "greet.proto",
}

func init() { proto.RegisterFile("greet.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
	// 126 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0x2f, 0x4a, 0x4d,
	0x2d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2d, 0xcd, 0x4b, 0x2c, 0xaa, 0x54, 0x92,
	0xe5, 0x62, 0x0f, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0x12, 0xe2, 0x62, 0xc9, 0x4b, 0xcc,
	0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x95, 0x14, 0xb8, 0x38, 0x82, 0x52,
	0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x44, 0xb8, 0x58, 0xc1, 0x06, 0x40, 0x15, 0x40, 0x38,
	0x46, 0xc6, 0x5c, 0xec, 0xee, 0x20, 0x46, 0x6a, 0x91, 0x90, 0x06, 0x54, 0x81, 0x10, 0x9f, 0x1e,
	0xd8, 0x70, 0x3d, 0xa8, 0xc9, 0x52, 0xfc, 0x70, 0x3e, 0xc4, 0xa8, 0x24, 0x36, 0xb0, 0x1b, 0x8c,
	0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xb8, 0x6d, 0x30, 0xb0, 0x92, 0x00, 0x00, 0x00,
}

repository: zero-all/go-zero

repo_name: zero-all/go-zero


text:
// Package orm provides `GORM` helpers for the creation, migration and access
// on the project's database
package orm

import (
	log "github.com/fedoratipper/bitkiosk/server/internal/logger"
	"github.com/fedoratipper/bitkiosk/server/internal/orm/migration"
	"time"

	"github.com/fedoratipper/bitkiosk/server/pkg/utils"
	"github.com/jinzhu/gorm"
	//Imports the database dialect of choice
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var autoMigrate, logMode, seedDB bool
var dsn, dialect string

// ORM struct to holds the gorm pointer to db
type ORM struct {
	DB *gorm.DB
}

func init() {
	dialect = utils.MustGet("GORM_DIALECT")
	dsn = utils.MustGet("GORM_CONNECTION_DSN")
	seedDB = utils.MustGetBool("GORM_SEED_DB")
	logMode = utils.MustGetBool("GORM_LOGMODE")
	autoMigrate = utils.MustGetBool("GORM_AUTOMIGRATE")
}

// Factory creates a db connection with the selected dialect and connection string
func Factory() (*ORM, error) {
	db, err := gorm.Open(dialect, dsn)
	if err != nil {
		log.Panic("[ORM] err: ", err)
	}

	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
	db.DB().SetConnMaxLifetime(time.Minute * 10)

	orm := &ORM{
		DB: db,
	}
	// Log every SQL command on dev, @prod: this should be disabled?
	db.LogMode(logMode)
	// Automigrate tables
	if autoMigrate {
		err = migration.ServiceAutoMigration(orm.DB)
	}
	log.Info("[ORM] Database connection initialized.")
	return orm, err
}

func CommitOrRollBackIfError(db *gorm.DB, err error)  {
	if err == nil{
		db = db.Commit()
	} else {
		db = db.Rollback()
	}

	if db.Error != nil {
		log.Error(db.Error)
	}
}

func CommitOrRollBackIfErrorAndCloseSession(db *gorm.DB, err error) {
	CommitOrRollBackIfError(db, err)
	CloseDbConnectionLogIfError(db)
}

func CloseDbConnectionLogIfError(db *gorm.DB) {
	dbCloseErr := db.Close()

	if dbCloseErr != nil {
		log.Error("Unable to close db connection", dbCloseErr.Error())
	}
}

repository: FedoraTipper/Bitkiosk

repo_name: FedoraTipper/Bitkiosk


text:
LICENSE = "Firmware-amd"

FILESEXTRAPATHS_prepend := "${THISDIR}/${BPN}:"

SRC_URI = " \
		file://LICENSE.amd-ucode \
		file://microcode_amd_fam15h.bin \
"

LIC_FILES_CHKSUM = "file://LICENSE.amd-ucode;md5=3c5399dc9148d7f0e1f41e34b69cf14f"

S = "${WORKDIR}"

# Since, no binaries are generated for a specific target,
# inherit allarch to simply populate prebuilt binaries
inherit allarch

do_compile() {
	:
}

do_install() {
	install -v -d ${D}/lib/firmware/amd-ucode/
	install -v -m 0644 ${S}/microcode_amd_fam15h.bin ${D}/lib/firmware/amd-ucode/
}

FILES_${PN} = "/lib/firmware/*"

repository: salerio-gs/meta-baldeagle

repo_name: salerio-gs/meta-baldeagle

branch_name: refs/heads/warrior

gha_language: C


text:
#ifndef GeneratorInterface_LHEInterface_LHEProxy_h
#define GeneratorInterface_LHEInterface_LHEProxy_h

#include <memory>

namespace lhef {

  // forward declarations
  class LHEEvent;
  class LHERunInfo;

  class LHEProxy {
  public:
    typedef unsigned long ProxyID;

    // not allowed and not implemented
    LHEProxy(const LHEProxy &orig) = delete;
    LHEProxy &operator=(const LHEProxy &orig) = delete;

    ~LHEProxy();

    const std::shared_ptr<LHERunInfo> &getRunInfo() const { return runInfo; }
    const std::shared_ptr<LHEEvent> &getEvent() const { return event; }

    std::shared_ptr<LHERunInfo> releaseRunInfo() {
      std::shared_ptr<LHERunInfo> result(runInfo);
      runInfo.reset();
      return result;
    }
    std::shared_ptr<LHEEvent> releaseEvent() {
      std::shared_ptr<LHEEvent> result(event);
      event.reset();
      return result;
    }

    void clearRunInfo() { runInfo.reset(); }
    void clearEvent() { event.reset(); }

    void loadRunInfo(const std::shared_ptr<LHERunInfo> &runInfo) { this->runInfo = runInfo; }
    void loadEvent(const std::shared_ptr<LHEEvent> &event) { this->event = event; }

    ProxyID getID() const { return id; }

    static std::shared_ptr<LHEProxy> create();
    static std::shared_ptr<LHEProxy> find(ProxyID id);

  private:
    LHEProxy(ProxyID id);

    const ProxyID id;

    std::shared_ptr<LHERunInfo> runInfo;
    std::shared_ptr<LHEEvent> event;
  };

}  // namespace lhef

#endif  // GeneratorProxy_LHEInterface_LHEProxy_h

repository: cms-sw/cmssw

repo_name: cms-sw/cmssw


text:
package edf

import (
	. "github.com/smartystreets/goconvey/convey"
	"io/ioutil"
	"os"
	"testing"
)

func TestAllocFixed(t *testing.T) {
	Convey("Creating a non-existent file should succeed", t, func() {
		tempFile, err := ioutil.TempFile(os.TempDir(), "TestFileCreate")
		So(err, ShouldEqual, nil)
		Convey("Mapping the file should succeed", func() {
			mapping, err := edfMap(tempFile, EDF_CREATE)
			So(err, ShouldEqual, nil)
			Convey("Allocation should succeed", func() {
				r, err := mapping.AllocPages(1, 2)
				So(err, ShouldEqual, nil)
				So(r.Start.Byte, ShouldEqual, 4*os.Getpagesize())
				So(r.Start.Segment, ShouldEqual, 0)
				Convey("Unmapping the file should succeed", func() {
					err = mapping.unmap(EDF_UNMAP_SYNC)
					So(err, ShouldEqual, nil)
					Convey("Remapping the file should succeed", func() {
						mapping, err = edfMap(tempFile, EDF_READ_ONLY)
						Convey("Should get the same allocations back", func() {
							rr, err := mapping.getThreadBlocks(2)
							So(err, ShouldEqual, nil)
							So(len(rr), ShouldEqual, 1)
							So(rr[0], ShouldResemble, r)
						})
					})
				})
			})
		})
	})
}

func TestAllocWithExtraContentsBlock(t *testing.T) {
	Convey("Creating a non-existent file should succeed", t, func() {
		tempFile, err := ioutil.TempFile(os.TempDir(), "TestFileCreate")
		So(err, ShouldEqual, nil)
		Convey("Mapping the file should succeed", func() {
			mapping, err := edfMap(tempFile, EDF_CREATE)
			So(err, ShouldEqual, nil)
			Convey("Allocation of 10 pages should succeed", func() {
				allocated := make([]edfRange, 10)
				for i := 0; i < 10; i++ {
					r, err := mapping.AllocPages(1, 2)
					So(err, ShouldEqual, nil)
					allocated[i] = r
				}
				Convey("Unmapping the file should succeed", func() {
					err = mapping.unmap(EDF_UNMAP_SYNC)
					So(err, ShouldEqual, nil)
					Convey("Remapping the file should succeed", func() {
						mapping, err = edfMap(tempFile, EDF_READ_ONLY)
						Convey("Should get the same allocations back", func() {
							rr, err := mapping.getThreadBlocks(2)
							So(err, ShouldEqual, nil)
							So(len(rr), ShouldEqual, 10)
							So(rr, ShouldResemble, allocated)
						})
					})
				})
			})
		})
	})
}

repository: amitkgupta/golearn

repo_name: amitkgupta/golearn