text:
package obcpbft

import (
	"encoding/base64"
	"fmt"
	gp "google/protobuf"
	"os"
	"reflect"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/op/go-logging"

	"github.com/hyperledger/fabric/consensus/obcpbft/events"
	pb "github.com/hyperledger/fabric/protos"
)

func init() {
	logging.SetLevel(logging.DEBUG, "")
}

func TestEnvOverride(t *testing.T) {
	config := loadConfig()

	key := "general.mode"               // for a key that exists
	envName := "CORE_PBFT_GENERAL_MODE" // env override name
	overrideValue := "overide_test"     // value to override default value with

	// test key
	if ok := config.IsSet("general.mode"); !ok {
		t.Fatalf("Cannot test env override because \"%s\" does not seem to be set", key)
	}

	os.Setenv(envName, overrideValue)
	// The override config value will cause other calls to fail unless unset.
	defer func() {
		os.Unsetenv(envName)
	}()

	if ok := config.IsSet("general.mode"); !ok {
		t.Fatalf("Env override in place, and key \"%s\" is not set", key)
	}

	// read key
	configVal := config.GetString("general.mode")
	if configVal != overrideValue {
		t.Fatalf("Env override in place, expected key \"%s\" to be \"%s\" but instead got \"%s\"", key, overrideValue, configVal)
	}

}

func TestMaliciousPrePrepare(t *testing.T) {
	mock := &omniProto{
		broadcastImpl: func(msgPayload []byte) {
			t.Fatalf("Expected to ignore malicious pre-prepare")
		},
	}
	instance := newPbftCore(1, loadConfig(), mock, &inertTimerFactory{})
	defer instance.close()
	instance.replicaCount = 5

	digest1 := "hi there"
	request2 := &Request{Payload: []byte("other"), ReplicaId: uint64(generateBroadcaster(instance.replicaCount))}

	pbftMsg := &Message_PrePrepare{&PrePrepare{
		View:           0,
		SequenceNumber: 1,
		RequestDigest:  digest1,
		Request:        request2,
		ReplicaId:      0,
	}}
	events.SendEvent(instance, pbftMsg)
}

func TestWrongReplicaID(t *testing.T) {
	mock := &omniProto{
		validateImpl: func(msg []byte) error {
			return nil
		},
	}
	instance := newPbftCore(1, loadConfig(), mock, &inertTimerFactory{})

	chainTxMsg := createOcMsgWithChainTx(1)
	req := &Request{
		Timestamp: chainTxMsg.Timestamp,
		Payload:   chainTxMsg.Payload,
		ReplicaId: 1,
	}
	pbftMsg := &Message{&Message_Request{req}}
	next, err := instance.recvMsg(pbftMsg, 0)

	if next != nil || err == nil {
		t.Fatalf("Shouldn't have processed message with incorrect replica ID")
	}

	if err != nil {
		rightError := strings.HasPrefix(err.Error(), "Sender ID")
		if !rightError {
			t.Fatalf("Should have returned error about incorrect replica ID on the incoming message")
		}
	}
}

func TestIncompletePayload(t *testing.T) {
	mock := &omniProto{
		validateImpl: func(msg []byte) error {
			return nil
		},
	}
	instance := newPbftCore(1, loadConfig(), mock, &inertTimerFactory{})
	defer instance.close()
	instance.replicaCount = 5

	broadcaster := uint64(generateBroadcaster(instance.replicaCount))

	checkMsg := func(msg *Message, errMsg string, args ...interface{}) {
		mock.broadcastImpl = func(msgPayload []byte) {
			t.Errorf(errMsg, args...)
		}
		events.SendEvent(instance, pbftMessageEvent{msg: msg, sender: broadcaster})
	}

	checkMsg(&Message{}, "Expected to reject empty message")
	checkMsg(&Message{&Message_Request{&Request{ReplicaId: broadcaster}}}, "Expected to reject empty request")
	checkMsg(&Message{&Message_PrePrepare{&PrePrepare{ReplicaId: broadcaster}}}, "Expected to reject empty pre-prepare")
}

func TestNetwork(t *testing.T) {
	validatorCount := 7
	net := makePBFTNetwork(validatorCount, nil)

	msg := createPbftRequestWithChainTx(1, uint64(generateBroadcaster(validatorCount)))
	net.pbftEndpoints[0].manager.Queue() <- msg

	err := net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions <= 0 {
			t.Errorf("Instance %d did not execute transaction", pep.id)
			continue
		}
		if pep.sc.executions != 1 {
			t.Errorf("Instance %d executed more than one transaction", pep.id)
			continue
		}
		if !reflect.DeepEqual(pep.sc.lastExecution, msg.Payload) {
			t.Errorf("Instance %d executed wrong transaction, %x should be %x",
				pep.id, pep.sc.lastExecution, msg.Payload)
		}
	}
}

type checkpointConsumer struct {
	simpleConsumer
	execWait *sync.WaitGroup
}

func (cc *checkpointConsumer) execute(seqNo uint64, tx []byte) {
}

func TestCheckpoint(t *testing.T) {
	execWait := &sync.WaitGroup{}
	finishWait := &sync.WaitGroup{}

	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	execReq := func(iter int64) {
		txTime := &gp.Timestamp{Seconds: iter, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, err := proto.Marshal(tx)
		if err != nil {
			t.Fatalf("Failed to marshal TX block: %s", err)
		}
		msg := &Message{&Message_Request{&Request{Payload: txPacked, ReplicaId: uint64(generateBroadcaster(validatorCount))}}}
		net.pbftEndpoints[0].manager.Queue() <- pbftMessageEvent{msg: msg, sender: msg.GetRequest().ReplicaId}

		net.process()
	}

	// execWait is 0, and execute will proceed
	execReq(1)
	execReq(2)
	finishWait.Wait()
	net.process()

	for _, pep := range net.pbftEndpoints {
		if len(pep.pbft.chkpts) != 1 {
			t.Errorf("Expected 1 checkpoint, found %d", len(pep.pbft.chkpts))
			continue
		}

		if _, ok := pep.pbft.chkpts[2]; !ok {
			t.Errorf("Expected checkpoint for seqNo 2")
			continue
		}

		if pep.pbft.h != 2 {
			t.Errorf("Expected low water mark to be 2, got %d", pep.pbft.h)
			continue
		}
	}

	// this will block executes for now
	execWait.Add(1)
	execReq(3)
	execReq(4)
	execReq(5)
	execReq(6)

	// by now the requests should have committed, but not yet executed
	// we also reached the high water mark by now.

	execReq(7)

	// request 7 should not have committed, because no more free seqNo
	// could be assigned.

	// unblock executes.
	execWait.Add(-1)

	net.process()
	finishWait.Wait() // Decoupling the execution thread makes this nastiness necessary
	net.process()

	// by now request 7 should have been confirmed and executed

	for _, pep := range net.pbftEndpoints {
		expectedExecutions := uint64(7)
		if pep.sc.executions != expectedExecutions {
			t.Errorf("Should have executed %d, got %d instead for replica %d", expectedExecutions, pep.sc.executions, pep.id)
		}
	}
}

func TestLostPrePrepare(t *testing.T) {
	validatorCount := 4
	net := makePBFTNetwork(validatorCount, nil)
	defer net.stop()

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)

	req := &Request{
		Timestamp: &gp.Timestamp{Seconds: 1, Nanos: 0},
		Payload:   txPacked,
		ReplicaId: uint64(generateBroadcaster(validatorCount)),
	}

	net.pbftEndpoints[0].manager.Queue() <- (req)

	// clear all messages sent by primary
	msg := <-net.msgs
	prePrep := &Message{}
	err := proto.Unmarshal(msg.msg, prePrep)
	if err != nil {
		t.Fatalf("Error unmarshaling message")
	}
	net.clearMessages()

	// deliver pre-prepare to subset of replicas
	for _, pep := range net.pbftEndpoints[1 : len(net.pbftEndpoints)-1] {
		pep.manager.Queue() <- prePrep.GetPrePrepare()
	}

	err = net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, pep := range net.pbftEndpoints {
		if pep.id != 3 && pep.sc.executions != 1 {
			t.Errorf("Expected execution on replica %d", pep.id)
			continue
		}
		if pep.id == 3 && pep.sc.executions > 0 {
			t.Errorf("Expected no execution")
			continue
		}
	}
}

func TestInconsistentPrePrepare(t *testing.T) {
	validatorCount := 4
	net := makePBFTNetwork(validatorCount, nil)
	defer net.stop()

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)

	makePP := func(iter int64) *PrePrepare {
		req := &Request{
			Timestamp: &gp.Timestamp{Seconds: iter, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: uint64(generateBroadcaster(validatorCount)),
		}
		preprep := &PrePrepare{
			View:           0,
			SequenceNumber: 1,
			RequestDigest:  hashReq(req),
			Request:        req,
			ReplicaId:      0,
		}
		return preprep
	}

	net.pbftEndpoints[0].manager.Queue() <- makePP(1).Request

	// clear all messages sent by primary
	net.clearMessages()

	// replace with fake messages
	net.pbftEndpoints[1].manager.Queue() <- makePP(1)
	net.pbftEndpoints[2].manager.Queue() <- makePP(2)
	net.pbftEndpoints[3].manager.Queue() <- makePP(3)

	net.process()

	for n, pep := range net.pbftEndpoints {
		if pep.sc.executions < 1 || pep.sc.executions > 3 {
			t.Errorf("Replica %d expected [1,3] executions, got %d", n, pep.sc.executions)
			continue
		}
	}
}

// This test is designed to detect a conflation of S and S' from the paper in the view change
func TestViewChangeWatermarksMovement(t *testing.T) {
	instance := newPbftCore(0, loadConfig(), &omniProto{
		viewChangeImpl: func(v uint64) {},
		skipToImpl: func(s uint64, id []byte, replicas []uint64) {
			t.Fatalf("Should not have attempted to initiate state transfer")
		},
		broadcastImpl: func(b []byte) {},
	}, &inertTimerFactory{})
	instance.activeView = false
	instance.view = 1
	instance.lastExec = 10

	vset := make([]*ViewChange, 3)

	// Replica 0 sent checkpoints for 10
	vset[0] = &ViewChange{
		H: 5,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 10,
				Id:             "ten",
			},
		},
	}

	// Replica 1 sent checkpoints for 10
	vset[1] = &ViewChange{
		H: 5,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 10,
				Id:             "ten",
			},
		},
	}

	// Replica 2 sent checkpoints for 10
	vset[2] = &ViewChange{
		H: 5,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 10,
				Id:             "ten",
			},
		},
	}

	xset := make(map[uint64]string)
	xset[11] = ""

	instance.newViewStore[1] = &NewView{
		View:      1,
		Vset:      vset,
		Xset:      xset,
		ReplicaId: 1,
	}

	if _, ok := instance.processNewView().(viewChangedEvent); !ok {
		t.Fatalf("Failed to successfully process new view")
	}

	expected := uint64(10)
	if instance.h != expected {
		t.Fatalf("Expected to move high watermark to %d, but picked %d", expected, instance.h)
	}
}

// This test is designed to detect a conflation of S and S' from the paper in the view change
func TestViewChangeCheckpointSelection(t *testing.T) {
	instance := &pbftCore{
		f:  1,
		N:  4,
		id: 0,
	}

	vset := make([]*ViewChange, 3)

	// Replica 0 sent checkpoints for 5
	vset[0] = &ViewChange{
		H: 5,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 10,
				Id:             "ten",
			},
		},
	}

	// Replica 1 sent checkpoints for 5
	vset[1] = &ViewChange{
		H: 5,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 10,
				Id:             "ten",
			},
		},
	}

	// Replica 2 sent checkpoints for 15
	vset[2] = &ViewChange{
		H: 10,
		Cset: []*ViewChange_C{
			{
				SequenceNumber: 15,
				Id:             "fifteen",
			},
		},
	}

	checkpoint, ok, _ := instance.selectInitialCheckpoint(vset)

	if !ok {
		t.Fatalf("Failed to pick correct a checkpoint for view change")
	}

	expected := uint64(10)
	if checkpoint.SequenceNumber != expected {
		t.Fatalf("Expected to pick checkpoint %d, but picked %d", expected, checkpoint.SequenceNumber)
	}
}

func TestViewChange(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	execReq := func(iter int64) {
		txTime := &gp.Timestamp{Seconds: iter, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, err := proto.Marshal(tx)
		if err != nil {
			t.Fatalf("Failed to marshal TX block: %s", err)
		}
		msg := &Message{&Message_Request{&Request{Payload: txPacked, ReplicaId: uint64(generateBroadcaster(validatorCount))}}}
		net.pbftEndpoints[0].manager.Queue() <- pbftMessageEvent{msg: msg, sender: msg.GetRequest().ReplicaId}
		if err != nil {
			t.Fatalf("Request failed: %s", err)
		}

		err = net.process()
		if err != nil {
			t.Fatalf("Processing failed: %s", err)
		}
	}

	execReq(1)
	execReq(2)
	execReq(3)

	for i := 2; i < len(net.pbftEndpoints); i++ {
		net.pbftEndpoints[i].pbft.sendViewChange()
	}

	err := net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	if net.pbftEndpoints[1].pbft.view != 1 || net.pbftEndpoints[0].pbft.view != 1 {
		t.Fatalf("Replicas did not follow f+1 crowd to trigger view-change")
	}

	cp, ok, _ := net.pbftEndpoints[1].pbft.selectInitialCheckpoint(net.pbftEndpoints[1].pbft.getViewChanges())
	if !ok || cp.SequenceNumber != 2 {
		t.Fatalf("Wrong new initial checkpoint: %+v",
			net.pbftEndpoints[1].pbft.viewChangeStore)
	}

	msgList := net.pbftEndpoints[1].pbft.assignSequenceNumbers(net.pbftEndpoints[1].pbft.getViewChanges(), cp.SequenceNumber)
	if msgList[4] != "" || msgList[5] != "" || msgList[3] == "" {
		t.Fatalf("Wrong message list: %+v", msgList)
	}
}

func TestInconsistentDataViewChange(t *testing.T) {
	validatorCount := 4
	net := makePBFTNetwork(validatorCount, nil)
	defer net.stop()

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)

	makePP := func(iter int64) *PrePrepare {
		req := &Request{
			Timestamp: &gp.Timestamp{Seconds: iter, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: uint64(generateBroadcaster(validatorCount)),
		}
		preprep := &PrePrepare{
			View:           0,
			SequenceNumber: 1,
			RequestDigest:  hashReq(req),
			Request:        req,
			ReplicaId:      0,
		}
		return preprep
	}

	net.pbftEndpoints[0].manager.Queue() <- makePP(0).Request

	// clear all messages sent by primary
	net.clearMessages()

	// replace with fake messages
	net.pbftEndpoints[1].manager.Queue() <- makePP(1)
	net.pbftEndpoints[2].manager.Queue() <- makePP(1)
	net.pbftEndpoints[3].manager.Queue() <- makePP(0)

	err := net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions < 1 {
			t.Errorf("Expected execution")
			continue
		}
	}
}

func TestViewChangeWithStateTransfer(t *testing.T) {
	validatorCount := 4
	net := makePBFTNetwork(validatorCount, nil)
	defer net.stop()

	var err error

	for _, pep := range net.pbftEndpoints {
		pep.pbft.K = 2
		pep.pbft.L = 6
		pep.pbft.requestTimeout = 500 * time.Millisecond
	}

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)

	broadcaster := uint64(generateBroadcaster(validatorCount))

	makePP := func(iter int64) *PrePrepare {
		req := &Request{
			Timestamp: &gp.Timestamp{Seconds: iter, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: broadcaster,
		}
		preprep := &PrePrepare{
			View:           0,
			SequenceNumber: uint64(iter),
			RequestDigest:  hashReq(req),
			Request:        req,
			ReplicaId:      0,
		}
		return preprep
	}

	// Have primary advance the sequence number past a checkpoint for replicas 0,1,2
	for i := int64(1); i <= 3; i++ {
		net.pbftEndpoints[0].manager.Queue() <- makePP(i).Request

		// clear all messages sent by primary
		net.clearMessages()

		net.pbftEndpoints[0].manager.Queue() <- makePP(i)
		net.pbftEndpoints[1].manager.Queue() <- makePP(i)
		net.pbftEndpoints[2].manager.Queue() <- makePP(i)

		err = net.process()
		if err != nil {
			t.Fatalf("Processing failed: %s", err)
		}

	}

	fmt.Println("Done with stage 1")

	// Add to replica 3's complaint, cause a view change
	net.pbftEndpoints[1].pbft.sendViewChange()
	net.pbftEndpoints[2].pbft.sendViewChange()
	err = net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	fmt.Println("Done with stage 3")

	net.pbftEndpoints[1].manager.Queue() <- makePP(5).Request
	err = net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 4 {
			t.Errorf("Replica %d expected execution through seqNo 5 with one null exec, got %d executions", pep.pbft.id, pep.sc.executions)
			continue
		}
	}
	fmt.Println("Done with stage 3")
}

func TestNewViewTimeout(t *testing.T) {
	millisUntilTimeout := time.Duration(800)

	validatorCount := 4
	config := loadConfig()
	config.Set("general.timeout.request", "400ms")
	config.Set("general.timeout.viewchange", "800ms")
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	replica1Disabled := false
	net.filterFn = func(src int, dst int, msg []byte) []byte {
		if dst == -1 && src == 1 && replica1Disabled {
			return nil
		}
		return msg
	}

	broadcaster := uint64(generateBroadcaster(validatorCount))

	req := createPbftRequestWithChainTx(1, broadcaster)

	go net.processContinually()

	// This will eventually trigger 1's request timeout
	// We check that one single timed out replica will not keep trying to change views by itself
	net.pbftEndpoints[1].manager.Queue() <- req
	fmt.Println("Debug: Sleeping 1")
	time.Sleep(5 * millisUntilTimeout * time.Millisecond)
	fmt.Println("Debug: Waking 1")

	// This will eventually trigger 3's request timeout, which will lead to a view change to 1.
	// However, we disable 1, which will disable the new-view going through.
	// This checks that replicas will automatically move to view 2 when the view change times out.
	// However, 2 does not know about the missing request, and therefore the request will not be
	// pre-prepared and finally executed.
	replica1Disabled = true
	net.pbftEndpoints[3].manager.Queue() <- req
	fmt.Println("Debug: Sleeping 2")
	time.Sleep(5 * millisUntilTimeout * time.Millisecond)
	fmt.Println("Debug: Waking 2")

	// So far, we are in view 2, and replica 1 and 3 (who got the request) in view change to view 3.
	// Submitting the request to 0 will eventually trigger its view-change timeout, which will make
	// all replicas move to view 3 and finally process the request.
	net.pbftEndpoints[0].manager.Queue() <- req
	fmt.Println("Debug: Sleeping 3")
	time.Sleep(5 * millisUntilTimeout * time.Millisecond)
	fmt.Println("Debug: Waking 3")

	for i, pep := range net.pbftEndpoints {
		if pep.pbft.view < 3 {
			t.Errorf("Should have reached view 3, got %d instead for replica %d", pep.pbft.view, i)
		}
		executionsExpected := uint64(1)
		if pep.sc.executions != executionsExpected {
			t.Errorf("Should have executed %d, got %d instead for replica %d", executionsExpected, pep.sc.executions, i)
		}
	}
}

func TestViewChangeUpdateSeqNo(t *testing.T) {
	millisUntilTimeout := 400 * time.Millisecond

	validatorCount := 4
	config.Set("general.timeout.request", "400ms")
	config.Set("general.timeout.viewchange", "400ms")
	net := makePBFTNetwork(validatorCount, config)
	for _, pe := range net.pbftEndpoints {
		pe.pbft.lastExec = 99
		pe.pbft.h = 99 / pe.pbft.K * pe.pbft.K
	}
	net.pbftEndpoints[0].pbft.seqNo = 99

	go net.processContinually()

	broadcaster := uint64(generateBroadcaster(validatorCount))

	req := createPbftRequestWithChainTx(1, broadcaster)
	net.pbftEndpoints[0].manager.Queue() <- req
	time.Sleep(5 * millisUntilTimeout)
	// Now we all have executed seqNo 100.  After triggering a
	// view change, the new primary should pick up right after
	// that.

	net.pbftEndpoints[0].pbft.sendViewChange()
	net.pbftEndpoints[1].pbft.sendViewChange()
	time.Sleep(5 * millisUntilTimeout)

	req = createPbftRequestWithChainTx(2, broadcaster)
	net.pbftEndpoints[1].manager.Queue() <- req
	time.Sleep(5 * millisUntilTimeout)

	net.stop()
	for i, pep := range net.pbftEndpoints {
		if pep.pbft.view < 1 {
			t.Errorf("Should have reached view 3, got %d instead for replica %d", pep.pbft.view, i)
		}
		executionsExpected := uint64(2)
		if pep.sc.executions != executionsExpected {
			t.Errorf("Should have executed %d, got %d instead for replica %d", executionsExpected, pep.sc.executions, i)
		}
	}
}

// Test for issue #1119
func TestSendQueueThrottling(t *testing.T) {
	prePreparesSent := 0

	mock := &omniProto{}
	instance := newPbftCore(0, loadConfig(), mock, &inertTimerFactory{})
	instance.f = 1
	instance.K = 2
	instance.L = 4
	instance.consumer = &omniProto{
		validateImpl: func(p []byte) error { return nil },
		broadcastImpl: func(p []byte) {
			prePreparesSent++
		},
	}
	defer instance.close()

	for j := 0; j < 4; j++ {
		events.SendEvent(instance, &Request{
			Timestamp: &gp.Timestamp{Seconds: int64(j), Nanos: 0},
			Payload:   []byte(fmt.Sprintf("%d", j)),
		})
	}

	expected := 2
	if prePreparesSent != expected {
		t.Fatalf("Expected to send only %d pre-prepares, but got %d messages", expected, prePreparesSent)
	}
}

// Test for issue #1091
// Once the primary ran out of sequence numbers, it would queue requests into a map, and resubmit them in arbitrary order
// This is incorrect, they need to be resubmitted in the order of their timestamps
func TestSendQueueOrdering(t *testing.T) {
	prePreparesSent := 0

	mock := &omniProto{}
	instance := newPbftCore(0, loadConfig(), mock, &inertTimerFactory{})
	instance.f = 1
	instance.K = 2
	instance.L = 100
	lastTime := &gp.Timestamp{Seconds: 0, Nanos: 0}

	instance.consumer = &omniProto{
		validateImpl: func(p []byte) error { return nil },
		broadcastImpl: func(p []byte) {
			msg := &Message{}
			err := proto.Unmarshal(p, msg)
			if err != nil {
				t.Fatalf("Error unmarshaling payload")
				return
			}
			prePrep := msg.GetPrePrepare()
			if prePrep == nil {
				// not a preprepare, ignoring
				return
			}
			req := prePrep.Request
			if lastTime.Seconds > req.Timestamp.Seconds {
				t.Fatalf("Did not arrive in order, got %d after %d", req.Timestamp.Seconds, lastTime.Seconds)
			}
			lastTime = req.Timestamp

			// As each pre-prepare is sent, delete it from the outstanding requests, like it executed
			delete(instance.outstandingReqs, prePrep.RequestDigest)
			prePreparesSent++
		},
	}
	defer instance.close()

	for j := 1; j <= 100; j++ {
		events.SendEvent(instance, &Request{
			Timestamp: &gp.Timestamp{Seconds: int64(j), Nanos: 0},
			Payload:   []byte(fmt.Sprintf("%d", j)),
		})
	}

	instance.moveWatermarks(50)

	expected := 100
	if prePreparesSent != expected {
		t.Fatalf("Expected to send only %d pre-prepares, but got %d messages", expected, prePreparesSent)
	}
}

// From issue #687
func TestWitnessCheckpointOutOfBounds(t *testing.T) {
	mock := &omniProto{}
	instance := newPbftCore(1, loadConfig(), mock, &inertTimerFactory{})
	instance.f = 1
	instance.K = 2
	instance.L = 4
	defer instance.close()

	events.SendEvent(instance, &Checkpoint{
		SequenceNumber: 6,
		ReplicaId:      0,
	})

	instance.moveWatermarks(6)

	// This causes the list of high checkpoints to grow to be f+1
	// even though there are not f+1 checkpoints witnessed outside our range
	// historically, this caused an index out of bounds error
	events.SendEvent(instance, &Checkpoint{
		SequenceNumber: 10,
		ReplicaId:      3,
	})
}

// From issue #687
func TestWitnessFallBehindMissingPrePrepare(t *testing.T) {
	mock := &omniProto{}
	instance := newPbftCore(1, loadConfig(), mock, &inertTimerFactory{})
	instance.f = 1
	instance.K = 2
	instance.L = 4
	defer instance.close()

	events.SendEvent(instance, &Commit{
		SequenceNumber: 2,
		ReplicaId:      0,
	})

	// Historically, the lack of prePrepare associated with the commit would cause
	// a nil pointer reference
	instance.moveWatermarks(6)
}

func TestFallBehind(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	execReq := func(iter int64, skipThree bool) {
		// Create a message of type `Message_CHAIN_TRANSACTION`
		txTime := &gp.Timestamp{Seconds: iter, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, err := proto.Marshal(tx)
		if err != nil {
			t.Fatalf("Failed to marshal TX block: %s", err)
		}

		msg := &Message{&Message_Request{&Request{Payload: txPacked, ReplicaId: uint64(generateBroadcaster(validatorCount))}}}

		net.pbftEndpoints[0].manager.Queue() <- pbftMessageEvent{msg: msg, sender: msg.GetRequest().ReplicaId}

		if skipThree {
			// Send the request for consensus to everone but replica 3
			net.filterFn = func(src, replica int, msg []byte) []byte {
				if src != -1 && replica == 3 {
					return nil
				}

				return msg
			}
		} else {
			// Send the request for consensus to everone
			net.filterFn = nil
		}
		err = net.process()

		if err != nil {
			t.Fatalf("Processing failed: %s", err)
		}
	}

	pep := net.pbftEndpoints[3]
	pbft := pep.pbft
	// Send enough requests to get to a checkpoint quorum certificate with sequence number L+K
	execReq(1, true)
	for request := int64(2); uint64(request) <= pbft.L+pbft.K; request++ {
		execReq(request, false)
	}

	if !pbft.skipInProgress {
		t.Fatalf("Replica did not detect that it has fallen behind.")
	}

	if len(pbft.chkpts) != 0 {
		t.Fatalf("Expected no checkpoints, found %d", len(pbft.chkpts))
	}

	if pbft.h != pbft.L+pbft.K {
		t.Fatalf("Expected low water mark to be %d, got %d", pbft.L+pbft.K, pbft.h)
	}

	// Send enough requests to get to a weak checkpoint certificate certain with sequence number L+K*2
	for request := int64(pbft.L + pbft.K + 1); uint64(request) <= pbft.L+pbft.K*2; request++ {
		execReq(request, false)
	}

	if !pep.sc.skipOccurred {
		t.Fatalf("Request failed to kick off state transfer")
	}

	execReq(int64(pbft.L+pbft.K*2+1), false)

	if pep.sc.executions < pbft.L+pbft.K*2 {
		t.Fatalf("Replica did not perform state transfer")
	}

	// XXX currently disabled, need to resync view# during/after state transfer
	// if pep.sc.executions != pbft.L+pbft.K*2+1 {
	// 	t.Fatalf("Replica did not begin participating normally after state transfer completed")
	//}
}

func TestPbftF0(t *testing.T) {
	net := makePBFTNetwork(1, nil)
	defer net.stop()

	req := createPbftRequestWithChainTx(1, 0)

	pep0 := net.pbftEndpoints[0]

	pep0.manager.Queue() <- req

	err := net.process()
	if err != nil {
		t.Fatalf("Processing failed: %s", err)
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions < 1 {
			t.Errorf("Instance %d did not execute transaction", pep.id)
			continue
		}
		if pep.sc.executions >= 2 {
			t.Errorf("Instance %d executed more than one transaction", pep.id)
			continue
		}
		if !reflect.DeepEqual(pep.sc.lastExecution, req.Payload) {
			t.Errorf("Instance %d executed wrong transaction, %x should be %x",
				pep.id, pep.sc.lastExecution, req.Payload)
		}
	}
}

// Make sure the request timer doesn't inflate the view timeout by firing during view change
func TestRequestTimerDuringViewChange(t *testing.T) {
	mock := &omniProto{
		validateImpl: func(txRaw []byte) error { return nil },
		signImpl:     func(msg []byte) ([]byte, error) { return msg, nil },
		verifyImpl:   func(senderID uint64, signature []byte, message []byte) error { return nil },
		broadcastImpl: func(msg []byte) {
			t.Errorf("Should not send the view change message during a view change")
		},
	}
	instance, manager := createRunningPbftWithManager(1, loadConfig(), mock)
	defer manager.Halt()
	instance.f = 1
	instance.K = 2
	instance.L = 4
	instance.requestTimeout = time.Millisecond
	instance.activeView = false
	defer instance.close()

	txTime := &gp.Timestamp{Seconds: 1, Nanos: 0}
	tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
	txPacked, _ := proto.Marshal(tx)

	req := &Request{
		Timestamp: &gp.Timestamp{Seconds: 1, Nanos: 0},
		Payload:   txPacked,
		ReplicaId: 1, // Not the primary
	}

	manager.Queue() <- req

	time.Sleep(100 * time.Millisecond)
}

// TestReplicaCrash1 simulates the restart of replicas 0 and 1 after
// some state has been built (one request executed).  At the time of
// the restart, replica 0 is also the primary.  All three requests
// submitted should also be executed on all replicas.
func TestReplicaCrash1(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	mkreq := func(n int64) *Request {
		txTime := &gp.Timestamp{Seconds: n, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, _ := proto.Marshal(tx)

		return &Request{
			Timestamp: &gp.Timestamp{Seconds: n, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: uint64(generateBroadcaster(validatorCount)),
		}
	}

	net.pbftEndpoints[0].manager.Queue() <- mkreq(1)
	net.process()

	for id := 0; id < 2; id++ {
		pe := net.pbftEndpoints[id]
		pe.pbft = newPbftCore(uint64(id), loadConfig(), pe.sc, events.NewTimerFactoryImpl(pe.manager))
		pe.manager.SetReceiver(pe.pbft)
		pe.pbft.N = 4
		pe.pbft.f = (4 - 1) / 3
		pe.pbft.K = 2
		pe.pbft.L = 2 * pe.pbft.K
	}

	net.pbftEndpoints[0].manager.Queue() <- mkreq(2)
	net.pbftEndpoints[0].manager.Queue() <- (mkreq(3))
	net.process()

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 3 {
			t.Errorf("Expected 3 executions on replica %d, got %d", pep.id, pep.sc.executions)
			continue
		}

		if pep.pbft.view != 0 {
			t.Errorf("Replica %d should still be in view 0, is %v %d", pep.id, pep.pbft.activeView, pep.pbft.view)
		}
	}
}

// TestReplicaCrash2 is a misnomer.  It simulates a situation where
// one replica (#3) is byzantine and does not participate at all.
// Additionally, for view<2 and seqno=1, the network drops commit
// messages to all but replica 1.
func TestReplicaCrash2(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.timeout.request", "800ms")
	config.Set("general.timeout.viewchange", "800ms")
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	filterMsg := true
	net.filterFn = func(src int, dst int, msg []byte) []byte {
		if dst == 3 { // 3 is byz
			return nil
		}
		pm := &Message{}
		err := proto.Unmarshal(msg, pm)
		if err != nil {
			t.Fatal(err)
		}
		// filter commits to all but 1
		commit := pm.GetCommit()
		if filterMsg && dst != -1 && dst != 1 && commit != nil && commit.View < 2 {
			logger.Infof("filtering commit message from %d to %d", src, dst)
			return nil
		}
		return msg
	}

	mkreq := func(n int64) *Request {
		txTime := &gp.Timestamp{Seconds: n, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, _ := proto.Marshal(tx)

		return &Request{
			Timestamp: &gp.Timestamp{Seconds: n, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: uint64(generateBroadcaster(validatorCount)),
		}
	}

	net.pbftEndpoints[0].manager.Queue() <- (mkreq(1))
	net.process()

	logger.Info("stopping filtering")
	filterMsg = false
	primary := net.pbftEndpoints[0].pbft.primary(net.pbftEndpoints[0].pbft.view)
	net.pbftEndpoints[primary].manager.Queue() <- (mkreq(2))
	net.pbftEndpoints[primary].manager.Queue() <- (mkreq(3))
	net.pbftEndpoints[primary].manager.Queue() <- (mkreq(4))
	go net.processContinually()
	time.Sleep(5 * time.Second)

	for _, pep := range net.pbftEndpoints {
		if pep.id != 3 && pep.sc.executions != 4 {
			t.Errorf("Expected 4 executions on replica %d, got %d", pep.id, pep.sc.executions)
			continue
		}
		if pep.id == 3 && pep.sc.executions > 0 {
			t.Errorf("Expected no execution")
			continue
		}
	}
}

// TestReplicaCrash3 simulates the restart requiring a view change
// to a checkpoint which was restored from the persistence state
// Replicas 0,1,2 participate up to a checkpoint, then all crash
// Then replicas 0,1,3 start back up, and a view change must be
// triggered to get vp3 up to speed
func TestReplicaCrash3(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", 2)
	config.Set("general.logmultiplier", 2)
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	twoOffline := false
	threeOffline := true
	net.filterFn = func(src int, dst int, msg []byte) []byte {
		if twoOffline && dst == 2 { // 2 is 'offline'
			return nil
		}
		if threeOffline && dst == 3 { // 3 is 'offline'
			return nil
		}
		return msg
	}

	mkreq := func(n int64) *Request {
		txTime := &gp.Timestamp{Seconds: n, Nanos: 0}
		tx := &pb.Transaction{Type: pb.Transaction_CHAINCODE_DEPLOY, Timestamp: txTime}
		txPacked, _ := proto.Marshal(tx)

		return &Request{
			Timestamp: &gp.Timestamp{Seconds: n, Nanos: 0},
			Payload:   txPacked,
			ReplicaId: uint64(generateBroadcaster(validatorCount)),
		}
	}

	for i := int64(1); i <= 8; i++ {
		net.pbftEndpoints[0].manager.Queue() <- (mkreq(i))
	}
	net.process() // vp0,1,2 should have a stable checkpoint for seqNo 8

	// Create new pbft instances to restore from persistence
	for id := 0; id < 2; id++ {
		pe := net.pbftEndpoints[id]
		config := loadConfig()
		config.Set("general.K", "2")
		pe.pbft.close()
		pe.pbft = newPbftCore(uint64(id), config, pe.sc, events.NewTimerFactoryImpl(pe.manager))
		pe.manager.SetReceiver(pe.pbft)
		pe.pbft.N = 4
		pe.pbft.f = (4 - 1) / 3
		pe.pbft.requestTimeout = 200 * time.Millisecond
	}

	threeOffline = false
	twoOffline = true

	// Because vp2 is 'offline', and vp3 is still at the genesis block, the network needs to make a view change

	net.pbftEndpoints[0].manager.Queue() <- (mkreq(9))
	net.process()

	// Now vp0,1,3 should be in sync with 9 executions in view 1, and vp2 should be at 8 executions in view 0
	for i, pep := range net.pbftEndpoints {

		if i == 2 {
			// 2 is 'offline'
			if pep.pbft.view != 0 {
				t.Errorf("Expected replica %d to be in view 0, got %d", pep.id, pep.pbft.view)
			}
			expectedExecutions := uint64(8)
			if pep.sc.executions != expectedExecutions {
				t.Errorf("Expected %d executions on replica %d, got %d", expectedExecutions, pep.id, pep.sc.executions)
			}
			continue
		}

		if pep.pbft.view != 1 {
			t.Errorf("Expected replica %d to be in view 1, got %d", pep.id, pep.pbft.view)
		}

		expectedExecutions := uint64(9)
		if pep.sc.executions != expectedExecutions {
			t.Errorf("Expected %d executions on replica %d, got %d", expectedExecutions, pep.id, pep.sc.executions)
		}
	}
}

func TestReplicaPersistQSet(t *testing.T) {
	persist := make(map[string][]byte)

	stack := &omniProto{
		validateImpl: func(b []byte) error {
			return nil
		},
		broadcastImpl: func(msg []byte) {
		},
		StoreStateImpl: func(key string, value []byte) error {
			persist[key] = value
			return nil
		},
		DelStateImpl: func(key string) {
			delete(persist, key)
		},
		ReadStateImpl: func(key string) ([]byte, error) {
			if val, ok := persist[key]; ok {
				return val, nil
			}
			return nil, fmt.Errorf("key not found")
		},
		ReadStateSetImpl: func(prefix string) (map[string][]byte, error) {
			r := make(map[string][]byte)
			for k, v := range persist {
				if len(k) >= len(prefix) && k[0:len(prefix)] == prefix {
					r[k] = v
				}
			}
			return r, nil
		},
	}
	p := newPbftCore(1, loadConfig(), stack, &inertTimerFactory{})
	req := &Request{
		Timestamp: &gp.Timestamp{Seconds: 1, Nanos: 0},
		Payload:   []byte("foo"),
		ReplicaId: uint64(0),
	}
	events.SendEvent(p, &PrePrepare{
		View:           0,
		SequenceNumber: 1,
		RequestDigest:  hashReq(req),
		Request:        req,
		ReplicaId:      uint64(0),
	})
	p.close()

	p = newPbftCore(1, loadConfig(), stack, &inertTimerFactory{})
	if !p.prePrepared(hashReq(req), 0, 1) {
		t.Errorf("did not restore qset properly")
	}
}

func TestReplicaPersistDelete(t *testing.T) {
	persist := make(map[string][]byte)

	stack := &omniProto{
		StoreStateImpl: func(key string, value []byte) error {
			persist[key] = value
			return nil
		},
		DelStateImpl: func(key string) {
			delete(persist, key)
		},
	}
	p := newPbftCore(1, loadConfig(), stack, &inertTimerFactory{})
	p.reqStore["a"] = &Request{}
	p.persistRequest("a")
	if len(persist) != 1 {
		t.Error("expected one persisted entry")
	}
	p.persistDelRequest("a")
	if len(persist) != 0 {
		t.Error("expected no persisted entry")
	}
}

func TestNilCurrentExec(t *testing.T) {
	p := newPbftCore(1, loadConfig(), &omniProto{}, &inertTimerFactory{})
	p.execDoneSync() // Per issue 1538, this would cause a Nil pointer dereference
}

func TestNetworkNullRequests(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.timeout.nullrequest", "200ms")
	config.Set("general.timeout.request", "500ms")
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	msg := createPbftRequestWithChainTx(1, 0)
	net.pbftEndpoints[0].manager.Queue() <- msg

	go net.processContinually()
	time.Sleep(3 * time.Second)

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 1 {
			t.Errorf("Instance %d executed incorrect number of transactions: %d", pep.id, pep.sc.executions)
		}
		if pep.pbft.lastExec <= 1 {
			t.Errorf("Instance %d: no null requests processed", pep.id)
		}
		if pep.pbft.view != 0 {
			t.Errorf("Instance %d: expected view=0", pep.id)
		}
	}
}

func TestNetworkNullRequestMissing(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.timeout.nullrequest", "200ms")
	config.Set("general.timeout.request", "500ms")
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	net.pbftEndpoints[0].pbft.nullRequestTimeout = 0

	msg := createPbftRequestWithChainTx(1, 0)
	net.pbftEndpoints[0].manager.Queue() <- msg

	go net.processContinually()
	time.Sleep(3 * time.Second) // Bumped from 2 to 3 seconds because of sporadic CI failures

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 1 {
			t.Errorf("Instance %d executed incorrect number of transactions: %d", pep.id, pep.sc.executions)
		}
		if pep.pbft.lastExec <= 1 {
			t.Errorf("Instance %d: no null requests processed", pep.id)
		}
		if pep.pbft.view != 1 {
			t.Errorf("Instance %d: expected view=1", pep.id)
		}
	}
}

func TestNetworkPeriodicViewChange(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", "2")
	config.Set("general.logmultiplier", "2")
	config.Set("general.timeout.request", "500ms")
	config.Set("general.viewchangeperiod", "1")
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	for n := 1; n < 6; n++ {
		msg := createPbftRequestWithChainTx(int64(n), 0)
		for _, pe := range net.pbftEndpoints {
			pe.manager.Queue() <- msg
		}
		net.process()
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 5 {
			t.Errorf("Instance %d executed incorrect number of transactions: %d", pep.id, pep.sc.executions)
		}
		// We should be in view 2, 2 exec, VC, 2 exec, VC, exec
		if pep.pbft.view != 2 {
			t.Errorf("Instance %d: expected view=2", pep.id)
		}
	}
}

func TestNetworkPeriodicViewChangeMissing(t *testing.T) {
	validatorCount := 4
	config := loadConfig()
	config.Set("general.K", "2")
	config.Set("general.logmultiplier", "2")
	config.Set("general.timeout.request", "500ms")
	config.Set("general.viewchangeperiod", "1")
	net := makePBFTNetwork(validatorCount, config)
	defer net.stop()

	net.pbftEndpoints[0].pbft.viewChangePeriod = 0
	net.pbftEndpoints[0].pbft.viewChangeSeqNo = ^uint64(0)

	for n := 1; n < 3; n++ {
		msg := createPbftRequestWithChainTx(int64(n), 0)
		for _, pe := range net.pbftEndpoints {
			pe.manager.Queue() <- msg
		}
		net.process()
	}

	for _, pep := range net.pbftEndpoints {
		if pep.sc.executions != 2 {
			t.Errorf("Instance %d executed incorrect number of transactions: %d", pep.id, pep.sc.executions)
		}
		if pep.pbft.view != 1 {
			t.Errorf("Instance %d: expected view=1", pep.id)
		}
	}
}

// TestViewChangeCannotExecuteToCheckpoint tests a replica mid-execution, which receives a view change to a checkpoint above its watermarks
// but does _not_ have enough commit certificates to reach the checkpoint. state should transfer
func TestViewChangeCannotExecuteToCheckpoint(t *testing.T) {
	instance := newPbftCore(3, loadConfig(), &omniProto{
		broadcastImpl:       func(b []byte) {},
		getStateImpl:        func() []byte { return []byte("state") },
		signImpl:            func(b []byte) ([]byte, error) { return b, nil },
		verifyImpl:          func(senderID uint64, signature []byte, message []byte) error { return nil },
		invalidateStateImpl: func() {},
	}, &inertTimerFactory{})
	instance.activeView = false
	instance.view = 1
	newViewBaseSeqNo := uint64(10)
	nextExec := uint64(6)
	instance.currentExec = &nextExec

	for i := instance.lastExec; i < newViewBaseSeqNo; i++ {
		commit := &Commit{View: 0, SequenceNumber: i}
		prepare := &Prepare{View: 0, SequenceNumber: i}
		instance.certStore[msgID{v: 0, n: i}] = &msgCert{
			digest:     "", // null request
			prePrepare: &PrePrepare{View: 0, SequenceNumber: i},
			prepare:    []*Prepare{prepare, prepare, prepare},
			commit:     []*Commit{commit, commit, commit},
		}
	}

	vset := make([]*ViewChange, 3)

	cset := []*ViewChange_C{
		{
			SequenceNumber: newViewBaseSeqNo,
			Id:             base64.StdEncoding.EncodeToString([]byte("Ten")),
		},
	}

	for i := 0; i < 3; i++ {
		// Replica 0 sent checkpoints for 100
		vset[i] = &ViewChange{
			H:    newViewBaseSeqNo,
			Cset: cset,
		}
	}

	xset := make(map[uint64]string)
	xset[11] = ""

	instance.lastExec = 9

	instance.newViewStore[1] = &NewView{
		View:      1,
		Vset:      vset,
		Xset:      xset,
		ReplicaId: 1,
	}

	if _, ok := instance.processNewView().(viewChangedEvent); !ok {
		t.Fatalf("Should have processed the new view")
	}

	if !instance.skipInProgress {
		t.Fatalf("Should have done state transfer")
	}
}

// TestViewChangeCanExecuteToCheckpoint tests a replica mid-execution, which receives a view change to a checkpoint above its watermarks
// but which has enough commit certificates to reach the checkpoint. State should not transfer and executions should trigger the view change
func TestViewChangeCanExecuteToCheckpoint(t *testing.T) {
	instance := newPbftCore(3, loadConfig(), &omniProto{
		broadcastImpl: func(b []byte) {},
		getStateImpl:  func() []byte { return []byte("state") },
		signImpl:      func(b []byte) ([]byte, error) { return b, nil },
		verifyImpl:    func(senderID uint64, signature []byte, message []byte) error { return nil },
		skipToImpl: func(s uint64, id []byte, replicas []uint64) {
			t.Fatalf("Should not have performed state transfer, should have caught up via execution")
		},
	}, &inertTimerFactory{})
	instance.activeView = false
	instance.view = 1
	instance.lastExec = 5
	newViewBaseSeqNo := uint64(10)
	nextExec := uint64(6)
	instance.currentExec = &nextExec

	for i := nextExec + 1; i <= newViewBaseSeqNo; i++ {
		commit := &Commit{View: 0, SequenceNumber: i}
		prepare := &Prepare{View: 0, SequenceNumber: i}
		instance.certStore[msgID{v: 0, n: i}] = &msgCert{
			digest:     "", // null request
			prePrepare: &PrePrepare{View: 0, SequenceNumber: i},
			prepare:    []*Prepare{prepare, prepare, prepare},
			commit:     []*Commit{commit, commit, commit},
		}
	}

	vset := make([]*ViewChange, 3)

	cset := []*ViewChange_C{
		{
			SequenceNumber: newViewBaseSeqNo,
			Id:             base64.StdEncoding.EncodeToString([]byte("Ten")),
		},
	}

	for i := 0; i < 3; i++ {
		// Replica 0 sent checkpoints for 100
		vset[i] = &ViewChange{
			H:    newViewBaseSeqNo,
			Cset: cset,
		}
	}

	xset := make(map[uint64]string)
	xset[11] = ""

	instance.lastExec = 9

	instance.newViewStore[1] = &NewView{
		View:      1,
		Vset:      vset,
		Xset:      xset,
		ReplicaId: 1,
	}

	if instance.processNewView() != nil {
		t.Fatalf("Should not have processed the new view")
	}

	events.SendEvent(instance, execDoneEvent{})

	if !instance.activeView {
		t.Fatalf("Should have finished processing new view after executions")
	}
}

func TestViewWithOldSeqNos(t *testing.T) {
	instance := newPbftCore(3, loadConfig(), &omniProto{
		broadcastImpl: func(b []byte) {},
		signImpl:      func(b []byte) ([]byte, error) { return b, nil },
		verifyImpl:    func(senderID uint64, signature []byte, message []byte) error { return nil },
	}, &inertTimerFactory{})
	instance.activeView = false
	instance.view = 1

	vset := make([]*ViewChange, 3)

	cset := []*ViewChange_C{
		{
			SequenceNumber: 0,
			Id:             base64.StdEncoding.EncodeToString([]byte("Zero")),
		},
	}

	qset := []*ViewChange_PQ{
		{
			SequenceNumber: 9,
			Digest:         "nine",
			View:           0,
		},
		{
			SequenceNumber: 2,
			Digest:         "two",
			View:           0,
		},
	}

	for i := 0; i < 3; i++ {
		// Replica 0 sent checkpoints for 100
		vset[i] = &ViewChange{
			H:    0,
			Cset: cset,
			Qset: qset,
			Pset: qset,
		}
	}

	xset := instance.assignSequenceNumbers(vset, 0)

	instance.lastExec = 10
	instance.moveWatermarks(instance.lastExec)

	instance.newViewStore[1] = &NewView{
		View:      1,
		Vset:      vset,
		Xset:      xset,
		ReplicaId: 1,
	}

	if _, ok := instance.processNewView().(viewChangedEvent); !ok {
		t.Fatalf("Failed to successfully process new view")
	}

	for idx, val := range instance.certStore {
		if idx.n < instance.h {
			t.Errorf("Found %+v=%+v in certStore who's seqNo < %d", idx, val, instance.h)
		}
	}
}

func TestViewChangeDuringExecution(t *testing.T) {
	skipped := false
	instance := newPbftCore(3, loadConfig(), &omniProto{
		viewChangeImpl: func(v uint64) {},
		skipToImpl: func(s uint64, id []byte, replicas []uint64) {
			skipped = true
		},
		invalidateStateImpl: func() {},
		broadcastImpl:       func(b []byte) {},
		signImpl:            func(b []byte) ([]byte, error) { return b, nil },
		verifyImpl:          func(senderID uint64, signature []byte, message []byte) error { return nil },
	}, &inertTimerFactory{})
	instance.activeView = false
	instance.view = 1
	instance.lastExec = 1
	nextExec := uint64(2)
	instance.currentExec = &nextExec

	vset := make([]*ViewChange, 3)

	cset := []*ViewChange_C{
		{
			SequenceNumber: 100,
			Id:             base64.StdEncoding.EncodeToString([]byte("onehundred")),
		},
	}

	// Replica 0 sent checkpoints for 100
	vset[0] = &ViewChange{
		H:    90,
		Cset: cset,
	}

	// Replica 1 sent checkpoints for 10
	vset[1] = &ViewChange{
		H:    90,
		Cset: cset,
	}

	// Replica 2 sent checkpoints for 10
	vset[2] = &ViewChange{
		H:    90,
		Cset: cset,
	}

	xset := make(map[uint64]string)
	xset[101] = ""

	instance.newViewStore[1] = &NewView{
		View:      1,
		Vset:      vset,
		Xset:      xset,
		ReplicaId: 1,
	}

	if _, ok := instance.processNewView().(viewChangedEvent); !ok {
		t.Fatalf("Failed to successfully process new view")
	}

	if skipped {
		t.Fatalf("Expected state transfer not to be kicked off until execution completes")
	}

	events.SendEvent(instance, execDoneEvent{})

	if !skipped {
		t.Fatalf("Expected state transfer to be kicked off once execution completed")
	}
}

func TestStateTransferredToOldPoint(t *testing.T) {
	skipped := false
	instance := newPbftCore(3, loadConfig(), &omniProto{
		skipToImpl: func(s uint64, id []byte, replicas []uint64) {
			skipped = true
		},
		invalidateStateImpl: func() {},
	}, &inertTimerFactory{})
	instance.moveWatermarks(90)
	instance.updateHighStateTarget(&stateUpdateTarget{
		checkpointMessage: checkpointMessage{
			seqNo: 100,
			id:    []byte("onehundred"),
		},
	})

	events.SendEvent(instance, stateUpdatedEvent{
		chkpt: &checkpointMessage{
			seqNo: 10,
		},
	})

	if !skipped {
		t.Fatalf("Expected state transfer to be kicked off once execution completed")
	}
}

func TestStateNetworkMovesOnDuringSlowStateTransfer(t *testing.T) {
	instance := newPbftCore(3, loadConfig(), &omniProto{
		skipToImpl:          func(s uint64, id []byte, replicas []uint64) {},
		invalidateStateImpl: func() {},
		//broadcastImpl:       func(b []byte) {},
		//signImpl:            func(b []byte) ([]byte, error) { return b, nil },
		//verifyImpl:          func(senderID uint64, signature []byte, message []byte) error { return nil },
	}, &inertTimerFactory{})
	instance.skipInProgress = true

	seqNo := uint64(20)

	for i := uint64(0); i < 3; i++ {
		events.SendEvent(instance, &Checkpoint{
			SequenceNumber: seqNo,
			ReplicaId:      i,
			Id:             base64.StdEncoding.EncodeToString([]byte("twenty")),
		})
	}

	if instance.h != seqNo {
		t.Fatalf("Expected watermark movement to %d because of state transfer, but low watermark is %d", seqNo, instance.h)
	}
}

// This test is designed to ensure state transfer occurs if our checkpoint does not match a quorum cert
func TestCheckpointDiffersFromQuorum(t *testing.T) {
	invalidated := false
	skipped := false
	instance := newPbftCore(3, loadConfig(), &omniProto{
		//broadcastImpl:       func(b []byte) { viewChangeSent = true },
		//signImpl:            func(b []byte) ([]byte, error) { return b, nil },
		//verifyImpl:          func(senderID uint64, signature []byte, message []byte) error { return nil },
		invalidateStateImpl: func() { invalidated = true },
		skipToImpl:          func(s uint64, id []byte, replicas []uint64) { skipped = true },
	}, &inertTimerFactory{})

	seqNo := uint64(10)

	badChkpt := &Checkpoint{
		SequenceNumber: 10,
		Id:             base64.StdEncoding.EncodeToString([]byte("WRONG")),
		ReplicaId:      0,
	}
	instance.chkpts[seqNo] = badChkpt.Id // This is done via the exec path, shortcut it here
	events.SendEvent(instance, badChkpt)

	for i := uint64(1); i <= 3; i++ {
		events.SendEvent(instance, &Checkpoint{
			SequenceNumber: 10,
			Id:             base64.StdEncoding.EncodeToString([]byte("CORRECT")),
			ReplicaId:      i,
		})
	}

	if instance.h != 10 {
		t.Fatalf("Replica should have moved its watermarks but did not")
	}

	if !instance.skipInProgress {
		t.Fatalf("Replica should be attempting state transfer")
	}

	if !invalidated || !skipped {
		t.Fatalf("Replica should have invalidated its state and skipped")
	}
}


text:
/**
 * Created by rohitk on 15-Dec-15.
 */

var fs = require('fs');

fs.appendFileSync("../something.json", "some is nonoe");

redpajama_set_name: RedPajamaGithub


text:
package com.ircclouds.irc.api.domain.messages;

import com.ircclouds.irc.api.domain.*;
import com.ircclouds.irc.api.domain.messages.interfaces.*;

/**
 *
 * @author
 *
 */
public class QuitMessage implements IUserMessage
{
	private IRCUser user;
	private String quitMsg;

	public QuitMessage(IRCUser aFromUser, String aQuitMsg)
	{
		user = aFromUser;
		quitMsg = aQuitMsg;
	}

	public IRCUser getSource()
	{
		return user;
	}

	public String getQuitMsg()
	{
		return quitMsg;
	}

	@Override
	public String asRaw()
	{
		return new StringBuffer().append(user).append(" QUIT :").toString();
	}
}


text:
using System;
using System.Collections.Generic;
using ElmahLogAnalyzer.Core.Common;
using ElmahLogAnalyzer.Core.Infrastructure.Settings;
using ElmahLogAnalyzer.Core.Presentation;
using Moq;
using NUnit.Framework;

namespace ElmahLogAnalyzer.UnitTests.Presentation
{
	[TestFixture]
	public class SettingsPresenterTests : UnitTestBase
	{
		private Mock<ISettingsView> _view;
		private Mock<ISettingsManager> _userSettingsManager;

		[SetUp]
		public void Setup()
		{
			_view = new Mock<ISettingsView>();
			_userSettingsManager = new Mock<ISettingsManager>();

			_userSettingsManager.Setup(x => x.GetMaxNumberOfLogs()).Returns(500);
			_userSettingsManager.Setup(x => x.GetDefaultDateInterval()).Returns(DateIntervalSpans.Month);
			_userSettingsManager.Setup(x => x.GetDefaultExportDirectory()).Returns(@"c:\exportedlogs");
			_userSettingsManager.Setup(x => x.GetDefaultLogsDirectory()).Returns(@"c:\mylogs");
			_userSettingsManager.Setup(x => x.GetLoadLogsFromDefaultDirectoryAtStartup()).Returns(true);
		}

		[Test]
		public void Ctor_SetsView()
		{
			// act
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// assert
			Assert.That(presenter.View, Is.EqualTo(_view.Object));
		}

		[Test]
		public void ViewOnLoaded_DisplaysMaxNumberOfLogsOptionsAndUsersSelectedValue()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// act
			_view.Raise(x => x.OnLoaded += null, new EventArgs());

			// assert
			_view.Verify(x => x.LoadMaxNumberOfLogOptions(It.IsAny<List<NameValuePair>>(), "500"), Times.Once());
		}

		[Test]
		public void ViewOnLoaded_DisplaysDefaultDateIntervalOptionsAndUsersSelectedValue()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// act
			_view.Raise(x => x.OnLoaded += null, new EventArgs());

			// assert
			_view.Verify(x => x.LoadDefaultDateIntervalOptions(It.IsAny<IEnumerable<NameValuePair>>(), DateIntervalSpans.Month), Times.Once());
		}

		[Test]
		public void ViewOnLoaded_DisplaysDefaultExportDirectory()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// act
			_view.Raise(x => x.OnLoaded += null, new EventArgs());

			// assert
			_view.VerifySet(x => x.DefaultExportDirectory = @"c:\exportedlogs", Times.Once());
		}

		[Test]
		public void ViewOnLoaded_DisplaysLoadLogsFromDefaultDirectoryAtStartup()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// act
			_view.Raise(x => x.OnLoaded += null, new EventArgs());

			// assert
			_view.VerifySet(x => x.LoadLogsFromDefaultDirectoryAtStartup = true, Times.Once());
		}

		[Test]
		public void ViewOnLoaded_DisplaysDefaultLogsDirectory()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			// act
			_view.Raise(x => x.OnLoaded += null, new EventArgs());

			// assert
			_view.VerifySet(x => x.DefaultLogsDirectory = @"c:\mylogs", Times.Once());
		}

		[Test]
		public void ViewOnSave_SavesMaxNumberOfLogsOption()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			_view.Setup(x => x.MaxNumberOfLogs).Returns(200);

			// act
			_view.Raise(x => x.OnSave += null, new EventArgs());

			// assert
			_userSettingsManager.Verify(x => x.SetMaxNumberOfLogs(200), Times.Once());
		}

		[Test]
		public void ViewOnSave_DefaultDateIntervalOption()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			_view.Setup(x => x.DefaultDateInterval).Returns(DateIntervalSpans.Year);

			// act
			_view.Raise(x => x.OnSave += null, new EventArgs());

			// assert
			_userSettingsManager.Verify(x => x.SetDefaultDateInterval(DateIntervalSpans.Year), Times.Once());
		}

		[Test]
		public void ViewOnSave_SavesDefaultExportDirectory()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			_view.Setup(x => x.DefaultExportDirectory).Returns(@"c:\exportedlogs");

			// act
			_view.Raise(x => x.OnSave += null, new EventArgs());

			// assert
			_userSettingsManager.Verify(x => x.SetDefaultExportDirectory(@"c:\exportedlogs"), Times.Once());
		}

		[Test]
		public void ViewOnSave_SavesDefaultLogsDirectory()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			_view.Setup(x => x.DefaultLogsDirectory).Returns(@"c:\mylogs");

			// act
			_view.Raise(x => x.OnSave += null, new EventArgs());

			// assert
			_userSettingsManager.Verify(x => x.SetDefaultLogsDirectory(@"c:\mylogs"), Times.Once());
		}

		[Test]
		public void ViewOnSave_SavesLoadLogsFromDefaultDirectoryAtStartup()
		{
			// arrange
			var presenter = new SettingsPresenter(_view.Object, _userSettingsManager.Object);

			_view.Setup(x => x.LoadLogsFromDefaultDirectoryAtStartup).Returns(true);

			// act
			_view.Raise(x => x.OnSave += null, new EventArgs());

			// assert
			_userSettingsManager.Verify(x => x.SetLoadLogsFromDefaultDirectoryAtStartup(true), Times.Once());
		}
	}
}


text:
<html>
<body>
This intention adds runtime exception under cursor to the current method throws clause.<br>
</body>
</html>


text:
Option Strict Off
Option Explicit On
<System.Runtime.InteropServices.ProgId("clsWordListPlayer_NET.clsWordListPlayer")> Public Class clsWordListPlayer

	Private bCancel As Boolean

	Public Property Cancel() As Boolean
		Get

			On Error Resume Next
			Cancel = bCancel

		End Get
		Set(ByVal Value As Boolean)

			On Error Resume Next
			bCancel = Value

		End Set
	End Property

	Public Sub Play(ByVal sWavFile As String)

		On Error Resume Next
		bCancel = False
		Call PlayWav(sWavFile)

	End Sub

	'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
	Private Sub Class_Initialize_Renamed()

		On Error Resume Next
		bCancel = False

	End Sub
	Public Sub New()
		MyBase.New()
		Class_Initialize_Renamed()
	End Sub
End Class


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycopath. Mycol. appl. 7: 88 (1954)

#### Original name
Irenina pipturi Hansf.

### Remarks
null


text:
package androidx.wear.widget.drawer;

import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.core.widget.NestedScrollView;
import androidx.core.widget.NestedScrollView.OnScrollChangeListener;
import androidx.wear.widget.drawer.FlingWatcherFactory.FlingListener;
import androidx.wear.widget.drawer.FlingWatcherFactory.FlingWatcher;

import java.lang.ref.WeakReference;

/**
 * {@link FlingWatcher} implementation for {@link NestedScrollView NestedScrollViews}.
 * <p>
 * Because {@link NestedScrollView} does not provide a way to listen to the scroll state, there's no
 * callback which definitely indicates the fling has finished. So, we instead listen for scroll
 * events. If we reach the top or bottom of the view or if there are no events within {@link
 * #MAX_WAIT_TIME_MS}, we assume the fling has finished.
 *
 * @hide
 */
@RestrictTo(Scope.LIBRARY)
class NestedScrollViewFlingWatcher implements FlingWatcher, OnScrollChangeListener {

    static final int MAX_WAIT_TIME_MS = 100;
    private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
    private final FlingListener mListener;
    private final WeakReference<NestedScrollView> mNestedScrollView;
    private final Runnable mNotifyListenerRunnable = new Runnable() {
        @Override
        public void run() {
            onEndOfFlingFound();
        }
    };

    NestedScrollViewFlingWatcher(FlingListener listener, NestedScrollView nestedScrollView) {
        mListener = listener;
        mNestedScrollView = new WeakReference<>(nestedScrollView);
    }

    private static boolean isViewAtTopOrBottom(View view) {
        return !view.canScrollVertically(-1 /* up */) || !view.canScrollVertically(1 /* down */);
    }

    @Override
    public void watch() {
        NestedScrollView nestedScrollView = mNestedScrollView.get();
        if (nestedScrollView != null) {
            nestedScrollView.setOnScrollChangeListener(this);
            scheduleNext();
        }
    }

    @Override
    public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                               int oldScrollY) {
        if (isViewAtTopOrBottom(v)) {
            onEndOfFlingFound();
        } else {
            scheduleNext();
        }
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    void onEndOfFlingFound() {
        mMainThreadHandler.removeCallbacks(mNotifyListenerRunnable);
        NestedScrollView nestedScrollView = mNestedScrollView.get();
        if (nestedScrollView != null) {
            nestedScrollView.setOnScrollChangeListener((OnScrollChangeListener) null);
            mListener.onFlingComplete(nestedScrollView);
        }
    }

    private void scheduleNext() {
        mMainThreadHandler.removeCallbacks(mNotifyListenerRunnable);
        mMainThreadHandler.postDelayed(mNotifyListenerRunnable, MAX_WAIT_TIME_MS);
    }
}


text:
/**
 * @fileoverview
 *
 * @author lvlcek@redhat.com (Lukas Vlcek)
 */

goog.provide('org.jboss.search.page.filter.NewRequestParamsEvent');
goog.provide('org.jboss.search.page.filter.NewRequestParamsEventType');

goog.require('goog.events');
goog.require('goog.events.Event');

/**
 * Filters fire this event whenever client changes selection.
 *
 * @param {string} type
 * @param {!org.jboss.core.context.RequestParams} requestParameters
 * @constructor
 * @extends {goog.events.Event}
 */
org.jboss.search.page.filter.NewRequestParamsEvent = function(type, requestParameters) {
  goog.events.Event.call(this, type);

  /**
   * @type {!org.jboss.core.context.RequestParams}
   * @private
   */
  this.requestParameters_ = requestParameters;
};
goog.inherits(org.jboss.search.page.filter.NewRequestParamsEvent, goog.events.Event);

/**
 * @return {!org.jboss.core.context.RequestParams}
 */
org.jboss.search.page.filter.NewRequestParamsEvent.prototype.getRequestParameters = function() {
  return this.requestParameters_;
};

/**
 *
 * @enum {string}
 */
org.jboss.search.page.filter.NewRequestParamsEventType = {
  NEW_REQUEST_PARAMETERS: goog.events.getUniqueId('new_request_parameters')
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ThriftCompiler">
    <compilers />
  </component>
</project>


text:
package snmp;

import java.io.IOException;
import java.util.List;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
 * TODO close all connection??
 * */
public final class SnmpManager {

    public static void Trap(Address targetAddress, List<VariableBinding> data) throws IOException {
        // 设置 target
        CommunityTarget target = new CommunityTarget();
        target.setAddress(targetAddress);

        // 通信不成功时的重试次数
        target.setRetries(2);
        // 超时时间
        target.setTimeout(1500);
        // snmp版本
        target.setVersion(SnmpConstants.version2c);

        // 创建 PDU
        PDU pdu = new PDU();
        for (VariableBinding d : data) {
            pdu.add(d);
        }
        pdu.setType(PDU.TRAP);

        TransportMapping transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);

        // // 向Agent发送PDU,并接收Response
        // ResponseEvent respEvnt = snmp.send(pdu, target);
        // // 解析Response
        // if (respEvnt != null && respEvnt.getResponse() != null) {
        // for (VariableBinding obj : (Vector<VariableBinding>) respEvnt.getResponse().getVariableBindings()) {
        // System.out.println("Agent: " + obj.getOid() + " : " + obj.getVariable());
        // }
        // }

        snmp.send(pdu, target);
        snmp.close();
    }

    @SuppressWarnings("unchecked")
    public static List<VariableBinding> Get(Address targetAddress, String community, String oid) throws IOException {

        PDU pdu = new PDU();
        pdu.add(new VariableBinding(new OID(oid)));
        pdu.setType(PDU.GET);

        // 创建共同体对象CommunityTarget
        CommunityTarget target = new CommunityTarget();
        target.setCommunity(new OctetString(community));
        target.setAddress(targetAddress);
        // 通信不成功时的重试次数
        target.setRetries(2);
        // 超时时间
        target.setTimeout(1500);
        // snmp版本
        target.setVersion(SnmpConstants.version2c);

        TransportMapping transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        // 向Agent发送PDU,并接收Response
        ResponseEvent respEvnt = snmp.send(pdu, target);
        snmp.close();

        // 解析Response
        if (respEvnt != null && respEvnt.getResponse() != null) {
            return respEvnt.getResponse().getVariableBindings();
        }
        return null;
    }

    // TODO
    // SET
}


text:
package com.tirthal.learning.java2scala.javaway.inheritance;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Test class instance for demo of interface default methods in Java 8
 *
 * @author tirthalp
 * @see Java 8 - default methods in interface
 */
public class InterfaceDefaultMethodSample {

	public static void main(String[] args) {
		Users users = new Users();
		users.add(new User("Tids", 34));
		users.add(new User("Adam", 40));
		users.add(new User("Ian", 4));
		System.out.println("Users sorted by name: " + users.sort());

		users = new UsersSortableByAge();
		users.add(new User("Tids", 34));
		users.add(new User("Adam", 40));
		users.add(new User("Ian", 4));
		System.out.println("Users sorted by age: " + users.sort());
	}
}

// Interface providing default ability of sorting for generic type A to be a sub-type of Comparable in collection
interface Sortable<A extends Comparable> extends Iterable {

	// default sorting implementation, which may be overridden by class implementing this interface
	default public List sort() {
		List list = new ArrayList<>();
		for(A element: this)
			list.add(element);
		list.sort(null); // null indicates to use natural comparison method - User#compareTo()
		return list;
	}
}

// Users class gets default sorting behavior from the default sort() implementation in Sortable interface
class Users implements Sortable<User> { // Here, User class must be sub-type of Comparable

	private final Set<User> users = new HashSet<>();

	public void add(User user) {
		users.add(user);
	}

	@Override
	public Iterator<User> iterator() {
		return users.iterator();
	}
}

class User implements Comparable<User> {

	private String fname;
	private Integer age;

	User(String fname, Integer age) {
		this.fname = fname;
		this.age = age;
	}

	public String getFname() {
		return fname;
	}

	public Integer getAge() {
		return age;
	}

	@Override
	public int compareTo(User u) {
		return fname.compareTo(u.fname); // Keep default natural ordering to sort user by fname
	}

	@Override
	public String toString() {
		return fname + "'s age is " + age;
	}
}

// Another UsersSortableByAge class overrides default sorting behavior of Sortable interface
class UsersSortableByAge extends Users {

	@Override
	public List<User> sort() {
		List<User> users = new ArrayList<>();
		for(User u: this)
			users.add(u);
		users.sort((first, second) -> second.getAge().compareTo(first.getAge()));
		return users;
	}
}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace PhoneCall.ViewModels
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Fires an event when called. Used to update the UI in the MVVM world.
        /// [CallerMemberName] Ensures only the peoperty that calls it gets the event
        /// and not every property
        /// </summary>
        protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Module>
  <ModulePrefs title="Preferences Gadget" description="Tests setting and getting user preferences." width="320" height="400">
  <Require feature="setprefs"/>
  <Require feature="settitle"/>
  <Require feature="dynamic-height"/>
  </ModulePrefs>
  <UserPref name="hello_pref" display_name="Name" default_value="World" datatype="string" required="true"/>
  <UserPref name="number_pref" display_name="Number" default_value="0" datatype="string" required="true"/>
  <UserPref name="list_pref" display_name="List" default_value="foo|bar|foobar" datatype="list" required="true"/>
  <UserPref name="boolean_pref" display_name="Boolean" default_value="false" datatype="bool" required="true"/>
  <UserPref name="enum_pref" display_name="Enum" default_value="Red" datatype="enum" required="true">
    <EnumValue value="Red" display_value="Red"/>
    <EnumValue value="Green" display_value="Green"/>
    <EnumValue value="Blue" display_value="Blue"/>
    <EnumValue value="Gray" display_value="Gray"/>
    <EnumValue value="Purple" display_value="Purple"/>
    <EnumValue value="Black" display_value="Black"/>
  </UserPref>
  <UserPref name="set_pref" display_name="Set this preference" datatype="string" required="false"/>
  <Content type="html">
  <![CDATA[

  <div id="boolean_div"

  <div id="number_div"

  Set the pref value: <input id="setPrefInput" type="text" />

  <button id="setPrefBtn" type="button" onclick="setPref()">Set the pref</button>

  ]]>
  </Content>
</Module>


text:
<?php

use Symfony\Component\Console;
use TwentyFifth\Migrations\Command;

function includeIfExists($file)
{
    if (file_exists($file)) {
        return include $file;
    }
}

if ((!$loader = includeIfExists(__DIR__ . '/../../../autoload.php'))) {
    die('You must set up the project dependencies, run the following commands:' . PHP_EOL .
        'curl -s http://getcomposer.org/installer | php' . PHP_EOL .
        'php composer.phar install' . PHP_EOL);
}

$sqlDirectory = '';

// ZF2
if (is_readable(__DIR__ . '/../config/application.config.php')) {
    chdir(dirname(__DIR__));
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\ZF2Manager(require __DIR__ . '/../config/application.config.php');

    $sqlDirectory = __DIR__ . '/../docs/sql/';
} else if (is_readable(__DIR__ . '/../../../../config/application.config.php')) {
    chdir(dirname(__DIR__) . '/../../../');
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\ZF2Manager(require __DIR__ . '/../../../../config/application.config.php');

    $sqlDirectory = __DIR__ . '/../../../../docs/sql/';

// ZF1
} else if (is_dir(__DIR__ . '/../application/')) {
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\ZF1Manager(__DIR__ . '/../application/');
    $sqlDirectory = __DIR__ . '/../docs/sql/';
} else if (is_dir(__DIR__ . '/../../../../application/')) {
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\ZF1Manager(__DIR__ . '/../../../../application/');
    $sqlDirectory = __DIR__ . '/../../../../docs/sql/';

// Symfony
} else if (is_readable(__DIR__ . '/../app/config/parameters.yml')) {
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\SymfonyManager(__DIR__ . '/../app/config/parameters.yml');
    $sqlDirectory = __DIR__ . '/../sql/';
} else if (is_readable(__DIR__ . '/../../../../app/config/parameters.yml')) {
    $configManager = new \TwentyFifth\Migrations\Manager\ConfigManager\SymfonyManager(__DIR__ . '/../../../../app/config/parameters.yml');
    $sqlDirectory = __DIR__ . '/../../../../sql/';

// UNKNOWN
} else {
    die('Could not set APPLICATION_PATH' . PHP_EOL);
}

$fileManager = new \TwentyFifth\Migrations\Manager\FileManager($sqlDirectory);

$application = new Console\Application('25th Migrations', '0.1.0');

$application->add(new Command\Status($configManager, $fileManager));
$application->add(new Command\Apply($configManager, $fileManager));

$application->run();


text:
package mtr.block;

import mtr.SoundEvents;
import mtr.data.TicketSystem;
import mtr.mappings.Utilities;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;

public class BlockTicketProcessor extends BlockDirectionalDoubleBlockBase {

	public boolean hasLight;
	public boolean canEnter;
	public boolean canExit;

	public static final EnumProperty<EnumTicketProcessorLights> LIGHTS = EnumProperty.create("lights", EnumTicketProcessorLights.class);

	public BlockTicketProcessor(boolean hasLight, boolean canEnter, boolean canExit) {
		super(Properties.of(Material.METAL, MaterialColor.COLOR_GRAY).requiresCorrectToolForDrops().strength(2).lightLevel(state -> 5).noOcclusion());
		this.hasLight = hasLight;
		this.canEnter = canEnter;
		this.canExit = canExit;
	}

	@Override
	public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand interactionHand, BlockHitResult blockHitResult) {
		if (!world.isClientSide && IBlock.getStatePropertySafe(state, HALF) == DoubleBlockHalf.UPPER) {
			final TicketSystem.EnumTicketBarrierOpen open = TicketSystem.passThrough(world, pos, player, canEnter, canExit, SoundEvents.TICKET_PROCESSOR_ENTRY, SoundEvents.TICKET_PROCESSOR_ENTRY_CONCESSIONARY, SoundEvents.TICKET_PROCESSOR_EXIT, SoundEvents.TICKET_PROCESSOR_EXIT_CONCESSIONARY, SoundEvents.TICKET_PROCESSOR_FAIL, true);
			world.setBlockAndUpdate(pos, state.setValue(LIGHTS, open.isOpen() ? EnumTicketProcessorLights.GREEN : EnumTicketProcessorLights.RED));
			Utilities.scheduleBlockTick(world, pos, this, 20);
		}
		return InteractionResult.SUCCESS;
	}

	@Override
	public void tick(BlockState state, ServerLevel world, BlockPos pos) {
		if (hasLight) {
			world.setBlockAndUpdate(pos, state.setValue(LIGHTS, EnumTicketProcessorLights.NONE));
		}
	}

	@Override
	public VoxelShape getShape(BlockState state, BlockGetter blockGetter, BlockPos pos, CollisionContext collisionContext) {
		final Direction facing = IBlock.getStatePropertySafe(state, FACING);
		if (IBlock.getStatePropertySafe(state, HALF) == DoubleBlockHalf.UPPER) {
			return Shapes.or(IBlock.getVoxelShapeByDirection(4.75, 1, 0, 11.25, 13, 8, facing), IBlock.getVoxelShapeByDirection(7, 0, 2, 9, 1, 4, facing));
		} else {
			return Shapes.or(IBlock.getVoxelShapeByDirection(5, 0, 0, 11, 1, 6, facing), IBlock.getVoxelShapeByDirection(7, 1, 2, 9, 16, 4, facing));
		}
	}

	@Override
	protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
		builder.add(FACING, HALF, LIGHTS);
	}

	public enum EnumTicketProcessorLights implements StringRepresentable {

		NONE("none"), RED("red"), YELLOW_GREEN("yellow_green"), GREEN("green");
		private final String name;

		EnumTicketProcessorLights(String nameIn) {
			name = nameIn;
		}

		@Override
		public String getSerializedName() {
			return name;
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>BitvUnit Samples</display-name>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>


text:
/**
 * <p>
 *     Provides Mojo goals for running Apache Solr instance during integration
 *     tests or as a standalone instance for other test purposes.
 * </p>
 */
package com.ffbit.maven.solr;


text:
<sky-link-records-item *ngFor="let record of records | async; trackBy: trackByRecordKey"
  [record]="record"
  [itemTemplate]="itemTemplate"
  [matchTemplate]="matchTemplate"
  [noMatchTemplate]="noMatchTemplate"
  [itemTitleTemplate]="itemTitleTemplate"
  [selectedByDefault]="selectedByDefault"
  [showNewFieldValues]="showNewFieldValues"
></sky-link-records-item>
<ng-content></ng-content>


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="app_name">Kore</string>
    <string name="settings">Configurações</string>
    <string name="action_options">Opções</string>

    <string name="loading">Carregando…</string>

    <string name="navigation_drawer_open">Abrir painel de navegação</string>
    <string name="navigation_drawer_close">Fechar painel de navegação</string>

    <string name="xbmc_media_center">Media Center</string>
    <string name="home">Início</string>
    <string name="movies">Filmes</string>
    <string name="tv_shows">Seriados</string>
    <string name="music">Músicas</string>
    <string name="pictures">Fotos</string>
    <string name="addons">Extensões</string>
    <string name="files">Arquivos</string>
    <string name="video">Vídeo</string>
    <string name="file_browser">Arquivos</string>

    <string name="no_xbmc_configured">Nenhum media center configurado</string>
    <string name="add_xbmc">Adicionar media center</string>

    <string name="xbmc_quit">Media center está sendo fechado.</string>
    <string name="wol_sent">Pedido enviado a seu media center.</string>

    <string name="power">Energia</string>
    <string name="quit">Sair</string>
    <string name="suspend">Suspender</string>
    <string name="reboot">Reiniciar</string>
    <string name="shutdown">Desligar</string>

    <string name="send">Enviar</string>
    <string name="send_text">Enviar texto ao media center</string>
    <string name="text_to_send">Texto a enviar</string>
    <string name="finish_after_send">Terminar após envio</string>

    <string name="library_actions">Manutenção da biblioteca</string>
    <string name="clean_video_library">Limpar biblioteca de vídeo</string>
    <string name="clean_audio_library">Limpar biblioteca de áudio</string>
    <string name="update_video_library">Atualizar biblioteca de vídeo</string>
    <string name="update_audio_library">Atualizar biblioteca de áudio</string>

    <string name="toggle_fullscreen">Alternar tela cheia</string>

    <string name="connected_to">Conectado ao %1$s</string>
    <string name="connecting">Conectando…</string>
    <string name="connecting_to">Conectando-se a %1$s (%2$s)…</string>

    <string name="wizard_welcome">Bem-vindo</string>
    <string name="wizard_welcome_message"><![CDATA[
    Vamos começar adicionado um Media Center. Certifique-se que seu Kodi/XBMC está funcionando, configurado corretamente e na mesma rede do seu dispositivo.

    Você pode obter ajuda na configuração aqui.

    Quando estiver pronto pressione Avançar.
    ]]></string>
    <string name="wizard_search_message"><![CDATA[
    Procurando media centers na sua rede local…

    ]]></string>
    <string name="wizard_search_no_host_found"><![CDATA[
    Não pude encontrar nenhum media center na sua rede.
Se necessita de ajuda na configuração, verifique aqui.

    Pressione Pesquisar para procurar novamente ou Avançar para configuração manual.
    ]]></string>
    <string name="wizard_search_no_network_connection"><![CDATA[
    Por favor conecte-se a uma rede antes de procurar por media centers.

    ]]></string>
    <string name="wizard_search_host_found"><![CDATA[
    Encontrei os seguintes media centers na sua rede.

Selecione um para adicionar ou pressione Avançar para adicionar manualmente um novo.
    ]]></string>
    <string name="no_network_connection">Sem conexão de rede</string>
    <string name="searching">Procurando…</string>
    <string name="no_xbmc_found">Nenhum media center encontrado</string>
    <string name="xbmc_found">Media center encontrado</string>
    <string name="wizard_manual_configuration">Configuração manual</string>
    <string name="wizard_manual_configuration_message">Insira sua configuração do media center:</string>
    <string name="wizard_manual_configuration_message_advanced">Configuração avançada (deixe em branco para padrões)</string>
    <string name="wizard_xbmc_name">Nome do media center</string>
    <string name="wizard_xbmc_ip">Endereço</string>
    <string name="wizard_xbmc_port">Porta</string>
    <string name="wizard_xbmc_username">Usuário</string>
    <string name="wizard_xbmc_password">Senha</string>
    <string name="wizard_xbmc_tcp_port">Porta TCP (9090)</string>
    <string name="wizard_xbmc_mac_address">Endereço MAC</string>
    <string name="wizard_xbmc_wol_port">Porta WoL (9)</string>
    <string name="wizard_xbmc_use_tcp">Usar TCP</string>
    <string name="wizard_xbmc_event_server_port">Porta do ES (9777)</string>
    <string name="wizard_xbmc_use_event_server">Usar EventServer</string>

    <string name="wizard_no_name_specified">Por favor especifique um nome para este media center, para que possa identificá-lo depois.</string>
    <string name="wizard_no_address_specified">Por favor especifique o endereço deste media center, para que eu consiga localizá-lo.</string>
    <string name="wizard_invalid_http_port_specified">Por favor especifique uma porta HTTP válida para este media center.</string>
    <string name="wizard_invalid_tcp_port_specified">Por favor especifique uma porta TCP válida para este media center.</string>
    <string name="wizard_invalid_es_port_specified">Por favor especifique uma porta do EventServer válida para este media center.</string>

    <string name="wizard_connecting_to_xbmc_title">Conectando-se a %1$s…</string>
    <string name="wizard_connecting_to_xbmc_message">Por favor espere enquanto eu tento conectar a seu media center…</string>

    <string name="wizard_empty_authentication">O Kodi/XBMC requer autenticação.\nPor favor especifique seu usuário e senha.</string>
    <string name="wizard_incorrect_authentication">Usuário e/ou senha incorreta.\nPor favor verifique as suas credenciais.</string>
    <string name="wizard_success_connecting">Conectado ao Kodi/XBMC.</string>
    <string name="wizard_error_connecting">Não foi possível conectar ao Kodi/XBMC.\nPor favor verifique a configuração.</string>

    <string name="wizard_done">Pronto!</string>
    <string name="wizard_done_message"><![CDATA[
    Seu media center está configurado.

    Você agora pode usar o controle remoto para controlá-lo. Sua biblioteca está sendo sincronizada e deve estar disponível em alguns momentos.

    Pressione Concluir para começar a usar o controle remoto.
    ]]></string>

    <string name="wizard_zeroconf_no_host_address">Não foi possível descobrir o endereço deste media center.</string>
    <string name="wizard_zeroconf_cant_connect_no_host_address">Não foi possível conectar a este media center porque seu endereço é desconhecido.</string>

    <string name="play">Reproduzir</string>
    <string name="pause">Pausar</string>
    <string name="stop">Parar</string>
    <string name="fast_forward">Avançar</string>
    <string name="rewind">Retroceder</string>

    <string name="repeat">Repetir</string>
    <string name="shuffle">Aleatório</string>
    <string name="volume_up">Aumentar o volume</string>
    <string name="volume_down">Diminuir o volume</string>
    <string name="volume_mute">Mudo</string>
    <string name="subtitles">Legendas</string>
    <string name="audiostreams">Áudio</string>
    <string name="no_audiostream">Nenhuma faixa de áudio disponível</string>
    <string name="download_subtitle">Baixar legendas</string>
    <string name="none">Nenhum</string>
    <string name="audio_sync">Sincronizar áudio</string>
    <string name="subtitle_sync">Sincronizar legendas</string>

    <string name="left">Esquerda</string>
    <string name="right">Direita</string>
    <string name="up">Cima</string>
    <string name="down">Baixo</string>
    <string name="select">Selecionar</string>
    <string name="info">Informações</string>
    <string name="codec_info">Codec</string>
    <string name="context">Contexto</string>
    <string name="osd">Menu</string>
    <string name="back">Voltar</string>

    <string name="previous">Anterior</string>
    <string name="next">Avançar</string>
    <string name="finish">Concluir</string>
    <string name="test_connection">Testar</string>
    <string name="search_again">Procurar</string>

    <string name="remove">Remover</string>
    <string name="edit">Editar</string>
    <string name="wake_up">Acordar</string>
    <string name="edit_xbmc">Editar media center</string>
    <string name="delete_xbmc">Excluir media center</string>
    <string name="delete_xbmc_confirm">Tem certeza que deseja excluir este media center?</string>
    <string name="queue_file">Colocar na fila</string>
    <string name="play_file">Reproduzir</string>
    <string name="play_from_here">Reproduzir a partir daqui</string>

    <string name="connecting_to_xbmc">Conectando…</string>
    <string name="unable_to_connect_to_xbmc">Não foi possível conectar ao media center</string>
    <string name="connected_to_xbmc">Conectado</string>
    <string name="xbmc_available">Disponível</string>
    <string name="xbmc_unavailable">Indisponível</string>

    <string name="nothing_playing">Nada em reprodução</string>

    <string name="now_playing">Em reprodução</string>
    <string name="remote">Controle remoto</string>
    <string name="playlist">Lista de reprodução</string>

    <string name="season_episode_abbrev">s%1$02de%2$02d</string>
    <string name="season_episode">Temporada %1$02d | Episódio %2$02d</string>
    <string name="season_number">Temporada %1$02d</string>
    <string name="episode_number">%1$d</string>

    <string name="votes">%1$s votos</string>

    <string name="fanart">Fanart</string>
    <string name="poster">Poster</string>
    <string name="thumbnail">Miniatura</string>

    <string name="error_getting_properties">Não foi possível obter as propriedades do Kodi/XBMC.\nMensagem de erro:
        %1$s.</string>
    <string name="error_executing_subtitles">Não foi possível executar a extensão de legendas.\nMensagem de erro:
        %1$s.</string>
    <string name="error_getting_addon_info">Não foi possível obter informações da extensão.\nMensagem de erro:
        %1$s.</string>
   <string name="error_getting_source_info">Não foi possível navegar.\nMensagem de erro:
        %1$s.</string>
    <string name="error_play_media_file">Não foi possível reproduzir o arquivo.\nMensagem de erro:
        %1$s.</string>
    <string name="error_queue_media_file">Não foi possível colocar o arquivo na fila.\nMensagem de erro:
        %1$s.</string>
     <string name="error_get_active_player">Nenhum reprodutor ativo.\nMensagem de erro:
        %1$s.</string>

    <string name="directors">Diretores:</string>
    <string name="studio">Estúdio:</string>
    <string name="cast">Elenco</string>
    <string name="additional_cast">Elenco adicional</string>
    <string name="cast_list_text">%1$s como %2$s</string>

    <string name="remaining_cast_count">Mais %d</string>

    <string name="general_error_executing_action">Erro ao executar a ação: %1$s</string>
    <string name="error_getting_playlist">Error ao obter lista de reprodução</string>
    <string name="error_message">Mensagem de erro: %1$s</string>
    <string name="playlist_empty">Lista de reprodução vazia</string>
    <string name="clear_playlist">Limpar lista de reprodução</string>
    <string name="source_empty">Fonte de mídia vazia</string>

    <string name="no_movies_found_refresh">Nenhum filme encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="no_tvshows_found_refresh">Nenhum seriado encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="no_episodes_found">Nenhum episódio encontrado</string>
    <string name="swipe_down_to_refresh">Deslize abaixo para atualizar</string>
    <string name="no_artists_found_refresh">Nenhum artista encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="no_albums_found_refresh">Nenhum álbum encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="no_genres_found_refresh">Nenhum gênero encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="no_addons_found_refresh">Nenhuma extensão encontrada ou não está conectado\n\nDeslize abaixo para atualizar</string>
    <string name="no_music_videos_found_refresh">Nenhum vídeo encontrado\n\nDeslize abaixo para atualizar</string>
    <string name="pull_to_refresh">Puxe para atualizar</string>
    <string name="no_cast_info">Não há informação sobre o elenco</string>

    <string name="minutes_abbrev">%1$s min</string>
    <string name="sync_successful">Sincronização bem-sucedida</string>
    <string name="error_while_syncing">Um erro ocorreu durante a sincronização: %1$s</string>

    <string name="action_search">Pesquisar</string>
    <string name="action_search_movies">Pesquisar filmes</string>
    <string name="action_search_tvshows">Pesquisar seriados</string>
    <string name="action_search_albums">Pesquisar álbuns</string>
    <string name="action_search_artists">Pesquisar artistas</string>
    <string name="action_search_genres">Pesquisar gêneros</string>
    <string name="action_search_music_videos">Pesquisar vídeos</string>

    <string name="add_to_playlist">Adicionar à lista de reprodução</string>
    <string name="item_added_to_playlist">Adicionado à lista de reprodução</string>
    <string name="no_suitable_playlist">Não foi encontrada nenhuma lista de reprodução adequada para este tipo de mídia.</string>

    <string name="imdb">IMDb</string>
    <string name="seen">Visto</string>
    <string name="download">Baixar</string>

    <string name="confirm_movie_download">Tem certeza que quer baixar este filme?\nO download será feito em segundo plano, mas pode demorar para ser concluído.</string>
    <string name="confirm_episode_download">Tem certeza que quer baixar este episódio?\nO download será feito em segundo plano, mas pode demorar para ser concluído.</string>
    <string name="confirm_album_download">Tem certeza que quer baixar este álbum?\nO download será feito em segundo plano, mas pode demorar para ser concluído.</string>

    <string name="download_file_exists">O arquivo já existe.\nDeseja substituí-lo ou baixar com um novo nome?</string>
    <string name="download_dir_exists">Pasta do download já existe.\nSe algum arquivo tiver o mesmo nome, deseja substituir ou baixar com um novo nome?</string>
    <string name="overwrite">Substituir</string>
    <string name="download_with_new_name">Novo nome</string>
    <string name="download_file_description">Baixado do seu media center</string>

    <string name="num_episodes">%1$d episódios  |  %2$d não vistos</string>
    <string name="premiered">Estreia: %1$s</string>

    <string name="tvshow_overview">Resumo</string>
    <string name="tvshow_episodes">Episódios</string>

    <string name="artists">Artistas</string>
    <string name="albums">Álbuns</string>
    <string name="genres">Gêneros</string>
    <string name="music_videos">Vídeos</string>

    <string name="no_files_to_download">Nenhum arquivo para baixar.</string>
    <string name="error_getting_file_information">Não foi possível obter informações para download do arquivo %1$s.</string>

    <string name="author">Autor:</string>
    <string name="version">Versão:</string>
    <string name="enable_disable">Ativar/desativar extensão</string>
    <string name="addon_enabled">Extensão ativada</string>
    <string name="addon_disabled">Extensão desativada</string>

    <string name="hide_watched">Ocultar vistos</string>
    <string name="sort_order">Ordenar</string>
    <string name="sort_by_name">Por nome</string>
    <string name="sort_by_date_added">Por data adicionada</string>
    <string name="ignore_prefixes">Ignorar prefixos</string>

    <string name="theme">Tema</string>
    <string name="theme_night">Noite</string>
    <string name="theme_day">Dia</string>
    <string name="theme_mist">Neblina</string>

    <string name="switch_to_remote">Mudar para o controle remoto ao iniciar reprodução</string>
    <string name="show_notification">Mostrar notificação enquanto estiver em reprodução</string>
    <string name="use_hardware_volume_keys">Usar as teclas de volume para controlar o volume</string>
    <string name="vibrate_on_remote">Vibrar ao pressionar botões</string>

    <string name="about">Sobre</string>
    <string name="about_desc"><![CDATA[
        \u00A9 2018 XBMC Foundation

        Por favor nos avalie no Google Play

        Se precisar de ajuda, visite nosso fórum
    ]]></string>

    <string name="play_on_kodi">Reproduzir no Kodi</string>

</resources>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cercospora septatissima Tracy & Earle

### Remarks
null


text:
```ini
zip:/export/app_servers/meatabase/metabase.jar!/sample-dataset.db;USER=GUEST;PASSWORD=guest
```


text:
import { Component } from '@angular/core';
import { CarouselConfig } from 'ng2-bootstrap';

@Component({
  selector: 'demo-carousel-config',
  templateUrl: './config.html',
  providers: [{provide: CarouselConfig, useValue: {interval: 1500, noPause: true}}]
})
export class DemoCarouselConfigComponent {
}


text:
namespace ExcelDataReader.Core.NumberFormat
{
    internal class Color
    {
        public string Value { get; set; }
    }
}


text:
/**
 * Created by liuzheng on 14-12-8.
 */
function HbaseList($scope, $http, ngTableParams) {
    $http({
        url: "/api/list",
        method: 'GET'
//        headers: {
//            "Authorization": Data.token()
//        },
//        data: {"uid": Data.uid()}
    }).success(function (data) {
        $scope.status = data["status"];//1 true or 0 false
        //Data.token = data["token"];
//        $scope.message = data["message"];
        $scope.data = data['data'];
        if ($scope.status) {
            //仅需要对message中的数据做处理
            $scope.list = $scope.data;
            $scope.weibo = [];
            $scope.tweibo = [];
            $scope.Data = [];
            for ( u in $scope.list['weibo']) {
                $scope.weibo.push({'id': u, 'status': $scope.list['weibo'][u]})
            }
            for (u in $scope.list['tweibo']) {
                $scope.tweibo.push({'id': u, 'status': $scope.list['tweibo'][u]})
            }
            $scope.Data = $scope.weibo;
            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 10           // count per page
            }, {
                total: $scope.Data.length, // length of data
                getData: function ($defer, params) {
                    $defer.resolve($scope.Data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
            });
            $scope.dataswitch = function (target) {
                if (target == 'tweibo') {
                    $scope.Data = $scope.tweibo
                } else {
                    $scope.Data = $scope.weibo
                }
                $scope.tableParams = new ngTableParams({
                    page: 1,            // show first page
                    count: 10           // count per page
                }, {
                    total: $scope.Data.length, // length of data
                    getData: function ($defer, params) {
                        $defer.resolve($scope.Data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    }
                });
            }
        } else {
        }
    }).error(function (data) {
    });
}


text:
namespace SocialToolBox.Core.Web
{
    /// <summary>
    /// A generic web endpoint, generates URLs from arguments.
    /// </summary>
    public interface IWebEndpoint<in T> where T : class
    {
        /// <summary>
        /// Using the arguments, generate an URL.
        /// </summary>
        WebUrl Url(T args);

        /// <summary>
        /// Using the arguments, generate an URL on the same domain, protocol and
        /// port as the provided request.
        /// </summary>
        WebUrl Url(IWebRequest request, T args);

        /// <summary>
        /// Perform a simulated query. Run as when testing.
        /// </summary>
        WebEndpointQuery Query(T args);
    }
}