text:
package advancedtls

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"sync"
	"testing"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/tls/certprovider"
	"google.golang.org/grpc/credentials/tls/certprovider/pemfile"
	pb "google.golang.org/grpc/examples/helloworld/helloworld"
	"google.golang.org/grpc/security/advancedtls/internal/testutils"
	"google.golang.org/grpc/security/advancedtls/testdata"
)

const (
	// Default timeout for normal connections.
	defaultTestTimeout = 5 * time.Second
	// Default timeout for failed connections.
	defaultTestShortTimeout = 10 * time.Millisecond
	// Intervals that set to monitor the credential updates.
	credRefreshingInterval = 200 * time.Millisecond
	// Time we wait for the credential updates to be picked up.
	sleepInterval = 400 * time.Millisecond
)

// stageInfo contains a stage number indicating the current phase of each
// integration test, and a mutex.
// Based on the stage number of current test, we will use different
// certificates and custom verification functions to check if our tests behave
// as expected.
type stageInfo struct {
	mutex sync.Mutex
	stage int
}

func (s *stageInfo) increase() {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	s.stage = s.stage + 1
}

func (s *stageInfo) read() int {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	return s.stage
}

func (s *stageInfo) reset() {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	s.stage = 0
}

type greeterServer struct {
	pb.UnimplementedGreeterServer
}

// sayHello is a simple implementation of the pb.GreeterServer SayHello method.
func (greeterServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

// TODO(ZhenLian): remove shouldFail to the function signature to provider
// tests.
func callAndVerify(msg string, client pb.GreeterClient, shouldFail bool) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err := client.SayHello(ctx, &pb.HelloRequest{Name: msg})
	if want, got := shouldFail == true, err != nil; got != want {
		return fmt.Errorf("want and got mismatch,  want shouldFail=%v, got fail=%v, rpc error: %v", want, got, err)
	}
	return nil
}

// TODO(ZhenLian): remove shouldFail and add ...DialOption to the function
// signature to provider cleaner tests.
func callAndVerifyWithClientConn(connCtx context.Context, address string, msg string, creds credentials.TransportCredentials, shouldFail bool) (*grpc.ClientConn, pb.GreeterClient, error) {
	var conn *grpc.ClientConn
	var err error
	// If we want the test to fail, we establish a non-blocking connection to
	// avoid it hangs and killed by the context.
	if shouldFail {
		conn, err = grpc.DialContext(connCtx, address, grpc.WithTransportCredentials(creds))
		if err != nil {
			return nil, nil, fmt.Errorf("client failed to connect to %s. Error: %v", address, err)
		}
	} else {
		conn, err = grpc.DialContext(connCtx, address, grpc.WithTransportCredentials(creds), grpc.WithBlock())
		if err != nil {
			return nil, nil, fmt.Errorf("client failed to connect to %s. Error: %v", address, err)
		}
	}
	greetClient := pb.NewGreeterClient(conn)
	err = callAndVerify(msg, greetClient, shouldFail)
	if err != nil {
		return nil, nil, err
	}
	return conn, greetClient, nil
}

// The advanced TLS features are tested in different stages.
// At stage 0, we establish a good connection between client and server.
// At stage 1, we change one factor(it could be we change the server's
// certificate, or custom verification function, etc), and test if the
// following connections would be dropped.
// At stage 2, we re-establish the connection by changing the counterpart of
// the factor we modified in stage 1.
// (could be change the client's trust certificate, or change custom
// verification function, etc)
func (s) TestEnd2End(t *testing.T) {
	cs := &testutils.CertStore{}
	if err := cs.LoadCerts(); err != nil {
		t.Fatalf("cs.LoadCerts() failed, err: %v", err)
	}
	stage := &stageInfo{}
	for _, test := range []struct {
		desc             string
		clientCert       []tls.Certificate
		clientGetCert    func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
		clientRoot       *x509.CertPool
		clientGetRoot    func(params *GetRootCAsParams) (*GetRootCAsResults, error)
		clientVerifyFunc CustomVerificationFunc
		clientVType      VerificationType
		serverCert       []tls.Certificate
		serverGetCert    func(*tls.ClientHelloInfo) ([]*tls.Certificate, error)
		serverRoot       *x509.CertPool
		serverGetRoot    func(params *GetRootCAsParams) (*GetRootCAsResults, error)
		serverVerifyFunc CustomVerificationFunc
		serverVType      VerificationType
	}{
		// Test Scenarios:
		// At initialization(stage = 0), client will be initialized with cert
		// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.
		// The mutual authentication works at the beginning, since ClientCert1 is
		// trusted by ServerTrust1, and ServerCert1 by ClientTrust1.
		// At stage 1, client changes ClientCert1 to ClientCert2. Since ClientCert2
		// is not trusted by ServerTrust1, following rpc calls are expected to
		// fail, while the previous rpc calls are still good because those are
		// already authenticated.
		// At stage 2, the server changes ServerTrust1 to ServerTrust2, and we
		// should see it again accepts the connection, since ClientCert2 is trusted
		// by ServerTrust2.
		{
			desc: "test the reloading feature for client identity callback and server trust callback",
			clientGetCert: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
				switch stage.read() {
				case 0:
					return &cs.ClientCert1, nil
				default:
					return &cs.ClientCert2, nil
				}
			},
			clientRoot: cs.ClientTrust1,
			clientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			clientVType: CertVerification,
			serverCert:  []tls.Certificate{cs.ServerCert1},
			serverGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {
				switch stage.read() {
				case 0, 1:
					return &GetRootCAsResults{TrustCerts: cs.ServerTrust1}, nil
				default:
					return &GetRootCAsResults{TrustCerts: cs.ServerTrust2}, nil
				}
			},
			serverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			serverVType: CertVerification,
		},
		// Test Scenarios:
		// At initialization(stage = 0), client will be initialized with cert
		// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.
		// The mutual authentication works at the beginning, since ClientCert1 is
		// trusted by ServerTrust1, and ServerCert1 by ClientTrust1.
		// At stage 1, server changes ServerCert1 to ServerCert2. Since ServerCert2
		// is not trusted by ClientTrust1, following rpc calls are expected to
		// fail, while the previous rpc calls are still good because those are
		// already authenticated.
		// At stage 2, the client changes ClientTrust1 to ClientTrust2, and we
		// should see it again accepts the connection, since ServerCert2 is trusted
		// by ClientTrust2.
		{
			desc:       "test the reloading feature for server identity callback and client trust callback",
			clientCert: []tls.Certificate{cs.ClientCert1},
			clientGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {
				switch stage.read() {
				case 0, 1:
					return &GetRootCAsResults{TrustCerts: cs.ClientTrust1}, nil
				default:
					return &GetRootCAsResults{TrustCerts: cs.ClientTrust2}, nil
				}
			},
			clientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			clientVType: CertVerification,
			serverGetCert: func(*tls.ClientHelloInfo) ([]*tls.Certificate, error) {
				switch stage.read() {
				case 0:
					return []*tls.Certificate{&cs.ServerCert1}, nil
				default:
					return []*tls.Certificate{&cs.ServerCert2}, nil
				}
			},
			serverRoot: cs.ServerTrust1,
			serverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			serverVType: CertVerification,
		},
		// Test Scenarios:
		// At initialization(stage = 0), client will be initialized with cert
		// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.
		// The mutual authentication works at the beginning, since ClientCert1
		// trusted by ServerTrust1, ServerCert1 by ClientTrust1, and also the
		// custom verification check allows the CommonName on ServerCert1.
		// At stage 1, server changes ServerCert1 to ServerCert2, and client
		// changes ClientTrust1 to ClientTrust2. Although ServerCert2 is trusted by
		// ClientTrust2, our authorization check only accepts ServerCert1, and
		// hence the following calls should fail. Previous connections should
		// not be affected.
		// At stage 2, the client changes authorization check to only accept
		// ServerCert2. Now we should see the connection becomes normal again.
		{
			desc:       "test client custom verification",
			clientCert: []tls.Certificate{cs.ClientCert1},
			clientGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {
				switch stage.read() {
				case 0:
					return &GetRootCAsResults{TrustCerts: cs.ClientTrust1}, nil
				default:
					return &GetRootCAsResults{TrustCerts: cs.ClientTrust2}, nil
				}
			},
			clientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				if len(params.RawCerts) == 0 {
					return nil, fmt.Errorf("no peer certs")
				}
				cert, err := x509.ParseCertificate(params.RawCerts[0])
				if err != nil || cert == nil {
					return nil, fmt.Errorf("failed to parse certificate: " + err.Error())
				}
				authzCheck := false
				switch stage.read() {
				case 0, 1:
					// foo.bar.com is the common name on ServerCert1
					if cert.Subject.CommonName == "foo.bar.com" {
						authzCheck = true
					}
				default:
					// foo.bar.server2.com is the common name on ServerCert2
					if cert.Subject.CommonName == "foo.bar.server2.com" {
						authzCheck = true
					}
				}
				if authzCheck {
					return &VerificationResults{}, nil
				}
				return nil, fmt.Errorf("custom authz check fails")
			},
			clientVType: CertVerification,
			serverGetCert: func(*tls.ClientHelloInfo) ([]*tls.Certificate, error) {
				switch stage.read() {
				case 0:
					return []*tls.Certificate{&cs.ServerCert1}, nil
				default:
					return []*tls.Certificate{&cs.ServerCert2}, nil
				}
			},
			serverRoot: cs.ServerTrust1,
			serverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			serverVType: CertVerification,
		},
		// Test Scenarios:
		// At initialization(stage = 0), client will be initialized with cert
		// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.
		// The mutual authentication works at the beginning, since ClientCert1
		// trusted by ServerTrust1, ServerCert1 by ClientTrust1, and also the
		// custom verification check on server side allows all connections.
		// At stage 1, server disallows the connections by setting custom
		// verification check. The following calls should fail. Previous
		// connections should not be affected.
		// At stage 2, server allows all the connections again and the
		// authentications should go back to normal.
		{
			desc:       "TestServerCustomVerification",
			clientCert: []tls.Certificate{cs.ClientCert1},
			clientRoot: cs.ClientTrust1,
			clientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				return &VerificationResults{}, nil
			},
			clientVType: CertVerification,
			serverCert:  []tls.Certificate{cs.ServerCert1},
			serverRoot:  cs.ServerTrust1,
			serverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {
				switch stage.read() {
				case 0, 2:
					return &VerificationResults{}, nil
				case 1:
					return nil, fmt.Errorf("custom authz check fails")
				default:
					return nil, fmt.Errorf("custom authz check fails")
				}
			},
			serverVType: CertVerification,
		},
	} {
		test := test
		t.Run(test.desc, func(t *testing.T) {
			// Start a server using ServerOptions in another goroutine.
			serverOptions := &ServerOptions{
				IdentityOptions: IdentityCertificateOptions{
					Certificates:                     test.serverCert,
					GetIdentityCertificatesForServer: test.serverGetCert,
				},
				RootOptions: RootCertificateOptions{
					RootCACerts:         test.serverRoot,
					GetRootCertificates: test.serverGetRoot,
				},
				RequireClientCert: true,
				VerifyPeer:        test.serverVerifyFunc,
				VType:             test.serverVType,
			}
			serverTLSCreds, err := NewServerCreds(serverOptions)
			if err != nil {
				t.Fatalf("failed to create server creds: %v", err)
			}
			s := grpc.NewServer(grpc.Creds(serverTLSCreds))
			defer s.Stop()
			lis, err := net.Listen("tcp", "localhost:0")
			if err != nil {
				t.Fatalf("failed to listen: %v", err)
			}
			defer lis.Close()
			addr := fmt.Sprintf("localhost:%v", lis.Addr().(*net.TCPAddr).Port)
			pb.RegisterGreeterServer(s, greeterServer{})
			go s.Serve(lis)
			clientOptions := &ClientOptions{
				IdentityOptions: IdentityCertificateOptions{
					Certificates:                     test.clientCert,
					GetIdentityCertificatesForClient: test.clientGetCert,
				},
				VerifyPeer: test.clientVerifyFunc,
				RootOptions: RootCertificateOptions{
					RootCACerts:         test.clientRoot,
					GetRootCertificates: test.clientGetRoot,
				},
				VType: test.clientVType,
			}
			clientTLSCreds, err := NewClientCreds(clientOptions)
			if err != nil {
				t.Fatalf("clientTLSCreds failed to create: %v", err)
			}
			// ------------------------Scenario 1------------------------------------
			// stage = 0, initial connection should succeed
			ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
			defer cancel()
			conn, greetClient, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 1", clientTLSCreds, false)
			if err != nil {
				t.Fatal(err)
			}
			defer conn.Close()
			// ----------------------------------------------------------------------
			stage.increase()
			// ------------------------Scenario 2------------------------------------
			// stage = 1, previous connection should still succeed
			err = callAndVerify("rpc call 2", greetClient, false)
			if err != nil {
				t.Fatal(err)
			}
			// ------------------------Scenario 3------------------------------------
			// stage = 1, new connection should fail
			shortCtx, shortCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
			defer shortCancel()
			conn2, greetClient, err := callAndVerifyWithClientConn(shortCtx, addr, "rpc call 3", clientTLSCreds, true)
			if err != nil {
				t.Fatal(err)
			}
			defer conn2.Close()
			// ----------------------------------------------------------------------
			stage.increase()
			// ------------------------Scenario 4------------------------------------
			// stage = 2,  new connection should succeed
			conn3, greetClient, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 4", clientTLSCreds, false)
			if err != nil {
				t.Fatal(err)
			}
			defer conn3.Close()
			// ----------------------------------------------------------------------
			stage.reset()
		})
	}
}

type tmpCredsFiles struct {
	clientCertTmp  *os.File
	clientKeyTmp   *os.File
	clientTrustTmp *os.File
	serverCertTmp  *os.File
	serverKeyTmp   *os.File
	serverTrustTmp *os.File
}

// Create temp files that are used to hold credentials.
func createTmpFiles() (*tmpCredsFiles, error) {
	tmpFiles := &tmpCredsFiles{}
	var err error
	tmpFiles.clientCertTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	tmpFiles.clientKeyTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	tmpFiles.clientTrustTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	tmpFiles.serverCertTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	tmpFiles.serverKeyTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	tmpFiles.serverTrustTmp, err = ioutil.TempFile(os.TempDir(), "pre-")
	if err != nil {
		return nil, err
	}
	return tmpFiles, nil
}

// Copy the credential contents to the temporary files.
func (tmpFiles *tmpCredsFiles) copyCredsToTmpFiles() error {
	if err := copyFileContents(testdata.Path("client_cert_1.pem"), tmpFiles.clientCertTmp.Name()); err != nil {
		return err
	}
	if err := copyFileContents(testdata.Path("client_key_1.pem"), tmpFiles.clientKeyTmp.Name()); err != nil {
		return err
	}
	if err := copyFileContents(testdata.Path("client_trust_cert_1.pem"), tmpFiles.clientTrustTmp.Name()); err != nil {
		return err
	}
	if err := copyFileContents(testdata.Path("server_cert_1.pem"), tmpFiles.serverCertTmp.Name()); err != nil {
		return err
	}
	if err := copyFileContents(testdata.Path("server_key_1.pem"), tmpFiles.serverKeyTmp.Name()); err != nil {
		return err
	}
	if err := copyFileContents(testdata.Path("server_trust_cert_1.pem"), tmpFiles.serverTrustTmp.Name()); err != nil {
		return err
	}
	return nil
}

func (tmpFiles *tmpCredsFiles) removeFiles() {
	os.Remove(tmpFiles.clientCertTmp.Name())
	os.Remove(tmpFiles.clientKeyTmp.Name())
	os.Remove(tmpFiles.clientTrustTmp.Name())
	os.Remove(tmpFiles.serverCertTmp.Name())
	os.Remove(tmpFiles.serverKeyTmp.Name())
	os.Remove(tmpFiles.serverTrustTmp.Name())
}

func copyFileContents(sourceFile, destinationFile string) error {
	input, err := ioutil.ReadFile(sourceFile)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(destinationFile, input, 0644)
	if err != nil {
		return err
	}
	return nil
}

// Create PEMFileProvider(s) watching the content changes of temporary
// files.
func createProviders(tmpFiles *tmpCredsFiles) (certprovider.Provider, certprovider.Provider, certprovider.Provider, certprovider.Provider, error) {
	clientIdentityOptions := pemfile.Options{
		CertFile:        tmpFiles.clientCertTmp.Name(),
		KeyFile:         tmpFiles.clientKeyTmp.Name(),
		RefreshDuration: credRefreshingInterval,
	}
	clientIdentityProvider, err := pemfile.NewProvider(clientIdentityOptions)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	clientRootOptions := pemfile.Options{
		RootFile:        tmpFiles.clientTrustTmp.Name(),
		RefreshDuration: credRefreshingInterval,
	}
	clientRootProvider, err := pemfile.NewProvider(clientRootOptions)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	serverIdentityOptions := pemfile.Options{
		CertFile:        tmpFiles.serverCertTmp.Name(),
		KeyFile:         tmpFiles.serverKeyTmp.Name(),
		RefreshDuration: credRefreshingInterval,
	}
	serverIdentityProvider, err := pemfile.NewProvider(serverIdentityOptions)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	serverRootOptions := pemfile.Options{
		RootFile:        tmpFiles.serverTrustTmp.Name(),
		RefreshDuration: credRefreshingInterval,
	}
	serverRootProvider, err := pemfile.NewProvider(serverRootOptions)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	return clientIdentityProvider, clientRootProvider, serverIdentityProvider, serverRootProvider, nil
}

// In order to test advanced TLS provider features, we used temporary files to
// hold credential data, and copy the contents under testdata/ to these tmp
// files.
// Initially, we establish a good connection with providers watching contents
// from tmp files.
// Next, we change the identity certs that IdentityProvider is watching. Since
// the identity key is not changed, the IdentityProvider should ignore the
// update, and the connection should still be good.
// Then the identity key is changed. This time IdentityProvider should pick
// up the update, and the connection should fail, due to the trust certs on the
// other side is not changed.
// Finally, the trust certs that other-side's RootProvider is watching get
// changed. The connection should go back to normal again.
func (s) TestPEMFileProviderEnd2End(t *testing.T) {
	tmpFiles, err := createTmpFiles()
	if err != nil {
		t.Fatalf("createTmpFiles() failed, error: %v", err)
	}
	defer tmpFiles.removeFiles()
	for _, test := range []struct {
		desc                string
		certUpdateFunc      func()
		keyUpdateFunc       func()
		trustCertUpdateFunc func()
	}{
		{
			desc: "test the reloading feature for clientIdentityProvider and serverTrustProvider",
			certUpdateFunc: func() {
				err = copyFileContents(testdata.Path("client_cert_2.pem"), tmpFiles.clientCertTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("client_cert_2.pem"), tmpFiles.clientCertTmp.Name(), err)
				}
			},
			keyUpdateFunc: func() {
				err = copyFileContents(testdata.Path("client_key_2.pem"), tmpFiles.clientKeyTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("client_key_2.pem"), tmpFiles.clientKeyTmp.Name(), err)
				}
			},
			trustCertUpdateFunc: func() {
				err = copyFileContents(testdata.Path("server_trust_cert_2.pem"), tmpFiles.serverTrustTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("server_trust_cert_2.pem"), tmpFiles.serverTrustTmp.Name(), err)
				}
			},
		},
		{
			desc: "test the reloading feature for serverIdentityProvider and clientTrustProvider",
			certUpdateFunc: func() {
				err = copyFileContents(testdata.Path("server_cert_2.pem"), tmpFiles.serverCertTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("server_cert_2.pem"), tmpFiles.serverCertTmp.Name(), err)
				}
			},
			keyUpdateFunc: func() {
				err = copyFileContents(testdata.Path("server_key_2.pem"), tmpFiles.serverKeyTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("server_key_2.pem"), tmpFiles.serverKeyTmp.Name(), err)
				}
			},
			trustCertUpdateFunc: func() {
				err = copyFileContents(testdata.Path("client_trust_cert_2.pem"), tmpFiles.clientTrustTmp.Name())
				if err != nil {
					t.Fatalf("copyFileContents(%s, %s) failed: %v", testdata.Path("client_trust_cert_2.pem"), tmpFiles.clientTrustTmp.Name(), err)
				}
			},
		},
	} {
		test := test
		t.Run(test.desc, func(t *testing.T) {
			if err := tmpFiles.copyCredsToTmpFiles(); err != nil {
				t.Fatalf("tmpFiles.copyCredsToTmpFiles() failed, error: %v", err)
			}
			clientIdentityProvider, clientRootProvider, serverIdentityProvider, serverRootProvider, err := createProviders(tmpFiles)
			if err != nil {
				t.Fatalf("createProviders(%v) failed, error: %v", tmpFiles, err)
			}
			defer clientIdentityProvider.Close()
			defer clientRootProvider.Close()
			defer serverIdentityProvider.Close()
			defer serverRootProvider.Close()
			// Start a server and create a client using advancedtls API with Provider.
			serverOptions := &ServerOptions{
				IdentityOptions: IdentityCertificateOptions{
					IdentityProvider: serverIdentityProvider,
				},
				RootOptions: RootCertificateOptions{
					RootProvider: serverRootProvider,
				},
				RequireClientCert: true,
				VerifyPeer: func(params *VerificationFuncParams) (*VerificationResults, error) {
					return &VerificationResults{}, nil
				},
				VType: CertVerification,
			}
			serverTLSCreds, err := NewServerCreds(serverOptions)
			if err != nil {
				t.Fatalf("failed to create server creds: %v", err)
			}
			s := grpc.NewServer(grpc.Creds(serverTLSCreds))
			defer s.Stop()
			lis, err := net.Listen("tcp", "localhost:0")
			if err != nil {
				t.Fatalf("failed to listen: %v", err)
			}
			defer lis.Close()
			addr := fmt.Sprintf("localhost:%v", lis.Addr().(*net.TCPAddr).Port)
			pb.RegisterGreeterServer(s, greeterServer{})
			go s.Serve(lis)
			clientOptions := &ClientOptions{
				IdentityOptions: IdentityCertificateOptions{
					IdentityProvider: clientIdentityProvider,
				},
				VerifyPeer: func(params *VerificationFuncParams) (*VerificationResults, error) {
					return &VerificationResults{}, nil
				},
				RootOptions: RootCertificateOptions{
					RootProvider: clientRootProvider,
				},
				VType: CertVerification,
			}
			clientTLSCreds, err := NewClientCreds(clientOptions)
			if err != nil {
				t.Fatalf("clientTLSCreds failed to create, error: %v", err)
			}

			// At initialization, the connection should be good.
			ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
			defer cancel()
			conn, greetClient, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 1", clientTLSCreds, false)
			if err != nil {
				t.Fatal(err)
			}
			defer conn.Close()
			// Make the identity cert change, and wait 1 second for the provider to
			// pick up the change.
			test.certUpdateFunc()
			time.Sleep(sleepInterval)
			// The already-established connection should not be affected.
			err = callAndVerify("rpc call 2", greetClient, false)
			if err != nil {
				t.Fatal(err)
			}
			// New connections should still be good, because the Provider didn't pick
			// up the changes due to key-cert mismatch.
			conn2, greetClient, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 3", clientTLSCreds, false)
			if err != nil {
				t.Fatal(err)
			}
			defer conn2.Close()
			// Make the identity key change, and wait 1 second for the provider to
			// pick up the change.
			test.keyUpdateFunc()
			time.Sleep(sleepInterval)
			// New connections should fail now, because the Provider picked the
			// change, and *_cert_2.pem is not trusted by *_trust_cert_1.pem on the
			// other side.
			shortCtx, shortCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
			defer shortCancel()
			conn3, greetClient, err := callAndVerifyWithClientConn(shortCtx, addr, "rpc call 4", clientTLSCreds, true)
			if err != nil {
				t.Fatal(err)
			}
			defer conn3.Close()
			// Make the trust cert change on the other side, and wait 1 second for
			// the provider to pick up the change.
			test.trustCertUpdateFunc()
			time.Sleep(sleepInterval)
			// New connections should be good, because the other side is using
			// *_trust_cert_2.pem now.
			conn4, greetClient, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 5", clientTLSCreds, false)
			if err != nil {
				t.Fatal(err)
			}
			defer conn4.Close()
		})
	}
}

func (s) TestDefaultHostNameCheck(t *testing.T) {
	cs := &testutils.CertStore{}
	if err := cs.LoadCerts(); err != nil {
		t.Fatalf("cs.LoadCerts() failed, err: %v", err)
	}
	for _, test := range []struct {
		desc             string
		clientRoot       *x509.CertPool
		clientVerifyFunc CustomVerificationFunc
		clientVType      VerificationType
		serverCert       []tls.Certificate
		serverVType      VerificationType
		expectError      bool
	}{
		// Client side sets vType to CertAndHostVerification, and will do
		// default hostname check. Server uses a cert without "localhost" or
		// "127.0.0.1" as common name or SAN names, and will hence fail.
		{
			desc:        "Bad default hostname check",
			clientRoot:  cs.ClientTrust1,
			clientVType: CertAndHostVerification,
			serverCert:  []tls.Certificate{cs.ServerCert1},
			serverVType: CertAndHostVerification,
			expectError: true,
		},
		// Client side sets vType to CertAndHostVerification, and will do
		// default hostname check. Server uses a certificate with "localhost" as
		// common name, and will hence pass the default hostname check.
		{
			desc:        "Good default hostname check",
			clientRoot:  cs.ClientTrust1,
			clientVType: CertAndHostVerification,
			serverCert:  []tls.Certificate{cs.ServerPeerLocalhost1},
			serverVType: CertAndHostVerification,
			expectError: false,
		},
	} {
		test := test
		t.Run(test.desc, func(t *testing.T) {
			// Start a server using ServerOptions in another goroutine.
			serverOptions := &ServerOptions{
				IdentityOptions: IdentityCertificateOptions{
					Certificates: test.serverCert,
				},
				RequireClientCert: false,
				VType:             test.serverVType,
			}
			serverTLSCreds, err := NewServerCreds(serverOptions)
			if err != nil {
				t.Fatalf("failed to create server creds: %v", err)
			}
			s := grpc.NewServer(grpc.Creds(serverTLSCreds))
			defer s.Stop()
			lis, err := net.Listen("tcp", "localhost:0")
			if err != nil {
				t.Fatalf("failed to listen: %v", err)
			}
			defer lis.Close()
			addr := fmt.Sprintf("localhost:%v", lis.Addr().(*net.TCPAddr).Port)
			pb.RegisterGreeterServer(s, greeterServer{})
			go s.Serve(lis)
			clientOptions := &ClientOptions{
				VerifyPeer: test.clientVerifyFunc,
				RootOptions: RootCertificateOptions{
					RootCACerts: test.clientRoot,
				},
				VType: test.clientVType,
			}
			clientTLSCreds, err := NewClientCreds(clientOptions)
			if err != nil {
				t.Fatalf("clientTLSCreds failed to create: %v", err)
			}
			shouldFail := false
			if test.expectError {
				shouldFail = true
			}
			ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
			defer cancel()
			conn, _, err := callAndVerifyWithClientConn(ctx, addr, "rpc call 1", clientTLSCreds, shouldFail)
			if err != nil {
				t.Fatal(err)
			}
			defer conn.Close()
		})
	}
}


text:
using namespace Utils;

RingBufferBase::RingBufferBase(int capacity) : writeOffset_(0), readOffset_(0), capacity_(capacity), size_(0)
{
    ;
}

int
RingBufferBase::getReadOffset()
{
    auto ro = readOffset_;
    readOffset_ = (ro + 1) % capacity_;
    return ro;
}

int
RingBufferBase::getWriteOffset()
{
    auto wo = writeOffset_;
    writeOffset_ = (wo + 1) % capacity_;
    return wo;
}

redpajama_set_name: RedPajamaGithub


text:
import os

import pandas as pd
from sklearn.model_selection import ShuffleSplit

import rampwf as rw

problem_title = 'Boston housing price regression'
_target_column_name = 'medv'
# A type (class) which will be used to create wrapper objects for y_pred
Predictions = rw.prediction_types.make_regression()
# An object implementing the workflow
workflow = rw.workflows.Regressor()

score_types = [
    rw.score_types.RMSE(),
    rw.score_types.RelativeRMSE(name='rel_rmse'),
    rw.score_types.NormalizedRMSE(name='n_rmse'),
]

def get_cv(X, y):
    cv = ShuffleSplit(n_splits=2, test_size=0.2, random_state=57)
    return cv.split(X)

def _read_data(path, f_name):
    data = pd.read_csv(os.path.join(path, 'data', f_name))
    y_array = data[_target_column_name].values
    X_array = data.drop([_target_column_name], axis=1).values
    return X_array, y_array

def get_train_data(path='.'):
    f_name = 'train.csv'
    return _read_data(path, f_name)

def get_test_data(path='.'):
    f_name = 'test.csv'
    return _read_data(path, f_name)


text:
using NUnit.Framework;
using Stylet.Xaml;
using System;
using System.Reflection;
using System.Windows;

namespace StyletUnitTests
{
    [TestFixture]
    public class EventActionTests
    {
        private class Subject : DependencyObject
        {
            // They're used by reflection - squish 'unused' warning
#pragma warning disable 0067
            public event EventHandler SimpleEventHandler;
            public event Action BadEventHandler;
            public event DependencyPropertyChangedEventHandler DependencyChangedEventHandler;
#pragma warning restore 0067
        }

        private class Target
        {
            public bool DoSomethingCalled;
            public void DoSomething()
            {
                this.DoSomethingCalled = true;
            }

            public void DoSomethingWithBadArgument(string arg)
            {
            }

            public void DoSomethingWithSenderAndBadArgument(object sender, object e)
            {
            }

            public void DoSomethingWithTooManyArguments(object sender, EventArgs e, object another)
            {
            }

            public EventArgs EventArgs;
            public void DoSomethingWithEventArgs(EventArgs ea)
            {
                this.EventArgs = ea;
            }

            public object Sender;
            public void DoSomethingWithObjectAndEventArgs(object sender, EventArgs e)
            {
                this.Sender = sender;
                this.EventArgs = e;
            }

            public DependencyPropertyChangedEventArgs DependencyChangedEventArgs;
            public void DoSomethingWithDependencyChangedEventArgs(DependencyPropertyChangedEventArgs e)
            {
                this.DependencyChangedEventArgs = e;
            }

            public void DoSomethingWithObjectAndDependencyChangedEventArgs(object sender, DependencyPropertyChangedEventArgs e)
            {
                this.Sender = sender;
                this.DependencyChangedEventArgs = e;
            }

            public void DoSomethingUnsuccessfully()
            {
                throw new InvalidOperationException("foo");
            }
        }

        private class Target2
        {
        }

        public class StaticTarget
        {
            public static bool DidSomething;
            public static void DoSomething() => DidSomething = true;
        }

        private DependencyObject subject;
        private Target target;
        private EventInfo eventInfo;
        private EventInfo dependencyChangedEventInfo;

        [SetUp]
        public void SetUp()
        {
            this.target = new Target();
            this.subject = new Subject();
            this.eventInfo = typeof(Subject).GetEvent("SimpleEventHandler");
            this.dependencyChangedEventInfo = typeof(Subject).GetEvent("DependencyChangedEventHandler");
            View.SetActionTarget(this.subject, this.target);
            StaticTarget.DidSomething = false;
        }

        [Test]
        public void ThrowsIfNullTargetBehaviourIsDisable()
        {
            Assert.Throws<ArgumentException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Disable, ActionUnavailableBehaviour.Enable));
        }

        [Test]
        public void ThrowsIfNonExistentActionBehaviourIsDisable()
        {
            Assert.Throws<ArgumentException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Disable));
        }

        [Test]
        public void ThrowsIfTargetNullBehaviourIsThrowAndTargetBecomesNull()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Enable);
            Assert.Throws<ActionTargetNullException>(() => View.SetActionTarget(this.subject, null));
        }

        [Test]
        public void ThrowsWhenClickedIfActionNonExistentBehaviourIsThrowAndActionIsNonExistent()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Throw);
            Assert.DoesNotThrow(() => View.SetActionTarget(this.subject, new Target2()));
            var e = Assert.Throws<TargetInvocationException>(() => cmd.GetDelegate().DynamicInvoke(null, new RoutedEventArgs()));
            Assert.IsInstanceOf<ActionNotFoundException>(e.InnerException);
        }

        [Test]
        public void ThrowsIfMethodHasTooManyArguments()
        {
            Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithTooManyArguments", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
        }

        [Test]
        public void ThrowsIfMethodHasBadParameter()
        {
            Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithBadArgument", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
        }

        [Test]
        public void ThrowsIfMethodHasBadEventArgsParameter()
        {
            Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithSenderAndBadArgument", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
        }

        [Test]
        public void ThrowsIfMethodHasTooManyParameters()
        {
            Assert.Throws<ActionSignatureInvalidException>(() => new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithTooManyArguments", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable));
        }

        [Test]
        public void InvokingCommandDoesNothingIfTargetIsNull()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            View.SetActionTarget(this.subject, null);
            cmd.GetDelegate().DynamicInvoke(null, null);
        }

        [Test]
        public void InvokingCommandDoesNothingIfActionIsNonExistent()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            View.SetActionTarget(this.subject, new Target2());
            cmd.GetDelegate().DynamicInvoke(null, null);
        }

        [Test]
        public void InvokingCommandCallsMethod()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            cmd.GetDelegate().DynamicInvoke(null, null);
            Assert.True(this.target.DoSomethingCalled);
        }

        [Test]
        public void InvokingCommandCallsMethodWithEventArgs()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            var arg = new RoutedEventArgs();
            cmd.GetDelegate().DynamicInvoke(null, arg);
            Assert.AreEqual(arg, this.target.EventArgs);
        }

        [Test]
        public void InvokingCommandCallsMethodWithSenderAndEventArgs()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingWithObjectAndEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            var sender = new object();
            var arg = new RoutedEventArgs();
            cmd.GetDelegate().DynamicInvoke(sender, arg);

            Assert.AreEqual(sender, this.target.Sender);
            Assert.AreEqual(arg, this.target.EventArgs);
        }

        [Test]
        public void InvokingCommandCallsMethodWithDependencyChangedEventArgs()
        {
            var cmd = new EventAction(this.subject, null, this.dependencyChangedEventInfo.EventHandlerType, "DoSomethingWithDependencyChangedEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            var arg = new DependencyPropertyChangedEventArgs();
            cmd.GetDelegate().DynamicInvoke(null, arg);
            Assert.AreEqual(arg, this.target.DependencyChangedEventArgs);
        }

        [Test]
        public void InvokingCommandCallsMethodWithSenderAndDependencyChangedEventArgs()
        {
            var cmd = new EventAction(this.subject, null, this.dependencyChangedEventInfo.EventHandlerType, "DoSomethingWithObjectAndDependencyChangedEventArgs", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            var sender = new object();
            var arg = new DependencyPropertyChangedEventArgs();
            cmd.GetDelegate().DynamicInvoke(sender, arg);

            Assert.AreEqual(sender, this.target.Sender);
            Assert.AreEqual(arg, this.target.DependencyChangedEventArgs);
        }

        [Test]
        public void BadEventHandlerSignatureThrows()
        {
            var cmd = new EventAction(this.subject, null, typeof(Subject).GetEvent("BadEventHandler").EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            Assert.Throws<ActionEventSignatureInvalidException>(() => cmd.GetDelegate());
        }

        [Test]
        public void PropagatesActionException()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomethingUnsuccessfully", ActionUnavailableBehaviour.Enable, ActionUnavailableBehaviour.Enable);
            var e = Assert.Throws<TargetInvocationException>(() => cmd.GetDelegate().DynamicInvoke(null, null));
            Assert.IsInstanceOf<InvalidOperationException>(e.InnerException);
            Assert.AreEqual("foo", e.InnerException.Message);
        }

        [Test]
        public void ExecuteThrowsIfActionTargetIsDefault()
        {
            View.SetActionTarget(this.subject, View.InitialActionTarget);
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);
            var e = Assert.Throws<TargetInvocationException>(() => cmd.GetDelegate().DynamicInvoke(null, null));
            Assert.IsInstanceOf<ActionNotSetException>(e.InnerException);
        }

        [Test]
        public void DoesNotRetainTarget()
        {
            WeakReference Test()
            {
                var view = new DependencyObject();
                View.SetActionTarget(view, this.target);
                var cmd = new EventAction(view, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);
                return new WeakReference(view);
            }

            var weakView = Test();

            GC.Collect();

            Assert.IsFalse(weakView.IsAlive);
        }

        [Test]
        public void OperatesAfterCollection()
        {
            var view = new DependencyObject();
            var cmd = new EventAction(view, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);

            GC.Collect();

            View.SetActionTarget(view, this.target);

            cmd.GetDelegate().DynamicInvoke(null, null);
            Assert.IsTrue(this.target.DoSomethingCalled);
        }

        [Test]
        public void UsesBackupSubjectIfActionTargetNotAvailable()
        {
            var view = new DependencyObject();
            var backupView = new DependencyObject();
            var cmd = new EventAction(view, backupView, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);

            View.SetActionTarget(backupView, this.target);
            view.SetValue(FrameworkElement.DataContextProperty, this.target);

            cmd.GetDelegate().DynamicInvoke(null, null);
            Assert.IsTrue(this.target.DoSomethingCalled);
        }

        [Test]
        public void SupportsStaticTargets()
        {
            var cmd = new EventAction(this.subject, null, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);
            View.SetActionTarget(this.subject, typeof(StaticTarget));

            cmd.GetDelegate().DynamicInvoke(null, null);
            Assert.True(StaticTarget.DidSomething);
        }

        [Test]
        public void UsesExplicitTarget()
        {
            var cmd = new EventAction(this.target, this.eventInfo.EventHandlerType, "DoSomething", ActionUnavailableBehaviour.Throw, ActionUnavailableBehaviour.Throw);
            cmd.GetDelegate().DynamicInvoke(null, null);
            Assert.True(this.target.DoSomethingCalled);
        }
    }
}


text:
/*
 A # symbol denotes that an element with a specific id should be styled.
*/

/* This styles the body element */
body {
    background-color: lightblue;

    /*
    Try typing to discover what can be styled using intellisense in Visual Studio code, or
    look up information on properties that can be styled.
    */

}

/* This styles elements of class "sectionHeadingStyle1" */
.sectionHeadingStyle1 {
    color: red;
}

/* This styles elements of class "sectionHeadingStyle2" */
.sectionHeadingStyle2 {
    color: purple;
}

/* This styles elements of class "sectionContent" */
.sectionContent {
    color: green
}


text:
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.tests.infrastructure.guards
{
    using System;
    using chocolatey.infrastructure.app.configuration;
    using chocolatey.infrastructure.guards;
    using Moq;
    using Should;

    public class EnsureSpecs
    {
        public abstract class EnsureSpecsBase : TinySpec
        {
            public override void Context()
            {
            }
        }

        public class when_Ensure_is_being_set_to_a_type : EnsureSpecsBase
        {
            private object result;
            private readonly string bob = "something";

            public override void Because()
            {
                result = Ensure.that(() => bob);
            }

            [Fact]
            public void should_return_a_type_of_string_for_ensuring()
            {
                result.ShouldBeType<Ensure<string>>();
            }

            [Fact]
            public void should_have_the_value_specified()
            {
                var bobEnsure = result as Ensure<string>;
                bobEnsure.Value.ShouldEqual(bob);
            }
        }

        public class when_using_Ensure : EnsureSpecsBase
        {
            public override void Because()
            {
            }

            [Fact]
            public void when_testing_a_string_against_is_not_null_should_pass()
            {
                string test = "value";
                Ensure.that(() => test).is_not_null();
            }

            [Fact]
            public void when_testing_a_null_string_against_is_not_null_should_throw_an_Argument_exception()
            {
                string test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).is_not_null();
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_a_Func_against_is_not_null_should_pass()
            {
                Func<string> test = () => "value";
                Ensure.that(() => test).is_not_null();
            }

            [Fact]
            public void when_testing_a_null_Func_against_is_not_null_should_throw_an_Argument_exception()
            {
                Func<string> test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).is_not_null();
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_a_class_against_is_not_null_should_pass()
            {
                var test = new ChocolateyConfiguration();
                Ensure.that(() => test).is_not_null();
            }

            [Fact]
            public void when_testing_an_uninstantiated_class_against_is_not_null_should_throw_an_Argument_exception()
            {
                ChocolateyConfiguration test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).is_not_null();
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_ensureFunction_against_string_value_should_throw_ArgumentNullException_on_ensureFunction()
            {
                string test = "bob";
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        null,
                        (name, value) => { throw new ApplicationException("this is what we throw."); });
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("Value for ensureFunction cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_exceptionAction_against_string_value_that_passes_should_throw_ArgumentNullException_on_exceptionAction()
            {
                string test = "bob";
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToLower(),
                        null);
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("exceptionAction");
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_exceptionAction_against_string_value_that_fails_should_throw_ArgumentNullException_on_exceptionAction()
            {
                string test = "bob";
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToUpper(),
                        null);
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("exceptionAction");
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_ensureFunction_against_null_value_should_throw_ArgumentNullException_on_ensureFunction()
            {
                string test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        null,
                        (name, value) => { throw new ApplicationException("this is what we throw."); });
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("ensureFunction");
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_exceptionAction_against_null_value_should_throw_ArgumentNullException_on_exceptionAction()
            {
                string test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToLower(),
                        null);
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("exceptionAction");
                exceptionMessage.ShouldContain("cannot be null.");
            }

            [Fact]
            public void when_testing_meets_with_null_everything_should_throw_ArgumentNullException_on_ensureFunction()
            {
                string test = null;
                object exceptionType = null;
                var exceptionMessage = string.Empty;
                try
                {
                    Ensure.that(() => test).meets(
                        null,
                        null);
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }

                exceptionType.ShouldBeType<ArgumentNullException>();
                exceptionMessage.ShouldContain("ensureFunction");
                exceptionMessage.ShouldContain("cannot be null.");
            }
        }

        public class when_testing_Ensure_meets_against_a_string_value_that_passes : EnsureSpecsBase
        {
            private object exceptionType;
            private string exceptionMessage = string.Empty;
            private bool exceptionActionInvoked;

            public override void Because()
            {
                string test = "bob";

                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToLower(),
                        (name, value) =>
                        {
                            exceptionActionInvoked = true;
                            throw new ApplicationException("this is what we throw.");
                        });
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }
            }

            [Fact]
            public void should_not_invoke_the_exceptionAction()
            {
                exceptionActionInvoked.ShouldBeFalse();
            }

            [Fact]
            public void should_not_return_a_specified_exception_since_there_was_no_failure()
            {
                exceptionType.ShouldBeNull();
            }

            [Fact]
            public void should_not_return_the_specified_error_message()
            {
                exceptionMessage.ShouldNotContain("this is what we throw.");
            }

            [Fact]
            public void should_not_log_an_error()
            {
                MockLogger.Verify(l => l.Error(It.IsAny<string>()), Times.Never);
            }
        }

        public class when_testing_Ensure_meets_against_a_string_value_that_fails : EnsureSpecsBase
        {
            private object exceptionType;
            private string exceptionMessage = string.Empty;
            private bool exceptionActionInvoked;

            public override void Because()
            {
                string test = "BOB";

                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToLower(),
                        (name, value) =>
                        {
                            exceptionActionInvoked = true;
                            throw new ApplicationException("this is what we throw.");
                        });
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }
            }

            [Fact]
            public void should_invoke_the_exceptionAction()
            {
                exceptionActionInvoked.ShouldBeTrue();
            }

            [Fact]
            public void should_return_the_specified_exception_of_type_ApplicationException()
            {
                exceptionType.ShouldBeType<ApplicationException>();
            }

            [Fact]
            public void should_return_the_specified_error_message()
            {
                exceptionMessage.ShouldContain("this is what we throw.");
            }

            [Fact]
            public void should_not_log_an_error()
            {
                MockLogger.Verify(l => l.Error(It.IsAny<string>()), Times.Never);
            }
        }

        public class when_testing_Ensure_meets_against_a_null_value_without_guarding_the_value : EnsureSpecsBase
        {
            private object exceptionType;
            private string exceptionMessage = string.Empty;
            private bool exceptionActionInvoked;

            public override void Because()
            {
                string test = null;

                try
                {
                    Ensure.that(() => test).meets(
                        s => s == s.ToLower(),
                        (name, value) =>
                        {
                            exceptionActionInvoked = true;
                            throw new ApplicationException("this is what we throw.");
                        });
                }
                catch (Exception ex)
                {
                    exceptionType = ex;
                    exceptionMessage = ex.Message;
                }
            }

            [Fact]
            public void should_not_invoke_the_exceptionAction()
            {
                exceptionActionInvoked.ShouldBeFalse();
            }

            [Fact]
            public void should_throw_an_error()
            {
                exceptionType.ShouldNotBeNull();
            }

            [Fact]
            public void should_not_return_the_specified_exception_of_type_ApplicationException()
            {
                exceptionType.ShouldNotBeType<ApplicationException>();
            }

            [Fact]
            public void should_not_return_the_specified_error_message()
            {
                exceptionMessage.ShouldNotContain("this is what we throw.");
            }

            //[Fact]
            //public void should_log_an_error()
            //{
            //    MockLogger.Verify(l => l.Error(It.IsAny<string>()), Times.Once);
            //}

            //    [Fact]
            //    public void should_log_the_error_we_expect()
            //    {
            //       var messages = MockLogger.MessagesFor(LogLevel.Error);
            //        messages.ShouldNotBeEmpty();
            //        messages.Count.ShouldEqual(1);
            //        messages[0].ShouldContain("Trying to call ensureFunction on");
            //    }
        }
    }
}


text:
using System;
using ReMi.Contracts.Cqrs.Commands;
using ReMi.Contracts.Cqrs.Queries;

namespace ReMi.Queries.Auth
{
    [Query("Get permissions for role", QueryGroup.AccessControl)]
    public class PermissionsRequest : IQuery
    {
        public QueryContext Context { get; set; }
        public Guid? RoleId { get; set; }

        public override string ToString()
        {
            return String.Format("[RoleId={0}, Context={1}]", RoleId, Context);
        }
    }
}


text:
Backend API example application featuring:
* REST endpoints
* Basic authentication (cookie)
* Authorization (roles)


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\Throwable\Exception\Generator\Resolver;

/**
 * @private
 */
final class RecursionLimitReachedExceptionFactory
{
    public static function create(int $limit, string $key): RecursionLimitReachedException
    {
        return new RecursionLimitReachedException(
            sprintf(
                'Recursion limit (%d tries) reached while resolving the parameter "%s"',
                $limit,
                $key
            )
        );
    }
}


text:
function scrollStepDefs(ch) {

    // one-time establishment of default settings
    ch.datasetsAvailable = 1;
    ch.useDensity = false;
    ch.triangleSetting = { x: 50, y: 50 };

    var baseDatasets = [ "mpg", "nba", "geyser" ];
    var laterDatasets = [ "mpg", "nba", "geyser", "diamonds", "marathons" ];

    var stepDefs = [
        { // draw value pool
        command: "gather data items",
        activate: function(chart) {
            // things that shouldn't survive a restart
            delete chart.highlightPathIndices;
            delete chart.highlightValueIndices;
            delete chart.binsAreDraggable;

            chart.datasetsForSwitching = baseDatasets;
            chart.drawDataSelector({ instant: true });
            chart.drawValueList({ stage: 0 });
            chart.drawDataUnits();
        }
        },

        { // move values across to list
        command: "sort items into list",
        replayable: true,
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            var options = targetStep===thisStep ? undefined : { stage: 1 };
            chart.drawValueList(options);
            }
        },

        { // draw a number line
        command: "draw a number line",
        replayable: true,
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);  // force completion of value list
            var options = targetStep===thisStep ? undefined : { instant: true };
            chart.drawColouredNumberLine(options);
            }
        },

        { // fly the values down to stacks on the number line
        label: "firstBalls",
        command: "place items on number line",
        replayable: true,
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);  // force completion of number line
            var options = targetStep===thisStep ? undefined : { instant: true };
            chart.flyBalls(options);
            },
        update: function(chart, progress) {
            // only change automatically on the first scroll through.  and once switch has been shown, don't reverse.
            if (progress < 0.25) return;

            if (chart.maximumScrolledIndex===stepIndex("firstBalls")) {
                var dataIndex = baseDatasets.indexOf(chart.dataName);

                if (progress > 0.5) dataIndex = baseDatasets.length-1;
                else if (progress > 0.25 && dataIndex===0) dataIndex = 1; // only increase

                if (chart.datasetsAvailable < dataIndex+1) {
                    chart.stopTimer();
                    chart.datasetsAvailable = dataIndex+1;
                    chart.loadData(baseDatasets[dataIndex]);
                    chart.replaySteps();
                }
            }
        }
        },

        { // drop the balls through to build up bins
        command: "portion items into bins",
        replayable: true,
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);  // force completion of ball stacks
            chart.datasetsAvailable = baseDatasets.length;
            chart.drawDataSelector({ instant: true });

            var options = targetStep===thisStep ? undefined : { instant: true };
            chart.drawRDefaultBinning(options);
            }
        },

        { // show the break values
        command: "show bin-break values",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);
            var options = targetStep===thisStep ? undefined : { instant: true };
            chart.drawBreakValues(options);
            }
        },

        { // move the bins through a sweep of offsets (relative to dataMin)
        command: "vary bin offset",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);
            chart.scenarioRecords = [];
            if (targetStep === thisStep) {
                chart.iterate(
                    lively.lang.arr.range(-100,0,20),
                    function(proportion) {
                        chart.drawRDefaultBinning({ instant: true, showLines: true, noScale: true, shiftProportion: proportion*0.01 });
                        chart.drawBreakValues({ instant: true });
                    }
                    );
                chart.drawCyclingScenarios(function(v) { return [
                    { text: "offset = bin width * " },
                    { text: String(-v), highlightOnChange: true },
                    { text: "%" }
                    ] });
            }
            }
        },

        { // move the bins through a sweep of widths (1.0 down to 0.5 of R default)
        command: "vary bin width",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer();
            if (targetStep === thisStep) {
                chart.iterate(
                    lively.lang.arr.range(100,50,-10),
                    function(proportion) {
                        chart.drawRDefaultBinning({ instant: true, showLines: true, noScale: true, shiftProportion: 0, widthProportion: proportion*0.01 });
                        chart.drawBreakValues({ instant: true });
                        }
                    );
                chart.drawCyclingScenarios(function(v)  { return [
                    { text: "bin width = " },
                    { text: String(v), highlightOnChange: true },
                    { text: "% of default" }
                    ] });
            }
            }
        },

        { // bring in the table...
        replayPoint: true,
        label: "firstTable",
        command: "show basic calculation",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            function definitions() {
                var binRounding = chart.dataBinDecimals;
                return [
                    { name: "width", main: lively.lang.num.roundTo(chart.dataRange/10, chart.dataBinQuantum).toFixed(binRounding), extra: lively.lang.arr.uniq(lively.lang.arr.range(25,10,-1).map(function(val) { return (chart.dataRange/val).toFixed(binRounding) })), rounding: binRounding },
                    { name: "breaks", main: "RANGE(dataMin, dataMax+width, width)", rounding: binRounding, styled: [
                        { style: "italic", text: "from ", colour: "grey" },
                        { style: "normal", text: "dataMin" },
                        { style: "italic", text: " to ", colour: "grey" },
                        { style: "normal", text: "dataMax+width" },
                        { style: "italic", text: " by ", colour: "grey" },
                        { style: "normal", text: "width" }
                        ] },
                    { name: "lefts", main: "ALL_BUT_LAST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but last of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
                    { name: "rights", main: "ALL_BUT_FIRST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but first of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
{ name: "open", main: '"L"', noDisplay: true },
{ name: "leftTests", main: 'i===0 ? "≥" : ">"', noDisplay: true },
{ name: "rightTests", main: '"≤" || i', noDisplay: true }, // hack: mention i to get an array
                    { name: "bins", main: "FILTER(data, lefts, rights, leftTests, rightTests, open)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "portion items based on ", colour: "grey" },
                            { style: "normal", text: "lefts, rights" }
                        ]},
                    { name: "counts", main: "COUNT(bins)",
                        styled: [
                            { style: "italic", text: "count items in ", colour: "grey" },
                            { style: "normal", text: "bins" }
                        ]}
//,{ name: "check", main: "SUM(counts)==data.length", reduce: true }
                    ];
            }

            // if previous steps have been given a chance to draw elements, clear them away
            if (prevRendered !== null) {
                chart.stopTimer();
                chart.clearMousetraps(["list", "flight", "ball"]);
                chart.highlightPathIndices([]);
                chart.highlightValueIndices([]);
                chart.clearDemoBins();
                chart.clearFixedCanvas();
                chart.clearEphemeralCanvas();
                // if we're landing here, keep the balls for now
                if (targetStep !== thisStep) chart.clearDemoBalls();
            } else { // no previous drawing, so fill in the elements that we need to be there
                chart.datasetsForSwitching = baseDatasets;
                chart.datasetsAvailable = baseDatasets.length;
                chart.drawDataSelector({ instant: true });
            }

            if (targetStep === thisStep) {
                chart.binsAreDraggable = false;
                chart.initHistogramArea({ instant: prevRendered===null }); // instant if no balls to shift
                chart.buildTable(definitions(), { noRanges: true });
            }
            }
        },

        { // more detail...
        command: "add bin offset",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            chart.stopTimer(true);  // make sure dataGroup reaches its target location

            if (targetStep !== thisStep) return;

            function definitions() {
                var binRounding = chart.dataBinDecimals;
                return [
                    { name: "width", main: lively.lang.num.roundTo(chart.dataRange/10, chart.dataBinQuantum).toFixed(binRounding), extra: lively.lang.arr.uniq(lively.lang.arr.range(25,10,-1).map(function(val) { return (chart.dataRange/val).toFixed(binRounding) })), rounding: binRounding },
                    { name: "offset", main: "0.0", extra: lively.lang.arr.range(-1,0.001,0.1).map(function(n) { return n.toFixed(1)}), rounding: 1 },
                    { name: "breaks", main: "RANGE(dataMin+offset*width, dataMax+width, width)", rounding: binRounding, styled: [
                        { style: "italic", text: "from ", colour: "grey" },
                        { style: "normal", text: "dataMin+width*offset" },
                        { style: "italic", text: " to ", colour: "grey" },
                        { style: "normal", text: "dataMax+width" },
                        { style: "italic", text: " by ", colour: "grey" },
                        { style: "normal", text: "width" }
                        ] },
                    { name: "lefts", main: "ALL_BUT_LAST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but last of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
                    { name: "rights", main: "ALL_BUT_FIRST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but first of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
{ name: "open", main: '"L"', noDisplay: true },
{ name: "leftTests", main: 'i===0 ? "≥" : ">"', noDisplay: true },
{ name: "rightTests", main: '"≤" || i', noDisplay: true }, // hack: mention i to get an array
                        { name: "bins", main: "FILTER(data, lefts, rights, leftTests, rightTests, open)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "portion items based on ", colour: "grey" },
                            { style: "normal", text: "lefts, rights" }
                        ]},
                    { name: "counts", main: "COUNT(bins)",
                        styled: [
                            { style: "italic", text: "count items in ", colour: "grey" },
                            { style: "normal", text: "bins" }
                        ]}
                    ];
            }

            chart.binsAreDraggable = true;
            chart.initHistogramArea({ instant: true });
            chart.buildTable(definitions(), { noRanges: true });
            }
        },

        { // and open/closed...
        command: "add bin openness",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            if (targetStep !== thisStep) return;
            function definitions() {
                var binRounding = chart.dataBinDecimals;
                return [
                    { name: "width", main: lively.lang.num.roundTo(chart.dataRange/10, chart.dataBinQuantum).toFixed(binRounding), extra: lively.lang.arr.uniq(lively.lang.arr.range(25,10,-1).map(function(val) { return (chart.dataRange/val).toFixed(binRounding)})), rounding: binRounding },
                    { name: "offset", main: "0.0", extra: lively.lang.arr.range(-1,0.001,0.1).map(function(n) { return n.toFixed(1) }), rounding: 1 },
                    { name: "breaks", main: "RANGE(dataMin+offset*width, dataMax+width, width)", rounding: binRounding, styled: [
                        { style: "italic", text: "from ", colour: "grey" },
                        { style: "normal", text: "dataMin+width*offset" },
                        { style: "italic", text: " to ", colour: "grey" },
                        { style: "normal", text: "dataMax+width" },
                        { style: "italic", text: " by ", colour: "grey" },
                        { style: "normal", text: "width" }
                        ] },
                    { name: "lefts", main: "ALL_BUT_LAST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but last of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
                    { name: "rights", main: "ALL_BUT_FIRST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but first of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
                    { name: "open", main: '"L"', extra: ['"L"', '"R"'] },
                    { name: "leftTests", main: 'open=="L" && i!=0 ? ">" : "≥"', styled: [
                        { style: "italic", text: "if ", colour: "grey" },
                        { style: "normal", text: "open" },
                        { style: "normal", text: " = " },
                        { style: "normal", text: '"L"' },
                        { style: "italic", text: " and ", colour: "grey" },
                        { style: "italic", text: "not first bin" },
                        { style: "italic", text: " then ", colour: "grey" },
                        { style: "normal", text: '">"' },
                        { style: "italic", text: " else ", colour: "grey" },
                        { style: "normal", text: '"≥"' }
                        ] },
                    { name: "rightTests", main: 'open=="R" && i!=iMax ? "<" : "≤"', styled: [
                        { style: "italic", text: "if ", colour: "grey" },
                        { style: "normal", text: "open" },
                        { style: "normal", text: " = " },
                        { style: "normal", text: '"R"' },
                        { style: "italic", text: " and ", colour: "grey" },
                        { style: "italic", text: "not last bin" },
                        { style: "italic", text: " then ", colour: "grey" },
                        { style: "normal", text: '"<"' },
                        { style: "italic", text: " else ", colour: "grey" },
                        { style: "normal", text: '"≤"' }
                        ] },
                    { name: "bins", main: "FILTER(data, lefts, rights, leftTests, rightTests, open)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "portion items based on ", colour: "grey" },
                            { style: "normal", text: "lefts, rights, leftTests, rightTests" }
                        ]},
                    { name: "counts", main: "COUNT(bins)",
                        styled: [
                            { style: "italic", text: "count items in ", colour: "grey" },
                            { style: "normal", text: "bins" }
                        ]}
                    ];
            }

            chart.binsAreDraggable = true;
            chart.initHistogramArea({ instant: true });
            chart.buildTable(definitions(), {});
            }
        },

        { // have a histogram without the table
        replayPoint: true,
        command: "just the histogram",
        activate: function(chart, originStep, prevRendered, targetStep, thisStep) {
            function definitions() {
                var binRounding = chart.dataBinDecimals;
                return [
                    { name: "width", main: lively.lang.num.roundTo(chart.dataRange/chart.minBinsOverRange, chart.dataBinQuantum).toFixed(binRounding), extra: lively.lang.arr.uniq(lively.lang.arr.range(chart.maxBinsOverRange,1,-1).map(function(bins) { return (bins===1 ? Math.ceil(chart.dataRange/chart.dataBinQuantum)*chart.dataBinQuantum : lively.lang.num.roundTo(chart.dataRange/bins, chart.dataBinQuantum)).toFixed(binRounding) })), rounding: binRounding },
                    { name: "offset", main: "0.0", extra: lively.lang.arr.range(-1,0.001,0.1).map(function(n) { return n.toFixed(1) }), rounding: 1 },
                    { name: "breaks", main: "RANGE(dataMin+offset*width, dataMax+width, width)", rounding: binRounding, styled: [
                        { style: "italic", text: "from ", colour: "grey" },
                        { style: "normal", text: "dataMin+width*offset" },
                        { style: "italic", text: " to ", colour: "grey" },
                        { style: "normal", text: "dataMax+width" },
                        { style: "italic", text: " by ", colour: "grey" },
                        { style: "normal", text: "width" }
                        ] },
                    { name: "lefts", main: "ALL_BUT_LAST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but last of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
                    { name: "rights", main: "ALL_BUT_FIRST(breaks)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "all but first of ", colour: "grey" },
                            { style: "normal", text: "breaks" }
                        ] },
{ name: "leftTests", main: 'i===0 ? "≥" : ">"', noDisplay: true },
{ name: "rightTests", main: '"≤" || i', noDisplay: true }, // hack: mention i to get an array
                    { name: "bins", main: "FILTER(data, lefts, rights, leftTests, rightTests)", reduce: true, rounding: binRounding,
                        styled: [
                            { style: "italic", text: "portion items based on ", colour: "grey" },
                            { style: "normal", text: "lefts, rights" }
                        ]},
                    { name: "counts", main: "COUNT(bins)",
                        styled: [
                            { style: "italic", text: "count items in ", colour: "grey" },
                            { style: "normal", text: "bins" }
                        ]}
                    ];
            }

            chart.datasetsForSwitching = laterDatasets;
            chart.datasetsAvailable = laterDatasets.length;
            chart.drawDataSelector({ instant: prevRendered===null });

            chart.binsAreDraggable = true;
            chart.initNakedHistogram({ instant: prevRendered===null || originStep<stepIndex("firstTable") });
            chart.buildTable(definitions(), { noVisibleTable: true, noDensity: true, widthControl: true, sweepControl: true, extraAxisValues: true });
            }
        }

        ];

    function stepIndex(label) { return stepDefs.findIndex(function(def) { return def.label===label }) || 0 }

    return stepDefs;
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('time_based', '0011_auto_20201028_0926'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='ongoingactivity',
            name='duration',
        ),
        migrations.AddField(
            model_name='ongoingactivity',
            name='duration',
            field=models.DurationField(blank=True, null=True, verbose_name='duration'),
        ),
        migrations.RemoveField(
            model_name='withadeadlineactivity',
            name='duration',
        ),

        migrations.AddField(
            model_name='withadeadlineactivity',
            name='duration',
            field=models.DurationField(blank=True, null=True, verbose_name='duration'),
        ),
    ]


text:
var NodeHelper = require("node_helper");

module.exports = NodeHelper.create({
	// Subclass start method.
	start: function() {
		var self = this;
		var events = [];

		this.fetchers = [];

		console.log("Starting node helper for: " + this.name);

	    this.expressApp.get('/statement', function (req, res) {
	        text = req.query.text
	        self.sendSocketNotification("STATEMENT", {"text":text})
	        res.sendStatus(200);
	    });

	    this.expressApp.post('/image', function (req, res) {
	    	var data = "";
   			req.on('data', function(chunk){ data += chunk})
   			req.on('end', function(){
       			req.rawBody = data;
       			req.jsonBody = JSON.parse(data);
       			url = req.jsonBody.url
       			console.log(url)
	        	self.sendSocketNotification("IMAGE", {"imageurl":url})
	        	res.sendStatus(200);
   			})
	    });

	    this.expressApp.post('/weather', function (req, res) {
	        var data = "";
   			req.on('data', function(chunk){ data += chunk})
   			req.on('end', function(){
       			req.rawBody = data;
       			req.jsonBody = JSON.parse(data);
	        	self.sendSocketNotification("WEATHER", req.jsonBody)
	        	res.sendStatus(200);
   			})
	    });

	    this.expressApp.get('/face', function (req, res) {
	        self.sendSocketNotification("FACE", {})
	        res.sendStatus(200);
	    });
	    this.expressApp.get('/creator', function (req, res) {
	        self.sendSocketNotification("CREATOR", {})
	        res.sendStatus(200);
	    });
	    this.expressApp.get('/Klaatu', function (req, res) {
	        self.sendSocketNotification("KLAATU", {})
	        res.sendStatus(200);
	    });

	    this.expressApp.post('/holidays', function (req, res) {
	        var data = "";
   			req.on('data', function(chunk){ data += chunk})
   			req.on('end', function(){
       			req.rawBody = data;
       			req.jsonBody = JSON.parse(data);
       			holiday = req.jsonBody.holiday
	        	self.sendSocketNotification("HOLIDAYS", {"holiday": holiday})
	        	res.sendStatus(200);
   			})
	    });

	    this.expressApp.post('/news', function (req, res) {
	       var data = "";
   			req.on('data', function(chunk){ data += chunk})
   			req.on('end', function(){
       			req.rawBody = data;
       			req.jsonBody = JSON.parse(data);
       			articles = req.jsonBody.articles
	        	self.sendSocketNotification("NEWS", {"articles":articles})
	        	res.sendStatus(200);
   			})
	    });

	    this.expressApp.get('/clear', function (req, res) {
	        text = req.query.text
	        self.sendSocketNotification("CLEAR", {})
	        res.sendStatus(200);
	    });

	},

	// Subclass socketNotificationReceived received.
	socketNotificationReceived: function(notification, payload) {
		console.log("helper received: " + notification)
	}
})


text:
import numpy as np
import logging
import time

class UnlockState(object):
    def __init__(self, state=None):
        super(UnlockState, self).__init__()
        self.state = state
        self.running = False

    def start(self):
        self.running = True

    def stop(self):
        self.running = False

    def is_stopped(self):
        return self.running

    def get_state(self):
        return self.state

    def process_command(self, command):
        ''' Subclass hook '''
        pass

class UnlockStateChain(UnlockState):
    def __init__(self, states):
        super(UnlockStateChain, self).__init__()
        self.states = states

    def start(self):
        for state in self.states:
            if state is not None:
                state.start()

    def stop(self):
        for state in self.states:
            if state is not None:
                state.stop()

    def process_command(self, command):
        for state in self.states:
            if state is not None:
                state.process_command(command)

class AlternatingBinaryState(UnlockState):
    def __init__(self, hold_duration=300):
        self.hold_duration = hold_duration
        self.state = True
        self.count = 0

    def get_state(self):
        ret = self.state
        self.count += 1
        if self.count % self.hold_duration == 0:
            self.state = not self.state
        return ret

class OfflineData(UnlockState):
    def __init__(self, output_file_prefix, cache_size=1):
        super(OfflineData, self).__init__()
        self.output_file_prefix = output_file_prefix
        self.file_handle = None
        self.logger = logging.getLogger(__name__)
        self.cache = list(range(cache_size))
        self.cache_size = cache_size
        self.current = 0
        self.last_invalid = 0
        self.invalid_count = 0

    def cache(self, command):
        self.cache[self.current] = command.matrix
        self.current = 0 if (self.current % self.cache_size) == 0 else self.current + 1

    def process_command(self, command):
        if self.file_handle is None:
            self.logger.warning("state not started")
            return

        if command.is_valid():
            np.savetxt(self.file_handle, command.matrix, fmt='%d', delimiter='\t')
        else:
            if (time.time() - self.last_invalid) < 1.5:
                self.invalid_count += 1
            else:
                msg = 'invalid command cannot be logged'
                if self.invalid_count > 0:
                    msg += '; logging attempted '+str(self.invalid_count)+' times in the last 1.5 secs'
                self.logger.warning(msg)
                self.invalid_count = 0
                self.last_invalid = time.time()
        #else:
            #XXX - hack for test
        #    a = np.array([0,0,0,0,0,0])
        #    a = np.hstack(a)
        #    np.savetxt(self.file_handle, a, fmt='%d', delimiter='\t')

    def get_state(self):
        raise NotImplementedError()

    def start(self):
        if self.file_handle is None:
            self.file_handle = open("%s_%d.txt" % (self.output_file_prefix, time.time()), 'wb')
        else:
            self.logger.warning("starting already stared state machine")

    def stop(self):
        if self.file_handle is None:
            self.logger.warning('state already stopped')
            return

        self.file_handle.flush()
        self.file_handle.close()
        self.file_handle = None

class OfflineTrialData(OfflineData):
    def __init__(self, output_file_prefix, cache_size=1):
        super(OfflineTrialData, self).__init__(output_file_prefix, cache_size)
        self.commands = []

    def process_command(self, command):
        assert self.file_handle != None
        if not command.is_valid():
            return

        if command.decision is not None:
            for i in self.commands:
                np.savetxt(self.file_handle, command.matrix, fmt='%d', delimiter='\t')
                self.cache(command)
                self.commands = []
        else:
            self.commands.append(command)

class NonBlockingOfflineData(UnlockState):
    def __init__(self):
        raise NotImplementedError()

class RunState(object):
    Stopped = 0
    Running = 1
    Resting = 2

    def __init__(self):
        self.state = RunState.Stopped

    def run(self):
        self.state = RunState.Running

    def rest(self):
        self.state = RunState.Resting

    def stop(self):
        self.state = RunState.Stopped

    def is_running(self):
        return self.state == RunState.Running

    def is_resting(self):
        return self.state == RunState.Resting

    def is_stopped(self):
        return self.state == RunState.Stopped

class TimerState(object):
    """
    A timer based off the variable time deltas coming from the system.
    In the event the timer duration is small i.e. < 100ms, jitter in the delta
    value can cause problems. Keeping the residual time instead of a full
    reset has been shown to have better accuracy in this case.
    """
    def __init__(self, duration):
        self.duration = float(duration)
        self.reset = lambda t: 0
        if self.duration < 0.1:
            self.reset = lambda t: t - self.duration
        self.elapsed = 0
        self.last_time = -1

    def begin_timer(self):
        # TODO: smarter time adjustment strategy
        self.elapsed = self.reset(self.elapsed)
        self.last_time = time.time()

    def update_timer(self, delta):
        self.elapsed += delta

    def is_complete(self):
        return self.elapsed >= self.duration

    def set_duration(self, duration):
        self.duration = float(duration)

class FrameCountTimerState(object):
    """
    A timer based off the variable time deltas coming from the system.
    In the event the timer duration is small i.e. < 100ms, jitter in the delta
    value can cause problems. Keeping the residual time instead of a full
    reset has been shown to have better accuracy in this case.
    """
    def __init__(self, duration_in_frames):
        assert duration_in_frames >= 1
        self.duration = int(60/int(duration_in_frames))
        self.elapsed = 0

    def begin_timer(self):
        self.elapsed = 0

    def update_timer(self, delta):
        self.elapsed += 1

    def is_complete(self):
        return self.elapsed >= self.duration

    def set_duration(self, duration_in_frames):
        self.duration = int(duration_in_frames)

# XXX this can be refactored.  there is no need for a rest state.  this can be implemented such
#     that the trials are 'stacked'.  then rests can be stacked with trials abstractly.  this
#     would help to optimize cases that have no rest condition; currently a bunch of statements are
#     processed to handle that case.
class TrialState(object):
    Unchanged = 0
    TrialExpiry = 1
    RestExpiry = 2

    def __init__(self, trial_timer, rest_timer, run_state):
        super(TrialState, self).__init__()
        self.trial_timer = trial_timer
        self.rest_timer = rest_timer
        self.run_state = run_state
        self.active_timer = self.trial_timer

        self.state_change = False
        self.last_change = TrialState.Unchanged

        def state_change_fn():
            change_value = TrialState.Unchanged
            if self.active_timer.is_complete():
                if self.run_state.is_running():
                    self.run_state.rest()
                    self.active_timer = self.rest_timer
                    change_value = TrialState.TrialExpiry
                elif self.run_state.is_resting():
                    self.run_state.run()
                    self.active_timer = self.trial_timer
                    change_value = TrialState.RestExpiry
                self.active_timer.begin_timer()
            if change_value != TrialState.Unchanged:
                self.state_change = True
                self.last_change = change_value
            return self.run_state.state, change_value

        self.update_state_table = state_change_fn

    def update_state(self, delta):
        self.active_timer.update_timer(delta)
        return self.update_state_table()

    def start(self):
        self.active_timer = self.trial_timer
        self.last_change = TrialState.Unchanged
        self.run_state.run()
        self.active_timer.begin_timer()

    def stop(self):
        self.run_state.stop()

    def is_stopped(self):
        return self.run_state.is_stopped()

    def get_state(self):
        if self.state_change:
            self.state_change = False
            ret = self.last_change
            self.last_change = TrialState.Unchanged
            return ret

class SequenceState(object):
    def __init__(self, sequence, value_transformer_fn=lambda x: x):
        self.sequence = sequence
        self.value_transformer_fn = value_transformer_fn
        self.index = 0

    def start(self):
        self.index = 0

    def step(self):
        self.index += 1
        if self.index == len(self.sequence):
            self.start()

    def state(self):
        return self.value_transformer_fn(self.sequence[self.index])

    def is_start(self):
        if self.index == 0:
            return True
        else:
            return False

    def is_end(self):
        if self.index+1 == len(self.sequence):
            return True