text:
package engine

import (
	"fmt"
	"sort"
	"testing"

	"github.com/keybase/client/go/libkb"
	keybase1 "github.com/keybase/client/go/protocol/keybase1"
	"github.com/stretchr/testify/require"
)

// testing service block
type sb struct {
	social     bool
	id         string
	proofState keybase1.ProofState
}

func checkTrack(tc libkb.TestContext, fu *FakeUser, username string, blocks []sb, outcome *keybase1.IdentifyOutcome, sigVersion libkb.SigVersion) error {
	ui, them, err := runTrack(tc, fu, username, sigVersion)
	if err != nil {
		return err
	}
	return checkTrackCommon(tc, blocks, outcome, them, ui)
}

func checkTrackForce(tc libkb.TestContext, fu *FakeUser, username string, blocks []sb, outcome *keybase1.IdentifyOutcome) error {
	ui, them, err := runTrackWithOptions(tc, fu, username, keybase1.TrackOptions{BypassConfirm: true}, fu.NewSecretUI(), true)
	if err != nil {
		return err
	}
	return checkTrackCommon(tc, blocks, outcome, them, ui)
}

func checkTrackCommon(tc libkb.TestContext, blocks []sb, outcome *keybase1.IdentifyOutcome, them *libkb.User, ui *FakeIdentifyUI) error {
	me, err := libkb.LoadMe(libkb.NewLoadUserArg(tc.G))
	if err != nil {
		return err
	}
	if them == nil {
		tc.T.Fatal("checkTrackCommon called with nil 'them' user")
	}
	m := NewMetaContextForTest(tc)
	s, err := me.TrackChainLinkFor(m, them.GetNormalizedName(), them.GetUID())
	if err != nil {
		return err
	}

	if s == nil {
		tc.T.Fatal("me.TrackChainLinkFor(...) returned nil, nil")
	} else {
		tc.T.Logf("payload json:\n%s", s.UnmarshalPayloadJSON().MarshalPretty())
	}

	sbs := s.ToServiceBlocks()
	if len(sbs) != len(blocks) {
		return fmt.Errorf("num service blocks: %d, expected %d", len(sbs), len(blocks))
	}
	sort.Sort(byID(sbs))
	for i, sb := range sbs {
		tsb := blocks[i]
		if sb.IsSocial() != tsb.social {
			return fmt.Errorf("(sb %d): social: %v, expected %v", i, sb.IsSocial(), tsb.social)
		}
		if sb.ToIDString() != tsb.id {
			return fmt.Errorf("(sb %d): id: %s, expected %s", i, sb.ToIDString(), tsb.id)
		}
		if sb.GetProofState() != tsb.proofState {
			return fmt.Errorf("(sb %d): proof state: %d, expected %d", i, sb.GetProofState(), tsb.proofState)
		}
	}

	if ui.Outcome.TrackStatus != outcome.TrackStatus {
		return fmt.Errorf("track status: %d, expected %d", ui.Outcome.TrackStatus, outcome.TrackStatus)
	}

	if ui.Outcome.NumTrackFailures != outcome.NumTrackFailures {
		return fmt.Errorf("num track failures: %d, expected %d", ui.Outcome.NumTrackFailures, outcome.NumTrackFailures)
	}
	if ui.Outcome.NumTrackChanges != outcome.NumTrackChanges {
		return fmt.Errorf("num track changes: %d, expected %d", ui.Outcome.NumTrackChanges, outcome.NumTrackChanges)
	}
	if ui.Outcome.NumProofFailures != outcome.NumProofFailures {
		return fmt.Errorf("num proof failures: %d, expected %d", ui.Outcome.NumProofFailures, outcome.NumProofFailures)
	}
	if ui.Outcome.NumProofSuccesses != outcome.NumProofSuccesses {
		return fmt.Errorf("num proof successes: %d, expected %d", ui.Outcome.NumProofSuccesses, outcome.NumProofSuccesses)
	}
	if ui.Outcome.NumRevoked != outcome.NumRevoked {
		return fmt.Errorf("num revoked: %d, expected %d", ui.Outcome.NumRevoked, outcome.NumRevoked)
	}

	return nil
}

type byID []*libkb.ServiceBlock

func (b byID) Len() int           { return len(b) }
func (b byID) Less(x, y int) bool { return b[x].ToIDString() < b[y].ToIDString() }
func (b byID) Swap(x, y int)      { b[x], b[y] = b[y], b[x] }

type sbtest struct {
	name    string
	blocks  []sb
	outcome keybase1.IdentifyOutcome
}

// these aren't that interesting since all the proof states are
// the same, but it does some basic testing of the service blocks
// in a TrackChainLink.
var sbtests = []sbtest{
	{
		name: "t_alice",
		blocks: []sb{
			{social: true, id: "kbtester2@github", proofState: keybase1.ProofState_OK},
			{social: true, id: "tacovontaco@twitter", proofState: keybase1.ProofState_OK},
		},
		outcome: keybase1.IdentifyOutcome{
			NumProofSuccesses: 2,
			TrackStatus:       keybase1.TrackStatus_NEW_OK,
		},
	},
	{
		name: "t_bob",
		blocks: []sb{
			{social: true, id: "kbtester1@github", proofState: keybase1.ProofState_OK},
			{social: true, id: "kbtester1@twitter", proofState: keybase1.ProofState_OK},
		},
		outcome: keybase1.IdentifyOutcome{
			NumProofSuccesses: 2,
			TrackStatus:       keybase1.TrackStatus_NEW_OK,
		},
	},
	{
		name: "t_charlie",
		blocks: []sb{
			{social: true, id: "tacoplusplus@github", proofState: keybase1.ProofState_OK},
			{social: true, id: "tacovontaco@twitter", proofState: keybase1.ProofState_OK},
		},
		outcome: keybase1.IdentifyOutcome{
			NumProofSuccesses: 2,
			TrackStatus:       keybase1.TrackStatus_NEW_OK,
		},
	},
	{
		name: "t_doug",
		outcome: keybase1.IdentifyOutcome{
			TrackStatus: keybase1.TrackStatus_NEW_ZERO_PROOFS,
		},
	},
}

func TestTrackProofServiceBlocks(t *testing.T) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()
	sigVersion := libkb.GetDefaultSigVersion(tc.G)
	fu := CreateAndSignupFakeUser(tc, "track")

	for _, test := range sbtests {
		err := checkTrack(tc, fu, test.name, test.blocks, &test.outcome, sigVersion)
		require.NoError(t, err)
		err = runUntrack(tc, fu, test.name, sigVersion)
		require.NoError(t, err)
	}
}

// track a user that has no proofs
func TestTrackProofZero(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofZero(t, sigVersion)
	})
}

func _testTrackProofZero(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with no proofs
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	outcome := keybase1.IdentifyOutcome{
		TrackStatus: keybase1.TrackStatus_NEW_ZERO_PROOFS,
	}
	err := checkTrack(tc, trackUser, proofUser.Username, nil, &outcome, sigVersion)
	require.NoError(t, err)
}

// track a user that has a rooter proof, check the tracking
// statement for correctness.
func TestTrackProofRooter(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofRooter(t, sigVersion)
	})
}

func _testTrackProofRooter(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, _, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	// retrack, check the track status
	outcome.TrackStatus = keybase1.TrackStatus_UPDATE_OK
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

func TestTrackProofGubble(t *testing.T) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()
	sigVersion := libkb.KeybaseSignatureV2

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	proveGubbleSocial(tc, proofUser, sigVersion)
	proveGubbleCloud(tc, proofUser, sigVersion)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := []sb{
		{
			social:     true,
			id:         proofUser.Username + "@gubble.cloud",
			proofState: keybase1.ProofState_OK,
		},
		{
			social:     true,
			id:         proofUser.Username + "@gubble.social",
			proofState: keybase1.ProofState_OK,
		},
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 2,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err := checkTrack(tc, trackUser, proofUser.Username, rbl, &outcome, sigVersion)
	require.NoError(t, err)

	// retrack, check the track status
	outcome.TrackStatus = keybase1.TrackStatus_UPDATE_OK
	err = checkTrack(tc, trackUser, proofUser.Username, rbl, &outcome, sigVersion)
	require.NoError(t, err)
}

// upgrade tracking statement when new proof is added:
// track a user that has no proofs, then track them again after they add a proof
func TestTrackProofUpgrade(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofUpgrade(t, sigVersion)
	})
}

func _testTrackProofUpgrade(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with no proofs
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")
	outcome := keybase1.IdentifyOutcome{
		TrackStatus: keybase1.TrackStatus_NEW_ZERO_PROOFS,
	}
	err := checkTrack(tc, trackUser, proofUser.Username, nil, &outcome, sigVersion)
	require.NoError(t, err)

	// proofUser adds a rooter proof:
	Logout(tc)
	proofUser.LoginOrBust(tc)
	_, _, err = proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// trackUser tracks proofUser again:
	trackUser.LoginOrBust(tc)

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome = keybase1.IdentifyOutcome{
		NumTrackChanges:   1,
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_UPDATE_NEW_PROOFS,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// test a change to a proof
func TestTrackProofChangeSinceTrack(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofChangeSinceTrack(t, sigVersion)
	})
}

func _testTrackProofChangeSinceTrack(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, _, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	Logout(tc)

	// proof user logs in and does a new rooter proof
	proofUser.LoginOrBust(tc)
	_, _, err = proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// track user logs in and tracks proof user again
	trackUser.LoginOrBust(tc)
	outcome.TrackStatus = keybase1.TrackStatus_UPDATE_OK
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// track a user that has a failed rooter proof
func TestTrackProofRooterFail(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofRooterFail(t, sigVersion)
	})
}

func _testTrackProofRooterFail(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, err := proveRooterFail(tc.G, proofUser, sigVersion)
	require.Error(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	// proveRooterFail posts a bad sig id, so it won't be found.
	// thus the state is ProofState_SIG_HINT_MISSING
	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_SIG_HINT_MISSING,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofFailures: 1,
		TrackStatus:      keybase1.TrackStatus_NEW_ZERO_PROOFS,
	}
	// and they have no proofs
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

func TestTrackProofGubbleFail(t *testing.T) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()
	sigVersion := libkb.KeybaseSignatureV2

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	proveGubbleSocialFail(tc, proofUser, sigVersion)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	// proveGubbleSocialFail posts a bad sig id, so it won't be found.
	// thus the state is ProofState_SIG_HINT_MISSING
	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@gubble.social",
		proofState: keybase1.ProofState_SIG_HINT_MISSING,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofFailures: 1,
		TrackStatus:      keybase1.TrackStatus_NEW_ZERO_PROOFS,
	}
	// and they have no proofs
	err := checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// track a user that has a rooter proof, remove the proof, then
// track again.
// Note that the API server won't notice that the rooter proof has
// been removed as it only checks every 12 hours.  The client will
// notice and should generate an appropriate tracking statement.
func TestTrackProofRooterRemove(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofRooterRemove(t, sigVersion)
	})
}

func _testTrackProofRooterRemove(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	ui, _, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	// remove the rooter proof
	Logout(tc)
	proofUser.LoginOrBust(tc)
	err = proveRooterRemove(tc.G, ui.postID)
	require.NoError(t, err)

	Logout(tc)

	// track again
	trackUser.LoginOrBust(tc)
	rbl.proofState = keybase1.ProofState_TEMP_FAILURE
	outcome = keybase1.IdentifyOutcome{
		NumTrackFailures: 1,
		NumTrackChanges:  1,
		NumProofFailures: 1,
		TrackStatus:      keybase1.TrackStatus_UPDATE_BROKEN_FAILED_PROOFS,
	}
	// use checkTrackForce to skip any proof cache results
	err = checkTrackForce(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome)
	require.NoError(t, err)

	// check that it is "fixed"
	outcome = keybase1.IdentifyOutcome{
		NumProofFailures: 1,
		TrackStatus:      keybase1.TrackStatus_UPDATE_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// test tracking a user who revokes a proof.  Revoking a proof
// removes it from the sig chain, so this tests the
// libkb.IdentifyState.ComputeRevokedProofs() function, and how
// libkb.IdentifyOutcome.TrackStatus() interprets the result.
func TestTrackProofRooterRevoke(t *testing.T) {
	doWithSigChainVersions(func(sigVersion libkb.SigVersion) {
		_testTrackProofRooterRevoke(t, sigVersion)
	})
}

func _testTrackProofRooterRevoke(t *testing.T, sigVersion libkb.SigVersion) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, sigID, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	// revoke the rooter proof
	Logout(tc)
	proofUser.LoginOrBust(tc)
	revEng := NewRevokeSigsEngine(tc.G, []string{sigID.String()})
	uis := libkb.UIs{
		LogUI:    tc.G.UI.GetLogUI(),
		SecretUI: proofUser.NewSecretUI(),
	}
	m := NewMetaContextForTest(tc).WithUIs(uis)

	err = revEng.Run(m)
	require.NoError(t, err)
	Logout(tc)

	// track proofUser again and check revoked proof handled correctly
	trackUser.LoginOrBust(tc)
	outcome = keybase1.IdentifyOutcome{
		NumRevoked:  1,
		TrackStatus: keybase1.TrackStatus_UPDATE_BROKEN_REVOKED,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, nil, &outcome, sigVersion)
	require.NoError(t, err)

	// track again and check for fix
	outcome = keybase1.IdentifyOutcome{
		TrackStatus: keybase1.TrackStatus_UPDATE_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, nil, &outcome, sigVersion)
	require.NoError(t, err)
}

// proofUser makes a user@rooter proof, then a user2@rooter proof.
// trackUser tracks proofUser.  Verify the tracking statement.
func TestTrackProofRooterOther(t *testing.T) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()

	sigVersion := libkb.GetDefaultSigVersion(tc.G)
	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, _, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// post a rooter proof as a different rooter user
	proofUserOther := CreateAndSignupFakeUser(tc, "proof")
	Logout(tc)
	proofUser.LoginOrBust(tc)
	_, _, err = proveRooterOther(tc.G, proofUser, proofUserOther.Username, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUserOther.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// proofUser makes a user@rooter proof, trackUser tracks
// proofUser.  proofUser makes a user2@rooter proof, trackUser
// tracks proofUser again.  Test that the change is noticed.
func TestTrackProofRooterChange(t *testing.T) {
	tc := SetupEngineTest(t, "track")
	defer tc.Cleanup()
	sigVersion := libkb.GetDefaultSigVersion(tc.G)

	// create a user with a rooter proof
	proofUser := CreateAndSignupFakeUser(tc, "proof")
	_, _, err := proveRooter(tc.G, proofUser, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// create a user to track the proofUser
	trackUser := CreateAndSignupFakeUser(tc, "track")

	rbl := sb{
		social:     true,
		id:         proofUser.Username + "@rooter",
		proofState: keybase1.ProofState_OK,
	}
	outcome := keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_NEW_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	// post a rooter proof as a different rooter user
	Logout(tc)
	proofUserOther := CreateAndSignupFakeUser(tc, "proof")
	Logout(tc)

	proofUser.LoginOrBust(tc)
	_, _, err = proveRooterOther(tc.G, proofUser, proofUserOther.Username, sigVersion)
	require.NoError(t, err)
	Logout(tc)

	// track proofUser again and check new rooter proof with different account handled correctly
	trackUser.LoginOrBust(tc)
	rbl.id = proofUserOther.Username + "@rooter"
	outcome = keybase1.IdentifyOutcome{
		NumTrackChanges:   1,
		NumTrackFailures:  1,
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_UPDATE_BROKEN_FAILED_PROOFS,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)

	// track again and check for fix
	outcome = keybase1.IdentifyOutcome{
		NumProofSuccesses: 1,
		TrackStatus:       keybase1.TrackStatus_UPDATE_OK,
	}
	err = checkTrack(tc, trackUser, proofUser.Username, []sb{rbl}, &outcome, sigVersion)
	require.NoError(t, err)
}

// TODO:
// * get a test that will generate TrackStatus_NEW_FAIL_PROOFS
//   (this requires two services, one with an ok proof, one with a
//   failing proof)
// * test upgrade from http to https, or a secure rooter post vs.
//   regular rooter post to get TrackDiffUpgraded.
// * a test that will generate TrackDiffRemoteChanged


text:
<?php
	include('../autoload.php');
    session_start();
    if( isset($_SESSION['userMerlaTrav']) ) {
        if( isset($_GET['idProjet']) ){
           $idProjet = $_GET['idProjet'];
        }
        //destroy contrat-form-data session
        if ( isset($_SESSION['contrat-form-data']) ) {
            unset($_SESSION['contrat-form-data']);
        }
        $projetManager = new ProjetManager($pdo);
        $clientManager = new ClientManager($pdo);
        $contratManager = new ContratManager($pdo);
        $operationManager = new OperationManager($pdo);
        $compteBancaireManager = new CompteBancaireManager($pdo);

        /*$codeContrat = $_GET['codeContrat'];
        $comptesBancaires = $compteBancaireManager->getCompteBancaires();
        $contrat = $contratManager->getContratByCode($codeContrat);

        $projet = $projetManager->getProjetById($contrat->idProjet());
        $client = $clientManager->getClientById($contrat->idClient());
        $sommeOperations = $operationManager->sommeOperations($contrat->id());
        $biens = "";
        $niveau = "";
        if($contrat->typeBien()=="appartement"){
            $appartementManager = new AppartementManager($pdo);
            $biens = $appartementManager->getAppartementById($contrat->idBien());
            $niveau = $biens->niveau();
        }
        else if($contrat->typeBien()=="localCommercial"){
            $locauxManager = new LocauxManager($pdo);
            $biens = $locauxManager->getLocauxById($contrat->idBien());
        }*/
        $mois = $_GET['mois'];
        $annee = $_GET['annee'];
        //$operations = "";
        //test the locaux object number: if exists get operations else do nothing
        //$operationsNumber = $operationManager->getOpertaionsNumberByIdContrat($contrat->id());
        $operations = $operationManager->getOperationsValideesByMonthYear($mois, $annee);
        /*if($operationsNumber != 0){
            $operations = $operationManager->getOperationsByIdContrat($contrat->id());
        }*/
?>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>ImmoERP - Management Application</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />
    <link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/css/metro.css" rel="stylesheet" />
    <link href="../assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
    <link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="../assets/css/style.css" rel="stylesheet" />
    <link href="../assets/css/style_responsive.css" rel="stylesheet" />
    <link href="../assets/css/style_default.css" rel="stylesheet" id="style_color" />
    <link href="../assets/fancybox/source/jquery.fancybox.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="../assets/uniform/css/uniform.default.css" />
    <link rel="stylesheet" type="text/css" href="../assets/bootstrap-datepicker/css/datepicker.css" />
    <link rel="stylesheet" type="text/css" href="../assets/chosen-bootstrap/chosen/chosen.css" />
    <link rel="stylesheet" href="../assets/data-tables/DT_bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../assets/uniform/css/uniform.default.css" />
    <link rel="shortcut icon" href="favicon.ico" />

        <?php include("../include/top-menu.php"); ?>

        <?php include("../include/sidebar.php"); ?>

                            Liste des paiements clients validés

                                Accueil

                                Les états

                                Les états des paiements clients

                                <?= $mois."/".$annee ?>

Liste des paiements clients validés

                                <?php
                                 if( isset($_SESSION['operation-action-message'])
                                 and isset($_SESSION['operation-type-message']) ){
                                    $message = $_SESSION['operation-action-message'];
                                    $typeMessage = $_SESSION['operation-type-message'];
                                 ?>
                                    <div class="alert alert-<?= $typeMessage ?>">
                                        <button class="close" data-dismiss="alert"></button>
                                        <?= $message ?>

                                 <?php
                                 }
                                 unset($_SESSION['operation-action-message']);
                                 unset($_SESSION['operation-type-message']);
                                ?>

                                        Action
                                        Client
                                        Projet
                                        DOpér
                                        DRégl
                                        ModPaimnt
                                        Compte
                                        N°Opé
                                        Montant
                                        Status

                                    <?php
                                    foreach($operations as $operation){
                                        $status = "";
                                        $action = "";
                                        $idContrat = $operation->idContrat();
                                        $contrat = $contratManager->getContratById($idContrat);
                                        $nomProjet = $projetManager->getProjetById($contrat->idProjet())->nom();
                                        $nomClient = $contratManager->getClientNameByIdContract($operation->idContrat());
                                        if ( $operation->status() == 0 ) {
                                            $action = '';
                                            if ( $_SESSION['userMerlaTrav']->profil() == "admin" ) {
                                                $status = 'id().'" data-toggle="modal" data-id="'.$operation->id().'"> Non validé';
                                            }
                                            else{
                                                $status = ' Non validé';
                                            }
                                        }
                                        else {
                                            if ( $_SESSION['userMerlaTrav']->profil() == "admin" ) {
                                                $status = 'id().'" data-toggle="modal" data-id="'.$operation->id().'"> Validé';
                                                $action = 'id().'" data-toggle="modal" data-id="'.$operation->id().'">';
                                            }
                                            else {
                                                $status = ' Validé';
                                                $action = '';
                                            }
                                        }
                                    ?>

                                        <?= $action ?>
                                        <?= $nomClient ?>
                                        <?= $nomProjet ?>
                                        <?= date('d/m/Y', strtotime($operation->date())) ?>
                                        <?= date('d/m/Y', strtotime($operation->dateReglement())) ?>
                                        <?= $operation->modePaiement() ?>
                                        <?= $operation->compteBancaire() ?>
                                        <?= $operation->numeroCheque() ?>
                                        <?= number_format($operation->montant(), 2, ',', ' ') ?> DH
                                        <?= $status ?>

                                    <div id="validateOperation<?= $operation->id() ?>" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="login" aria-hidden="false" >

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Valider Paiement Client

                                            <form class="form-horizontal loginFrm" action="../controller/OperationActionController.php" method="post">

                                                    <input type="hidden" name="action" value="validate" />
                                                    <input type="hidden" name="source" value="operations-status" />
                                                    <input type="hidden" name="mois" value="<?= $mois ?>" />
                                                    <input type="hidden" name="annee" value="<?= $annee ?>" />
                                                    <input type="hidden" name="idOperation" value="<?= $operation->id() ?>" />
                                                    <button class="btn" data-dismiss="modal"aria-hidden="true">Non</button>
                                                    <button type="submit" class="btn blue" aria-hidden="true">Oui</button>

                                            </form>

                                    <div id="cancelOperation<?= $operation->id() ?>" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="login" aria-hidden="false" >

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Annuler Paiement Client

                                            <form class="form-horizontal loginFrm" action="../controller/OperationActionController.php" method="post">

                                                    <input type="hidden" name="action" value="cancel" />
                                                    <input type="hidden" name="source" value="operations-status" />
                                                    <input type="hidden" name="mois" value="<?= $mois ?>" />
                                                    <input type="hidden" name="annee" value="<?= $annee ?>" />
                                                    <input type="hidden" name="idOperation" value="<?= $operation->id() ?>" />
                                                    <button class="btn" data-dismiss="modal"aria-hidden="true">Non</button>
                                                    <button type="submit" class="btn red" aria-hidden="true">Oui</button>

                                            </form>

                                    <div id="hideOperation<?= $operation->id() ?>" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="login" aria-hidden="false" >

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Retirer Paiement Client

                                            <form class="form-horizontal loginFrm" action="../controller/OperationActionController.php" method="post">

                                                    <input type="hidden" name="action" value="hide" />
                                                    <input type="hidden" name="source" value="operations-status" />
                                                    <input type="hidden" name="mois" value="<?= $mois ?>" />
                                                    <input type="hidden" name="annee" value="<?= $annee ?>" />
                                                    <input type="hidden" name="idOperation" value="<?= $operation->id() ?>" />
                                                    <button class="btn" data-dismiss="modal"aria-hidden="true">Non</button>
                                                    <button type="submit" class="btn green" aria-hidden="true">Oui</button>

                                            </form>

                                    <div id="deleteOperation<?= $operation->id() ?>" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="login" aria-hidden="false" >

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Supprimer Réglement Client

                                            <form class="form-horizontal loginFrm" action="../controller/OperationActionController.php" method="post">

Êtes-vous sûr de vouloir supprimer ce réglement ?

                                                    <input type="hidden" name="action" value="delete" />
                                                    <input type="hidden" name="mois" value="<?= $mois ?>" />
                                                    <input type="hidden" name="annee" value="<?= $annee ?>" />
                                                    <input type="hidden" name="idOperation" value="<?= $operation->id() ?>" />
                                                    <button class="btn" data-dismiss="modal"aria-hidden="true">Non</button>
                                                    <button type="submit" class="btn red" aria-hidden="true">Oui</button>

                                            </form>

                                    <?php
                                    }//end of loop
                                    ?>

        2015 © ImmoERP. Management Application.

<?php
}
/*else if(isset($_SESSION['userMerlaTrav']) and $_SESSION->profil()!="admin"){
    header('Location:dashboard.php');
}*/
else{
    header('Location:index.php');
}

?>

redpajama_set_name: RedPajamaGithub


text:
class CalendarEvent < ApplicationRecord
  include Eventable
  eventablize_opts actor: proc { User.current }, provider: :calendarable, team: :team,
                   as_json: {
                     only: [:name]
                   }
  eventablize_on :create
  eventablize_on :update, verb: :edit
  eventablize_on :destroy

  belongs_to :calendarable, polymorphic: true
  belongs_to :team
  belongs_to :creator, class_name: 'User'
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">

<meta name="GENERATOR" content="PasDoc 0.9.0">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>imapsend</title>
<link rel="StyleSheet" type="text/css" href="pasdoc.css">

Unit imapsend

Description	uses	Classes, Interfaces, Objects and Records	Functions and Procedures	Types	Constants	Variables

Description

IMAP4 rev1 protocol client

Used RFC: RFC-2060, RFC-2595

uses

SysUtils

Classes

blcksock

synautil

Overview

Classes, Interfaces, Objects and Records

Name
Description

Class TIMAPSend
Implementation of IMAP4 protocol.

Constants

cIMAPProtocol = '143';

Description

Constants

cIMAPProtocol = '143';

Generated by PasDoc 0.9.0 on 2012-04-23 21:38:50


text:
public interface Named
{
   default String name() { return "(NONE)"; }
}


text:
package de.passau.uni.sec.compose.id.rest.messages;

import com.fasterxml.jackson.annotation.JsonInclude;

import de.passau.uni.sec.compose.id.core.persistence.entities.Application;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ApplicationResponseMessage extends AbstractCoreEnityResponse implements EntityResponseMessage
{

	private String name;

	public ApplicationResponseMessage(Application app)
	{
		 name = app.getName();
		 id = app.getId();
		 owner_id = app.getOwner().getId();
		 groups = app.getApprovedGroups(app.getGroups());
		 lastModified = app.getLastModified();
		 //Do this for every entity. And test!
		 attributeValues = app.getApprovedAttributeValues(app.getAttributes());
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getOwner_id() {
		return owner_id;
	}
	public void setOwner_id(String owner_id) {
		this.owner_id = owner_id;
	}

}


text:
#ifndef _OHS_CMD
#define _OHS_CMD

#include <stdio.h>

struct ohs_command {
  const char *cmd;
  const char *syntax;
  const char *helptext_brief;
  const char *helptext_long;
  int (*cmd_cb) (const char *);
};

int ohs_set_olsrd_path(const char *);

void ohs_parse_command(void);

int ohs_cmd_olsrd(const char *);

int ohs_cmd_list(const char *);

int ohs_cmd_help(const char *);

int ohs_cmd_exit(const char *) __attribute__ ((noreturn));

int ohs_cmd_log(const char *);

int ohs_cmd_link(const char *);

#endif /* _OHS_CMD */

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
package com.sattvik.baitha

import Predef.{wrapString => _, augmentString => _, _}
import android.util.Log

import Logger.{LogPrinter, LogConfig}

import SdkVersions._

/** An enhanced logging facility for Android inspired from the facility from
  * [[http://code.google.com/p/roboguice RoboGuice]].
  *
  * == Getting a logger ==
  *
  * The simplest way to get a logger is to simply use the
  * `Logger.createLogger` factory function as in:
  *
  * {{{
  * val log = Logger.createLogger("MyTag")
  * }}}
  *
  * If your application already makes use of a [[com.sattvik.baitha.BuildMode]]
  * instance, you can use it combination with a `DefaultLogger` as follows:
  *
  * {{{
  * trait MyBuildMode extends DebugMode
  *
  * val log = new DefaultLoggeR("MyTag") extends MyBuildMode
  * }}}
  *
  *
  * == Using a logger ==
  *
  * === Log levels ===
  *
  * The log levels supported by `Logger` in order of increasing severity are:
  *
  *

  *
Verbose: `Logger.v(…)`

  *
Debug: `Logger.d(…)`

  *
Info: `Logger.i(…)`

  *
Warn: `Logger.w(…)`

  *
Error: `Logger.e(…)`

  *
What a Terrible Failure!: `Logger.wtf(…)`

  *

  *
  * '''Note:''' The WTF level is treated specially.  On FroYo (Android 2.2)
  * and newer, it uses the native WTF mechanism.  On older version of Android,
  * it simply logs at the `ASSERT` level.
  *
  *
  * === Log arguments ===
  *
  * Generally, log messages may include a message, an exception, or both.  It
  * is also possible to use `String.format` style formatting.  Some examples
  * follow:
  *
  * {{{
  * Log.i("hello there")
  * Log.v("%s %s", "hello", "there")
  * Log.w(exception, "Error occurred, panic!")
  * Log.e(exception, "Another error occured, %s panic!", "please")
  * }}}
  *
  * '''Note:''' Unlike Android's Log mechanism, exceptions occur at the
  * beginning of the argument list.  Also, additional arguments to the log
  * message will not simply be appended, they must be included using a format
  * parameter.
  *
  * == Advanced configuration ==
  *
  * The Logger trait depends on two different other traits that can be used to
  * change the logging behaviour: `LogConfig` and `LogPrinter`.
  *
  * `LogConfig` is used to specify the logging 'scope', which can be
  * understood as the log source and corresponds to Android's log tag.  The
  * `LogConfig` also specifies the minimum log level that should be printed.
  *
  * A `LogPrinter` can modify the message before it is printed, and can even
  * be used to redirect logging to some place other than the Android log
  * mechanism.
  *
  * @author Daniel Solano Gómez */
trait Logger {this: LogConfig with LogPrinter =>
  /** The handler for terrible failures.  On FroYo and beyond, this defers to
    * Android's mechanism.  On versions before FroYo, it is simply handled as
    * an ASSERT level log message. */
  private val wtfLogger = {
    if (currentSdkSince(FroYo)) {
      new FroYoWtfLogger
    }
    else {
      new PreFroYoWtfLogger
    }
  }

  /** Logs the exception at a VERBOSE level. */
  def v(throwable: Throwable) = logThrowable(Log.VERBOSE, throwable)

  /** Log the message at a VERBOSE level. */
  def v(message: AnyRef, args: Any*) = logMessage(Log.VERBOSE, message, args)

  /** Log the exception with a message at a VERBOSE level */
  def v(throwable: Throwable, message: AnyRef, args: Any*) = {
    logThrowableWithMessage(Log.VERBOSE, throwable, message, args)
  }

  /** Logs the exception at a DEBUG level. */
  def d(throwable: Throwable) = logThrowable(Log.DEBUG, throwable)

  /** Log the message at a DEBUG level. */
  def d(message: AnyRef, args: Any*) = logMessage(Log.DEBUG, message, args)

  /** Log the exception with a message at a DEBUG level */
  def d(throwable: Throwable, message: AnyRef, args: Any*) = {
    logThrowableWithMessage(Log.DEBUG, throwable, message, args)
  }

  /** Logs the exception at a INFO level. */
  def i(throwable: Throwable) = logThrowable(Log.INFO, throwable)

  /** Log the message at a INFO level. */
  def i(message: AnyRef, args: Any*) = logMessage(Log.INFO, message, args)

  /** Log the exception with a message at a INFO level */
  def i(throwable: Throwable, message: AnyRef, args: Any*) = {
    logThrowableWithMessage(Log.INFO, throwable, message, args)
  }

  /** Logs the exception at a WARN level. */
  def w(throwable: Throwable) = logThrowable(Log.WARN, throwable)

  /** Log the message at a WARN level. */
  def w(message: AnyRef, args: Any*) = logMessage(Log.WARN, message, args)

  /** Log the exception with a message at a WARN level */
  def w(throwable: Throwable, message: AnyRef, args: Any*) = {
    logThrowableWithMessage(Log.WARN, throwable, message, args)
  }

  /** Logs the exception at a ERROR level. */
  def e(throwable: Throwable) = logThrowable(Log.ERROR, throwable)

  /** Log the message at a ERROR level. */
  def e(message: AnyRef, args: Any*) = logMessage(Log.ERROR, message, args)

  /** Log the exception with a message at a ERROR level */
  def e(throwable: Throwable, message: AnyRef, args: Any*) = {
    logThrowableWithMessage(Log.ERROR, throwable, message, args)
  }

  /** What a Terrible Failure: Report a condition that should never happen.
    * The error will always be logged at level ASSERT with the call stack.
    * Depending on system configuration, a report may be added to the
    * DropBoxManager and/or the process may be terminated immediately with an
    * error dialog. */
  def wtf(message: AnyRef, args: Any*) {
    wtfLogger.wtf(null, messageString(message, args))
  }

  /** What a Terrible Failure: Report a condition that should never happen.
    * Similar to wtf(AnyRef, Any*), but with an exception as well. */
  def wtf(throwable: Throwable, message: AnyRef, args: Any*) = {
    wtfLogger.wtf(throwable, messageString(message, args))
  }

  /** What a Terrible Failure: Report a condition that should never happen.
    * Similar to wtf(AnyRef, Any*), but with an exception to log. */
  def wtf(throwable: Throwable) = {
    wtfLogger.wtf(
      throwable,
      if (throwable == null) "null" else throwable.getMessage)
  }

  /** If the given log level is loggable, perform the given action. */
  private def whenLoggable(logLevel: Int)(action: => Int) = {
    if (logLevel < config.minLogLevel) 0 else action
  }

  /** Logs an exception if the given log level is loggable. */
  private def logThrowable(logLevel: Int, throwable: Throwable) = {
    whenLoggable(logLevel) {
      printer.printLog(logLevel, Log.getStackTraceString(throwable))
    }
  }

  /** Logs a message if the given log level is loggable. */
  private def logMessage(logLevel: Int, message: AnyRef, args: Seq[Any]) = {
    whenLoggable(logLevel) {
      printer.printLog(logLevel, messageString(message, args))
    }
  }

  /** Creates a message by applying the arguments to the message in a fashion
    * similar to String.format(message, args). */
  private def messageString(message: AnyRef, args: Seq[Any]) = {
    val messageStr = if (message == null) "null" else message.toString
    if (args.isEmpty) {
      messageStr
    } else {
      val argArray: Seq[AnyRef] = args map { arg: Any =>
        arg match {
          case r: AnyRef => r
          case d: Double => java.lang.Double.valueOf(d)
          case f: Float => java.lang.Float.valueOf(f)
          case l: Long => java.lang.Long.valueOf(l)
          case i: Int => java.lang.Integer.valueOf(i)
          case c: Char => java.lang.Character.valueOf(c)
          case s: Short => java.lang.Short.valueOf(s)
          case b: Boolean => java.lang.Boolean.valueOf(b)
        }
      }
      String.format(message.toString, argArray: _*)
    }
  }

  /** Logs an exception with a message if the given log level is loggable. */
  private def logThrowableWithMessage(
    logLevel: Int,
    throwable: Throwable,
    message: AnyRef,
    args: Seq[Any]
  ) = {
    whenLoggable(logLevel) {
      printer.printLog(
        logLevel, messageString(message, args) + '\n' +
            Log.getStackTraceString(throwable))
    }
  }

  /** The interface for a logger to support the What a Terrible Failure
    * report. */
  private trait WtfLogger {
    def wtf(throwable: Throwable, message: String): Int
  }

  /** The logger that uses the ASSERT log level for wtf messages.  This is for
    * platforms that don't support the wtf log method. */
  private class PreFroYoWtfLogger extends WtfLogger {
    def wtf(throwable: Throwable, message: String) = {
      printer.printLog(Log.ASSERT, message)
    }
  }

  /** The logger that actually uses the wtf log messages available since
    * FroYo. */
  private class FroYoWtfLogger extends WtfLogger {
    def wtf(throwable: Throwable, message: String) = {
      Log.wtf(config.scope, message, throwable)
    }
  }
}

/** Companion object that defined the types for log printers and
  * configurations.  It also provides a mostly-configure default logger
  * class, along with a factory function to easily create new loggers with a
  * given name for a scope.
  *
  * @todo Add a context-driven configuration
  * @todo Create a fancy printer with extra debug information
  *
  * @author Daniel Solano Gómez */
object Logger {
  /** Creates a new default logger with the given name for a scope.
    *
    * @param name the name of the scope for the logger
    * @param debug if true, the logger operates in debug mode,
    * otherwise it operates in production mode. */
  def createLogger(name: String, debug: Boolean = false) = {
    if (debug) new DefaultLogger(name) with DebugMode
    else new DefaultLogger(name) with ProductionMode
  }

  /** The log printer is in charge of actually taking a log message that has
    * been processed by the logger and logging it. */
  trait LogPrinter {
    /** A reference to the printer for use within the logger. */
    val printer: Printer

    /** The interface for the printer. */
    trait Printer {
      /** Prints the given message at the given priority. */
      def printLog(priority: Int, message: String): Int
    }
  }

  /** The simple log printer does not do any further processing of the
    * message and simply passes it along to Android. */
  trait SimpleLogPrinter extends LogPrinter {this: LogConfig =>
    /** Simple printer that uses the configuration scope as the log tag. */
    class SimplePrinter extends Printer {
      override def printLog(priority: Int, message: String) = {
        Log.println(priority, config.scope, message)
      }
    }
  }

  /** A logger instance must have a log configuration which determines what
    * log levels are active and names the source of the log message. */
  trait LogConfig {
    /** Reference to the configuration, for use by the logger. */
    val config: Config

    /** Basic configuration parameters for the logger. */
    trait Config {
      /** The minimum log level that is currently loggable. */
      def minLogLevel: Int
      /** A string used to identify the source of the log message. */
      def scope: String
    }
  }

  /** Simple implementation of a log configuration that uses a given name and
    * depends on a BuildMode to determine the minimum log level.  If the current
    * build mode is Debug, all log messages will be printed.  If the current
    * log level is Release, only WARN and higher priority messages will be
    * logged. */
  trait NamedDebugLogConfig extends LogConfig with BuildMode {
    /** Actual implementation of the named debug log configuration.
      *
      * @constructor Creates a new configuration using the given name as the
      * scope. */
    class NamedDebugConfig(name: String) extends Config {
      /** Sets the minimum log level depending on the debug flag. */
      override val minLogLevel = if (debugMode) Log.VERBOSE else Log.WARN
      /** Sets the scope to the given name. */
      override val scope = name
    }
  }

  /** A logger configuration that uses a SimpleLogPrinter and a
    * NamedDebugLogConfig.   Note that this class is abstract as it does not
    * actually have the build mode set. */
  abstract class DefaultLogger(name: String)
      extends Logger with SimpleLogPrinter with NamedDebugLogConfig {
    val config  = new NamedDebugConfig(name)
    val printer = new SimplePrinter
  }

  /** An implementation of the logger that does nothing, useful for testing. */
  trait NoOpLogger extends Logger with LogConfig with LogPrinter {
    val printer = new Printer {
      def printLog(priority: Int, message: String) = 0
    }
    val config  = new Config {
      def minLogLevel = Int.MaxValue

      def scope = null
    }
  }
}


text:
<?php

namespace Fuel\Upload;

/**
 * Exception class to indicate no files where uploaded
 */
class NoFilesException extends \RuntimeException {}


text:
using engenious;
using OctoAwesome.Notifications;
using OctoAwesome.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OctoAwesome.Network
{
    public class SimulationManager
    {
        public bool IsRunning { get; private set; }
        public IDefinitionManager DefinitionManager => definitionManager;

        public Simulation Simulation
        {
            get
            {
                lock (mainLock)
                    return simulation;
            }
            set
            {
                lock (mainLock)
                    simulation = value;
            }
        }

        public GameTime GameTime { get; private set; }

        public ResourceManager ResourceManager { get; private set; }
        public GameService Service { get; }

        private Simulation simulation;
        private ExtensionLoader extensionLoader;
        private DefinitionManager definitionManager;

        private ISettings settings;

        private Thread backgroundThread;
        private object mainLock;
        private IDisposable chunkSubscription;

        public SimulationManager(ISettings settings, UpdateHub updateHub)
        {
            mainLock = new object();

            this.settings = settings; //TODO: Where are the settings?

            extensionLoader = new ExtensionLoader(settings);
            extensionLoader.LoadExtensions();

            definitionManager = new DefinitionManager(extensionLoader);

            var persistenceManager = new DiskPersistenceManager(extensionLoader, definitionManager, settings);

            ResourceManager = new ResourceManager(extensionLoader, definitionManager, settings, persistenceManager);
            ResourceManager.InsertUpdateHub(updateHub);

            chunkSubscription = updateHub.Subscribe(ResourceManager.GlobalChunkCache, DefaultChannels.Chunk);
            ResourceManager.GlobalChunkCache.InsertUpdateHub(updateHub);
            Service = new GameService(ResourceManager);
            simulation = new Simulation(ResourceManager, extensionLoader, Service)
            {
                IsServerSide = true
            };
            backgroundThread = new Thread(SimulationLoop)
            {
                Name = "Simulation Loop",
                IsBackground = true
            };
        }

        public void Start()
        {
            IsRunning = true;
            GameTime = new GameTime();

            var universe = settings.Get<string>("LastUniverse");

            if (string.IsNullOrWhiteSpace(universe) || true) //TODO: If the load mechanism is repaired remove true
            {
                var guid = simulation.NewGame("melmack", new Random().Next());
                settings.Set("LastUniverse", guid.ToString());
            }
            else
            {
                simulation.LoadGame(new Guid(universe));
            }

            backgroundThread.Start();
        }

        public void Stop()
        {
            IsRunning = false;
            simulation.ExitGame();
            backgroundThread.Abort();
        }

        public IUniverse GetUniverse() => ResourceManager.CurrentUniverse;

        public IUniverse NewUniverse()
        {
            throw new NotImplementedException();
        }

        public IPlanet GetPlanet(int planetId) => ResourceManager.GetPlanet(planetId);

        public IChunkColumn LoadColumn(Guid guid, int planetId, Index2 index2)
            => ResourceManager.LoadChunkColumn(planetId, index2);

        private void SimulationLoop()
        {
            while (IsRunning)
            {
                Simulation.Update(GameTime);
            }
        }
    }
}


text:
class FeedbacksController < ApplicationController
  def create
    @feedback = Feedback.new(feedback_params)

    respond_to do |format|
      if @feedback.save
        format.html { redirect_to :back, notice: "Feedback sucessfully created!" }
        format.json { render json: @feedback, status: :created, location: @feedback }
      else
        format.html { render 'new' }
        format.json { render json: @feedback.errors, status: :unprocessable_entity }
      end
    end
  end

  def new
    @feedback = Feedback.new
  end

  private
  def feedback_params
    params.require(:feedback).permit(:title, :content, :email)
  end
end


text: log = loglevel.createPackageLogger('practicalmeteor:munit', 'info');


text:
@implementation OrgBouncycastleMathRawNat512

+ (void)mulWithIntArray:(IOSIntArray *)x
           withIntArray:(IOSIntArray *)y
           withIntArray:(IOSIntArray *)zz {
  OrgBouncycastleMathRawNat512_mulWithIntArray_withIntArray_withIntArray_(x, y, zz);
}

+ (void)squareWithIntArray:(IOSIntArray *)x
              withIntArray:(IOSIntArray *)zz {
  OrgBouncycastleMathRawNat512_squareWithIntArray_withIntArray_(x, zz);
}

- (instancetype)init {
  OrgBouncycastleMathRawNat512_init(self);
  return self;
}

@end

void OrgBouncycastleMathRawNat512_mulWithIntArray_withIntArray_withIntArray_(IOSIntArray *x, IOSIntArray *y, IOSIntArray *zz) {
  OrgBouncycastleMathRawNat512_initialize();
  OrgBouncycastleMathRawNat256_mulWithIntArray_withIntArray_withIntArray_(x, y, zz);
  OrgBouncycastleMathRawNat256_mulWithIntArray_withInt_withIntArray_withInt_withIntArray_withInt_(x, 8, y, 8, zz, 16);
  jint c24 = OrgBouncycastleMathRawNat256_addToEachOtherWithIntArray_withInt_withIntArray_withInt_(zz, 8, zz, 16);
  jint c16 = c24 + OrgBouncycastleMathRawNat256_addToWithIntArray_withInt_withIntArray_withInt_withInt_(zz, 0, zz, 8, 0);
  c24 += OrgBouncycastleMathRawNat256_addToWithIntArray_withInt_withIntArray_withInt_withInt_(zz, 24, zz, 16, c16);
  IOSIntArray *dx = OrgBouncycastleMathRawNat256_create(), *dy = OrgBouncycastleMathRawNat256_create();
  jboolean neg = OrgBouncycastleMathRawNat256_diffWithIntArray_withInt_withIntArray_withInt_withIntArray_withInt_(x, 8, x, 0, dx, 0) != OrgBouncycastleMathRawNat256_diffWithIntArray_withInt_withIntArray_withInt_withIntArray_withInt_(y, 8, y, 0, dy, 0);
  IOSIntArray *tt = OrgBouncycastleMathRawNat256_createExt();
  OrgBouncycastleMathRawNat256_mulWithIntArray_withIntArray_withIntArray_(dx, dy, tt);
  c24 += neg ? OrgBouncycastleMathRawNat_addToWithInt_withIntArray_withInt_withIntArray_withInt_(16, tt, 0, zz, 8) : OrgBouncycastleMathRawNat_subFromWithInt_withIntArray_withInt_withIntArray_withInt_(16, tt, 0, zz, 8);
  OrgBouncycastleMathRawNat_addWordAtWithInt_withInt_withIntArray_withInt_(32, c24, zz, 24);
}

void OrgBouncycastleMathRawNat512_squareWithIntArray_withIntArray_(IOSIntArray *x, IOSIntArray *zz) {
  OrgBouncycastleMathRawNat512_initialize();
  OrgBouncycastleMathRawNat256_squareWithIntArray_withIntArray_(x, zz);
  OrgBouncycastleMathRawNat256_squareWithIntArray_withInt_withIntArray_withInt_(x, 8, zz, 16);
  jint c24 = OrgBouncycastleMathRawNat256_addToEachOtherWithIntArray_withInt_withIntArray_withInt_(zz, 8, zz, 16);
  jint c16 = c24 + OrgBouncycastleMathRawNat256_addToWithIntArray_withInt_withIntArray_withInt_withInt_(zz, 0, zz, 8, 0);
  c24 += OrgBouncycastleMathRawNat256_addToWithIntArray_withInt_withIntArray_withInt_withInt_(zz, 24, zz, 16, c16);
  IOSIntArray *dx = OrgBouncycastleMathRawNat256_create();
  OrgBouncycastleMathRawNat256_diffWithIntArray_withInt_withIntArray_withInt_withIntArray_withInt_(x, 8, x, 0, dx, 0);
  IOSIntArray *tt = OrgBouncycastleMathRawNat256_createExt();
  OrgBouncycastleMathRawNat256_squareWithIntArray_withIntArray_(dx, tt);
  c24 += OrgBouncycastleMathRawNat_subFromWithInt_withIntArray_withInt_withIntArray_withInt_(16, tt, 0, zz, 8);
  OrgBouncycastleMathRawNat_addWordAtWithInt_withInt_withIntArray_withInt_(32, c24, zz, 24);
}

void OrgBouncycastleMathRawNat512_init(OrgBouncycastleMathRawNat512 *self) {
  (void) NSObject_init(self);
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgBouncycastleMathRawNat512)


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ShopifySharp.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShopifySharp
{
    /// <summary>
    /// An object representing remote javascript tags that are loaded into the pages of a shop's storefront.
    /// </summary>
    public class ScriptTag: ShopifyObject
    {
        /// <summary>
        /// The date and time when the <see cref="ScriptTag"/> was created.
        /// </summary>
        [JsonProperty("created_at")]
        public DateTimeOffset? CreatedAt { get; set; }

        /// <summary>
        /// Where the script tag should be included on the store. Known values are 'online_store', 'order_status' or 'all'. Defaults to 'all'.
        /// </summary>
        [JsonProperty("display_scope")]
        public string DisplayScope { get; set; }

        /// <summary>
        /// DOM event which triggers the loading of the script. The only known value is 'onload'.
        /// </summary>
        [JsonProperty("event")]
        public string Event { get; set; }

        /// <summary>
        /// Specifies the location of the ScriptTag.
        /// </summary>
        [JsonProperty("src")]
        public string Src { get; set; }

        /// <summary>
        /// The date and time when the <see cref="ScriptTag"/> was updated.
        /// </summary>
        [JsonProperty("updated_at")]
        public DateTimeOffset? UpdatedAt { get; set; }
    }
}


text:
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>anthill.log</file>
        <append>true</append>
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
        <!--<appender-ref ref="FILE" />-->
    </root>
</configuration>


text:
<?php

namespace Oro\Bundle\SecurityBundle\Tests\Unit;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;

use Oro\Bundle\SecurityBundle\SecurityFacade;
use Oro\Bundle\SecurityBundle\Annotation\Acl;

class SecurityFacadeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var SecurityFacade
     */
    private $facade;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $securityContext;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $annotationProvider;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $objectIdentityFactory;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $logger;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $classResolver;

    protected function setUp()
    {
        $this->securityContext = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $this->annotationProvider =
            $this->getMockBuilder('Oro\Bundle\SecurityBundle\Metadata\AclAnnotationProvider')
                ->disableOriginalConstructor()
                ->getMock();
        $this->objectIdentityFactory =
            $this->getMockBuilder('Oro\Bundle\SecurityBundle\Acl\Domain\ObjectIdentityFactory')
                ->disableOriginalConstructor()
                ->getMock();
        $this->logger = $this->getMock('Psr\Log\LoggerInterface');

        $this->classResolver =
            $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\EntityClassResolver')
                ->disableOriginalConstructor()
                ->getMock();

        $this->facade = new SecurityFacade(
            $this->securityContext,
            $this->annotationProvider,
            $this->objectIdentityFactory,
            $this->classResolver,
            $this->logger
        );
    }

    public function testIsClassMethodGrantedDenyingByMethodAcl()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));

        $this->annotationProvider->expects($this->once())
            ->method('findAnnotation')
            ->with('TestClass', 'TestMethod')
            ->will($this->returnValue($annotation));
        $this->logger->expects($this->once())
            ->method('debug');
        $this->objectIdentityFactory->expects($this->once())
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(false));

        $result = $this->facade->isClassMethodGranted('TestClass', 'TestMethod');
        $this->assertFalse($result);
    }

    public function testIsClassMethodGrantedGrantingByMethodAclNoClassAcl()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $annotation->expects($this->once())
            ->method('getIgnoreClassAcl')
            ->will($this->returnValue(false));

        $this->annotationProvider->expects($this->at(0))
            ->method('findAnnotation')
            ->with('TestClass', 'TestMethod')
            ->will($this->returnValue($annotation));
        $this->annotationProvider->expects($this->at(1))
            ->method('findAnnotation')
            ->with('TestClass')
            ->will($this->returnValue(null));
        $this->logger->expects($this->once())
            ->method('debug');
        $this->objectIdentityFactory->expects($this->once())
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(true));

        $result = $this->facade->isClassMethodGranted('TestClass', 'TestMethod');
        $this->assertTrue($result);
    }

    public function testIsClassMethodGrantedGrantingByMethodAclWithIgnoreClassAcl()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $annotation->expects($this->once())
            ->method('getIgnoreClassAcl')
            ->will($this->returnValue(true));

        $this->annotationProvider->expects($this->once())
            ->method('findAnnotation')
            ->with('TestClass', 'TestMethod')
            ->will($this->returnValue($annotation));
        $this->logger->expects($this->once())
            ->method('debug');
        $this->objectIdentityFactory->expects($this->once())
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(true));

        $result = $this->facade->isClassMethodGranted('TestClass', 'TestMethod');
        $this->assertTrue($result);
    }

    public function testIsClassMethodGrantedDenyingByClassAcl()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $annotation->expects($this->once())
            ->method('getIgnoreClassAcl')
            ->will($this->returnValue(false));

        $classOid = new ObjectIdentity('2', 'TestType');
        $classAnnotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $classAnnotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('class_annotation'));
        $classAnnotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION_CLASS'));

        $this->annotationProvider->expects($this->at(0))
            ->method('findAnnotation')
            ->with('TestClass', 'TestMethod')
            ->will($this->returnValue($annotation));
        $this->annotationProvider->expects($this->at(1))
            ->method('findAnnotation')
            ->with('TestClass')
            ->will($this->returnValue($classAnnotation));
        $this->logger->expects($this->exactly(2))
            ->method('debug');
        $this->objectIdentityFactory->expects($this->at(0))
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->objectIdentityFactory->expects($this->at(1))
            ->method('get')
            ->with($this->identicalTo($classAnnotation))
            ->will($this->returnValue($classOid));
        $this->securityContext->expects($this->at(0))
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(true));
        $this->securityContext->expects($this->at(1))
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION_CLASS'), $this->identicalTo($classOid))
            ->will($this->returnValue(false));

        $result = $this->facade->isClassMethodGranted('TestClass', 'TestMethod');
        $this->assertFalse($result);
    }

    public function testIsClassMethodGrantedGrantingByMethodAndClassAcls()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $annotation->expects($this->once())
            ->method('getIgnoreClassAcl')
            ->will($this->returnValue(false));

        $classOid = new ObjectIdentity('2', 'TestType');
        $classAnnotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $classAnnotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('class_annotation'));
        $classAnnotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION_CLASS'));

        $this->annotationProvider->expects($this->at(0))
            ->method('findAnnotation')
            ->with('TestClass', 'TestMethod')
            ->will($this->returnValue($annotation));
        $this->annotationProvider->expects($this->at(1))
            ->method('findAnnotation')
            ->with('TestClass')
            ->will($this->returnValue($classAnnotation));
        $this->logger->expects($this->exactly(2))
            ->method('debug');
        $this->objectIdentityFactory->expects($this->at(0))
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->objectIdentityFactory->expects($this->at(1))
            ->method('get')
            ->with($this->identicalTo($classAnnotation))
            ->will($this->returnValue($classOid));
        $this->securityContext->expects($this->at(0))
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(true));
        $this->securityContext->expects($this->at(1))
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION_CLASS'), $this->identicalTo($classOid))
            ->will($this->returnValue(true));

        $result = $this->facade->isClassMethodGranted('TestClass', 'TestMethod');
        $this->assertTrue($result);
    }

    public function testIsGrantedWithAclAnnotationIdAndNoObject()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $this->objectIdentityFactory->expects($this->once())
            ->method('get')
            ->with($this->identicalTo($annotation))
            ->will($this->returnValue($oid));
        $this->annotationProvider->expects($this->at(0))
            ->method('findAnnotationById')
            ->with('TestAnnotation')
            ->will($this->returnValue($annotation));
        $this->logger->expects($this->once())
            ->method('debug');
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($oid))
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('TestAnnotation');
        $this->assertTrue($result);
    }

    public function testIsGrantedWithAclAnnotationIdAndWithObject()
    {
        $obj = new \stdClass();
        $annotation = $this->getMockBuilder('Oro\Bundle\SecurityBundle\Annotation\Acl')
            ->disableOriginalConstructor()
            ->getMock();
        $annotation->expects($this->once())
            ->method('getId')
            ->will($this->returnValue('method_annotation'));
        $annotation->expects($this->once())
            ->method('getPermission')
            ->will($this->returnValue('TEST_PERMISSION'));
        $this->objectIdentityFactory->expects($this->never())
            ->method('get');
        $this->annotationProvider->expects($this->at(0))
            ->method('findAnnotationById')
            ->with('TestAnnotation')
            ->will($this->returnValue($annotation));
        $this->logger->expects($this->once())
            ->method('debug');
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($obj))
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('TestAnnotation', $obj);
        $this->assertTrue($result);
    }

    public function testIsGrantedWithRoleName()
    {
        $this->annotationProvider->expects($this->once())
            ->method('findAnnotationById')
            ->with('TestRole')
            ->will($this->returnValue(null));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('TestRole'), $this->equalTo(null))
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('TestRole');
        $this->assertTrue($result);
    }

    public function testIsGrantedWithRoleNames()
    {
        $this->annotationProvider->expects($this->never())
            ->method('findAnnotationById');
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo(array('TestRole1', 'TestRole2')), $this->equalTo(null))
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted(array('TestRole1', 'TestRole2'));
        $this->assertTrue($result);
    }

    public function testIsGrantedWithString()
    {
        $oid = new ObjectIdentity('1', 'TestType');
        $obj = 'Entity:SomeClass';
        $this->annotationProvider->expects($this->once())
            ->method('findAnnotationById')
            ->with('PERMISSION')
            ->will($this->returnValue(false));
        $this->objectIdentityFactory->expects($this->at(0))
            ->method('get')
            ->with($this->equalTo($obj))
            ->will($this->returnValue($oid));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('PERMISSION'), $oid)
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('PERMISSION', $obj);
        $this->assertTrue($result);
    }

    public function testIsGrantedWithCombinedString()
    {
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('VIEW'), 'entity:AcmeDemoBundle:Test')
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('VIEW;entity:AcmeDemoBundle:Test');
        $this->assertTrue($result);
    }

    public function testIsGrantedWithObject()
    {
        $obj = new \stdClass();
        $this->annotationProvider->expects($this->once())
            ->method('findAnnotationById')
            ->with('PERMISSION')
            ->will($this->returnValue(false));
        $this->securityContext->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo('PERMISSION'), $this->equalTo($obj))
            ->will($this->returnValue(true));

        $result = $this->facade->isGranted('PERMISSION', $obj);
        $this->assertTrue($result);
    }

    public function testGetRequestAcl()
    {
        $request = new Request();
        $request->attributes->add(['_controller' => 'OroTestBundle::testAction']);
        $acl = new Acl(['id' => 1, 'class' => 'OroTestBundle:Test', 'type' => 'entity']);
        $this->annotationProvider->expects($this->once())
            ->method('findAnnotation')
            ->with('OroTestBundle', 'testAction')
            ->will($this->returnValue($acl));
        $this->classResolver->expects($this->once())
            ->method('isEntity')
            ->with('OroTestBundle:Test')
            ->will($this->returnValue(true));
        $this->classResolver->expects($this->once())
            ->method('getEntityClass')
            ->with('OroTestBundle:Test')
            ->will($this->returnValue('Oro\Bundle\TestBundle\Entity\Test'));

        $returnAcl = $this->facade->getRequestAcl($request, true);
        $this->assertNotNull($returnAcl);
        $this->assertEquals('Oro\Bundle\TestBundle\Entity\Test', $acl->getClass());
    }

    public function testGeWrongRequestAcl()
    {
        $request = new Request();
        $request->attributes->add(['_controller' => 'wrong controller']);
        $this->annotationProvider->expects($this->never())
            ->method('findAnnotation');
        $this->classResolver->expects($this->never())
            ->method('isEntity');
        $this->classResolver->expects($this->never())
            ->method('getEntityClass');

        $this->assertNull($this->facade->getRequestAcl($request, true));
    }

    /**
     * @dataProvider isRequestObjectIsGrantedProvider
     */
    public function testIsRequestObjectIsGranted($requestController, $isGrant, $result)
    {
        $object = new \stdClass();
        $request = new Request();
        $request->attributes->add(['_controller' => $requestController]);
        $acl = new Acl(
            ['id' => 1, 'class' => 'OroTestBundle:Test', 'type' => 'entity', 'permission' => 'TEST_PERMISSION']
        );
        $this->annotationProvider->expects($this->any())
            ->method('findAnnotation')
            ->will($this->returnValue($acl));
        $this->classResolver->expects($this->any())
            ->method('isEntity')
            ->with('OroTestBundle:Test')
            ->will($this->returnValue(true));
        $this->classResolver->expects($this->any())
            ->method('getEntityClass')
            ->with('OroTestBundle:Test')
            ->will($this->returnValue('\stdClass'));
        $this->securityContext->expects($this->any())
            ->method('isGranted')
            ->with($this->equalTo('TEST_PERMISSION'), $this->identicalTo($object))
            ->will($this->returnValue($isGrant));

        $this->assertEquals($result, $this->facade->isRequestObjectIsGranted($request, $object));
    }

    public function isRequestObjectIsGrantedProvider()
    {
        return [
            ['testBundle::testAction', true, 1],
            ['testBundle::testAction', false, -1],
            ['wrong_action', true, 0]
        ];
    }
}


text:
package com.amazonaws.services.redshift;

import javax.annotation.Generated;

import com.amazonaws.services.redshift.model.*;
import com.amazonaws.*;
import com.amazonaws.services.redshift.waiters.AmazonRedshiftWaiters;

/**
 * Abstract implementation of {@code AmazonRedshift}. Convenient method forms pass through to the corresponding overload
 * that takes a request object, which throws an {@code UnsupportedOperationException}.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAmazonRedshift implements AmazonRedshift {

    protected AbstractAmazonRedshift() {
    }

    @Override
    public void setEndpoint(String endpoint) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public void setRegion(com.amazonaws.regions.Region region) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterSecurityGroup authorizeClusterSecurityGroupIngress(AuthorizeClusterSecurityGroupIngressRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Snapshot authorizeSnapshotAccess(AuthorizeSnapshotAccessRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Snapshot copyClusterSnapshot(CopyClusterSnapshotRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster createCluster(CreateClusterRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterParameterGroup createClusterParameterGroup(CreateClusterParameterGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterSecurityGroup createClusterSecurityGroup(CreateClusterSecurityGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Snapshot createClusterSnapshot(CreateClusterSnapshotRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterSubnetGroup createClusterSubnetGroup(CreateClusterSubnetGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public EventSubscription createEventSubscription(CreateEventSubscriptionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public HsmClientCertificate createHsmClientCertificate(CreateHsmClientCertificateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public HsmConfiguration createHsmConfiguration(CreateHsmConfigurationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public SnapshotCopyGrant createSnapshotCopyGrant(CreateSnapshotCopyGrantRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateTagsResult createTags(CreateTagsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster deleteCluster(DeleteClusterRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteClusterParameterGroupResult deleteClusterParameterGroup(DeleteClusterParameterGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteClusterSecurityGroupResult deleteClusterSecurityGroup(DeleteClusterSecurityGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Snapshot deleteClusterSnapshot(DeleteClusterSnapshotRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteClusterSubnetGroupResult deleteClusterSubnetGroup(DeleteClusterSubnetGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteEventSubscriptionResult deleteEventSubscription(DeleteEventSubscriptionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteHsmClientCertificateResult deleteHsmClientCertificate(DeleteHsmClientCertificateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteHsmConfigurationResult deleteHsmConfiguration(DeleteHsmConfigurationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteSnapshotCopyGrantResult deleteSnapshotCopyGrant(DeleteSnapshotCopyGrantRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteTagsResult deleteTags(DeleteTagsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterParameterGroupsResult describeClusterParameterGroups(DescribeClusterParameterGroupsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterParameterGroupsResult describeClusterParameterGroups() {
        return describeClusterParameterGroups(new DescribeClusterParameterGroupsRequest());
    }

    @Override
    public DescribeClusterParametersResult describeClusterParameters(DescribeClusterParametersRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterSecurityGroupsResult describeClusterSecurityGroups(DescribeClusterSecurityGroupsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterSecurityGroupsResult describeClusterSecurityGroups() {
        return describeClusterSecurityGroups(new DescribeClusterSecurityGroupsRequest());
    }

    @Override
    public DescribeClusterSnapshotsResult describeClusterSnapshots(DescribeClusterSnapshotsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterSnapshotsResult describeClusterSnapshots() {
        return describeClusterSnapshots(new DescribeClusterSnapshotsRequest());
    }

    @Override
    public DescribeClusterSubnetGroupsResult describeClusterSubnetGroups(DescribeClusterSubnetGroupsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterSubnetGroupsResult describeClusterSubnetGroups() {
        return describeClusterSubnetGroups(new DescribeClusterSubnetGroupsRequest());
    }

    @Override
    public DescribeClusterVersionsResult describeClusterVersions(DescribeClusterVersionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClusterVersionsResult describeClusterVersions() {
        return describeClusterVersions(new DescribeClusterVersionsRequest());
    }

    @Override
    public DescribeClustersResult describeClusters(DescribeClustersRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeClustersResult describeClusters() {
        return describeClusters(new DescribeClustersRequest());
    }

    @Override
    public DefaultClusterParameters describeDefaultClusterParameters(DescribeDefaultClusterParametersRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEventCategoriesResult describeEventCategories(DescribeEventCategoriesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEventCategoriesResult describeEventCategories() {
        return describeEventCategories(new DescribeEventCategoriesRequest());
    }

    @Override
    public DescribeEventSubscriptionsResult describeEventSubscriptions(DescribeEventSubscriptionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEventSubscriptionsResult describeEventSubscriptions() {
        return describeEventSubscriptions(new DescribeEventSubscriptionsRequest());
    }

    @Override
    public DescribeEventsResult describeEvents(DescribeEventsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEventsResult describeEvents() {
        return describeEvents(new DescribeEventsRequest());
    }

    @Override
    public DescribeHsmClientCertificatesResult describeHsmClientCertificates(DescribeHsmClientCertificatesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeHsmClientCertificatesResult describeHsmClientCertificates() {
        return describeHsmClientCertificates(new DescribeHsmClientCertificatesRequest());
    }

    @Override
    public DescribeHsmConfigurationsResult describeHsmConfigurations(DescribeHsmConfigurationsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeHsmConfigurationsResult describeHsmConfigurations() {
        return describeHsmConfigurations(new DescribeHsmConfigurationsRequest());
    }

    @Override
    public DescribeLoggingStatusResult describeLoggingStatus(DescribeLoggingStatusRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeOrderableClusterOptionsResult describeOrderableClusterOptions(DescribeOrderableClusterOptionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeOrderableClusterOptionsResult describeOrderableClusterOptions() {
        return describeOrderableClusterOptions(new DescribeOrderableClusterOptionsRequest());
    }

    @Override
    public DescribeReservedNodeOfferingsResult describeReservedNodeOfferings(DescribeReservedNodeOfferingsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeReservedNodeOfferingsResult describeReservedNodeOfferings() {
        return describeReservedNodeOfferings(new DescribeReservedNodeOfferingsRequest());
    }

    @Override
    public DescribeReservedNodesResult describeReservedNodes(DescribeReservedNodesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeReservedNodesResult describeReservedNodes() {
        return describeReservedNodes(new DescribeReservedNodesRequest());
    }

    @Override
    public DescribeResizeResult describeResize(DescribeResizeRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeSnapshotCopyGrantsResult describeSnapshotCopyGrants(DescribeSnapshotCopyGrantsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeSnapshotCopyGrantsResult describeSnapshotCopyGrants() {
        return describeSnapshotCopyGrants(new DescribeSnapshotCopyGrantsRequest());
    }

    @Override
    public DescribeTableRestoreStatusResult describeTableRestoreStatus(DescribeTableRestoreStatusRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeTableRestoreStatusResult describeTableRestoreStatus() {
        return describeTableRestoreStatus(new DescribeTableRestoreStatusRequest());
    }

    @Override
    public DescribeTagsResult describeTags(DescribeTagsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeTagsResult describeTags() {
        return describeTags(new DescribeTagsRequest());
    }

    @Override
    public DisableLoggingResult disableLogging(DisableLoggingRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster disableSnapshotCopy(DisableSnapshotCopyRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public EnableLoggingResult enableLogging(EnableLoggingRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster enableSnapshotCopy(EnableSnapshotCopyRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public GetClusterCredentialsResult getClusterCredentials(GetClusterCredentialsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster modifyCluster(ModifyClusterRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster modifyClusterIamRoles(ModifyClusterIamRolesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ModifyClusterParameterGroupResult modifyClusterParameterGroup(ModifyClusterParameterGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterSubnetGroup modifyClusterSubnetGroup(ModifyClusterSubnetGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public EventSubscription modifyEventSubscription(ModifyEventSubscriptionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster modifySnapshotCopyRetentionPeriod(ModifySnapshotCopyRetentionPeriodRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ReservedNode purchaseReservedNodeOffering(PurchaseReservedNodeOfferingRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster rebootCluster(RebootClusterRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ResetClusterParameterGroupResult resetClusterParameterGroup(ResetClusterParameterGroupRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster restoreFromClusterSnapshot(RestoreFromClusterSnapshotRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public TableRestoreStatus restoreTableFromClusterSnapshot(RestoreTableFromClusterSnapshotRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ClusterSecurityGroup revokeClusterSecurityGroupIngress(RevokeClusterSecurityGroupIngressRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Snapshot revokeSnapshotAccess(RevokeSnapshotAccessRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public Cluster rotateEncryptionKey(RotateEncryptionKeyRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public void shutdown() {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public com.amazonaws.ResponseMetadata getCachedResponseMetadata(com.amazonaws.AmazonWebServiceRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public AmazonRedshiftWaiters waiters() {
        throw new java.lang.UnsupportedOperationException();
    }

}


text:
#pragma once

#include "unittest.h"
#include <iostream>
#include <string>

class ConvertBase : public UnitTest
{
public:
    virtual TestResult test() override;

private:
    /*!
     * \brief Convert a number from one base to another.
     * \param baseIn The base that number is represented in
     * \param number The number to be converted
     * \param baseOut The new base to change the number into
     * \return The number after conversion to the new base
     */
    std::string convertBase(int baseIn, std::string number, int baseOut);
};


text:
comments: false
date: 2014-03-23T22:14:16Z
tags:
- terminal
- airline
- zsh
- prezto
- vim
title: Switch to Prezto and vim-airline
url: /blog/2014/03/23/switch-to-prezto-and-vim-airline/
---

I've been using [Oh-My-Zsh](http://ohmyz.sh/) and [Powerline](https://github.com/Lokaltog/powerline) for vim for a while now, but just recently converted to [Prezto](https://github.com/sorin-ionescu/prezto) and [vim-airline](https://github.com/bling/vim-airline), repectively, on word of the usability and performance improvements. Already, the benefits have been well worth the minimal effort required to set these up.

* __Note:__ anecdotally, the original switch from bash to zsh was quite easy - I understandably hear questions about this often.

With Prezto, two improvements stand out markedly:

1. Using the Oh-My-Zsh git plugin, I would often see a long lag time (_sometimes 5+ seconds!_) between cd'ing into a git repo and the appearance of the prompt - I'm kind of surprised I never traced that =/ In any case, Prezto is consistently near-instantaneous.
2. I had a reverse history search with Oh-My-Zsh that would check for the string ahead of the first space (i.e. `cd th` would show me any previous `cd` commands via the 'up' arrow). The Prezto reverse history search plugin does two or three better by letting me search for strings with spaces, 'cd' will match any command from history that had 'cd' anywhere in the entire command, and there is a nice highlight on each match.

With vim-airline, set-up and customization were an absolute breeze - especially compared to powerline, which is notoriously difficult to install.

So as you can tell, I'm sold. I haven't been this excited about the shell in at least months :)