text:
package main

import (
	"fmt"
	"net"
	"testing"
	"time"

	"encoding/base64"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/hyperledger/fabric/core/chaincode"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/chaincode/shim/crypto/attr"
	"github.com/hyperledger/fabric/core/container"
	"github.com/hyperledger/fabric/core/crypto"
	"github.com/hyperledger/fabric/core/ledger"
	"github.com/hyperledger/fabric/membersrvc/ca"
	pb "github.com/hyperledger/fabric/protos"
	"github.com/op/go-logging"
	"github.com/spf13/viper"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"

	"reflect"
)

const (
	chaincodeStartupTimeoutDefault int = 5000
)

var (
	testLogger = logging.MustGetLogger("test")

	lis net.Listener

	administrator crypto.Client
	alice         crypto.Client
	bob           crypto.Client

	server *grpc.Server
	aca    *ca.ACA
	eca    *ca.ECA
	tca    *ca.TCA
	tlsca  *ca.TLSCA
)

func TestMain(m *testing.M) {
	removeFolders()
	setup()
	go initMembershipSrvc()

	fmt.Println("Wait for some secs for OBCCA")
	time.Sleep(2 * time.Second)

	go initVP()

	fmt.Println("Wait for some secs for VP")
	time.Sleep(2 * time.Second)

	go initAssetManagementChaincode()

	fmt.Println("Wait for some secs for Chaincode")
	time.Sleep(2 * time.Second)

	if err := initClients(); err != nil {
		panic(err)
	}

	fmt.Println("Wait for 10 secs for chaincode to be started")
	time.Sleep(10 * time.Second)

	ret := m.Run()

	closeListenerAndSleep(lis)

	defer removeFolders()
	os.Exit(ret)
}

func TestAssetManagement(t *testing.T) {
	// Administrator deploy the chaicode
	adminCert, err := administrator.GetTCertificateHandlerNext("role")
	if err != nil {
		t.Fatal(err)
	}

	if err := deploy(adminCert); err != nil {
		t.Fatal(err)
	}

	// Administrator assigns ownership of Picasso to Alice
	aliceCert, err := alice.GetTCertificateHandlerNext("role", "account")
	if err != nil {
		t.Fatal(err)
	}

	// This must fail
	if err := assignOwnership(alice, "Picasso", aliceCert); err == nil {
		t.Fatal("Alice doesn't have the assigner role. Assignment should fail.")
	}

	// This must succeed
	if err := assignOwnership(administrator, "Picasso", aliceCert); err != nil {
		t.Fatal(err)
	}

	// Check who is the owner of the Picasso
	theOnwerIs, err := whoIsTheOwner("Picasso")
	if err != nil {
		t.Fatal(err)
	}

	aliceAccount, err := attr.GetValueFrom("account", aliceCert.GetCertificate())
	if !reflect.DeepEqual(theOnwerIs, aliceAccount) {
		fmt.Printf("%v --- %v", string(theOnwerIs), string(aliceAccount))
		t.Fatal("Alice is not the owner of Picasso")
	}

	// Alice transfers ownership of Picasso to Bob
	bobCert, err := bob.GetTCertificateHandlerNext("role", "account")
	if err != nil {
		t.Fatal(err)
	}

	// This must fail
	if err := transferOwnership(bob, bobCert, "Picasso", adminCert); err == nil {
		t.Fatal(err)
	}

	// This must succeed
	if err := transferOwnership(alice, aliceCert, "Picasso", bobCert); err != nil {
		t.Fatal(err)
	}

	// Check who is the owner of the Picasso
	theOnwerIs, err = whoIsTheOwner("Picasso")
	if err != nil {
		t.Fatal(err)
	}

	bobAccount, err := attr.GetValueFrom("account", bobCert.GetCertificate())
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(theOnwerIs, bobAccount) {
		t.Fatal("Bob is not the owner of Picasso")
	}

	// Check who is the owner of an asset that doesn't exist
	_, err = whoIsTheOwner("Klee")
	if err == nil {
		t.Fatal("This asset doesn't exist. Querying should fail.")
	}
}

func deploy(admCert crypto.CertificateHandler) error {
	// Prepare the spec. The metadata includes the role of the users allowed to assign assets
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: "mycc"},
		CtorMsg:              &pb.ChaincodeInput{Function: "init", Args: []string{}},
		Metadata:             []byte("assigner"),
		ConfidentialityLevel: pb.ConfidentialityLevel_PUBLIC,
	}

	// First build and get the deployment spec
	var ctx = context.Background()
	chaincodeDeploymentSpec, err := getDeploymentSpec(ctx, spec)
	if err != nil {
		return err
	}

	tid := chaincodeDeploymentSpec.ChaincodeSpec.ChaincodeID.Name

	// Now create the Transactions message and send to Peer.
	transaction, err := administrator.NewChaincodeDeployTransaction(chaincodeDeploymentSpec, tid)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	ledger, err := ledger.GetLedger()
	ledger.BeginTxBatch("1")
	_, _, err = chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s", err)
	}
	ledger.CommitTxBatch("1", []*pb.Transaction{transaction}, nil, nil)

	return err
}

func assignOwnership(assigner crypto.Client, asset string, newOwnerCert crypto.CertificateHandler) error {
	// Get a transaction handler to be used to submit the execute transaction
	// and bind the chaincode access control logic using the binding
	submittingCertHandler, err := assigner.GetTCertificateHandlerNext("role")
	if err != nil {
		return err
	}
	txHandler, err := submittingCertHandler.GetTransactionHandler()
	if err != nil {
		return err
	}

	newOwner := base64.StdEncoding.EncodeToString(newOwnerCert.GetCertificate())
	chaincodeInput := &pb.ChaincodeInput{Function: "assign", Args: []string{asset, newOwner}}

	// Prepare spec and submit
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: "mycc"},
		CtorMsg:              chaincodeInput,
		ConfidentialityLevel: pb.ConfidentialityLevel_PUBLIC,
	}

	var ctx = context.Background()
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	tid := chaincodeInvocationSpec.ChaincodeSpec.ChaincodeID.Name

	// Now create the Transactions message and send to Peer.
	transaction, err := txHandler.NewChaincodeExecute(chaincodeInvocationSpec, tid)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	ledger, err := ledger.GetLedger()
	ledger.BeginTxBatch("1")
	_, _, err = chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s", err)
	}
	ledger.CommitTxBatch("1", []*pb.Transaction{transaction}, nil, nil)

	return err
}

func transferOwnership(owner crypto.Client, ownerCert crypto.CertificateHandler, asset string, newOwnerCert crypto.CertificateHandler) error {
	// Get a transaction handler to be used to submit the execute transaction
	// and bind the chaincode access control logic using the binding

	submittingCertHandler, err := owner.GetTCertificateHandlerNext("role", "account")
	if err != nil {
		return err
	}
	txHandler, err := submittingCertHandler.GetTransactionHandler()
	if err != nil {
		return err
	}

	newOwner := base64.StdEncoding.EncodeToString(newOwnerCert.GetCertificate())
	chaincodeInput := &pb.ChaincodeInput{Function: "transfer", Args: []string{asset, newOwner}}

	// Prepare spec and submit
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: "mycc"},
		CtorMsg:              chaincodeInput,
		ConfidentialityLevel: pb.ConfidentialityLevel_PUBLIC,
	}

	var ctx = context.Background()
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	tid := chaincodeInvocationSpec.ChaincodeSpec.ChaincodeID.Name

	// Now create the Transactions message and send to Peer.
	transaction, err := txHandler.NewChaincodeExecute(chaincodeInvocationSpec, tid)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	ledger, err := ledger.GetLedger()
	ledger.BeginTxBatch("1")
	_, _, err = chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
	if err != nil {
		return fmt.Errorf("Error deploying chaincode: %s", err)
	}
	ledger.CommitTxBatch("1", []*pb.Transaction{transaction}, nil, nil)

	return err

}

func whoIsTheOwner(asset string) ([]byte, error) {
	chaincodeInput := &pb.ChaincodeInput{Function: "query", Args: []string{asset}}

	// Prepare spec and submit
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: "mycc"},
		CtorMsg:              chaincodeInput,
		ConfidentialityLevel: pb.ConfidentialityLevel_PUBLIC,
	}

	var ctx = context.Background()
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	tid := chaincodeInvocationSpec.ChaincodeSpec.ChaincodeID.Name

	// Now create the Transactions message and send to Peer.
	transaction, err := administrator.NewChaincodeQuery(chaincodeInvocationSpec, tid)
	if err != nil {
		return nil, fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	ledger, err := ledger.GetLedger()
	ledger.BeginTxBatch("1")
	result, _, err := chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
	if err != nil {
		return nil, fmt.Errorf("Error deploying chaincode: %s", err)
	}
	ledger.CommitTxBatch("1", []*pb.Transaction{transaction}, nil, nil)

	return result, err
}

func setup() {
	// Conf
	viper.SetConfigName("asset") // name of config file (without extension)
	viper.AddConfigPath(".")     // path to look for the config file in
	err := viper.ReadInConfig()  // Find and read the config file
	if err != nil {              // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s] \n", err))
	}

	// Logging
	var formatter = logging.MustStringFormatter(
		`%{color}[%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logging.SetFormatter(formatter)

	logging.SetLevel(logging.DEBUG, "peer")
	logging.SetLevel(logging.DEBUG, "chaincode")
	logging.SetLevel(logging.DEBUG, "cryptochain")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	removeFolders()
}

func initMembershipSrvc() {
	ca.LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout)
	ca.CacheConfiguration() // Cache configuration
	aca = ca.NewACA()
	eca = ca.NewECA()
	tca = ca.NewTCA(eca)
	tlsca = ca.NewTLSCA(eca)

	var opts []grpc.ServerOption
	if viper.GetBool("peer.pki.tls.enabled") {
		// TLS configuration
		creds, err := credentials.NewServerTLSFromFile(
			filepath.Join(viper.GetString("server.rootpath"), "tlsca.cert"),
			filepath.Join(viper.GetString("server.rootpath"), "tlsca.priv"),
		)
		if err != nil {
			panic("Failed creating credentials for Membersrvc: " + err.Error())
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}

	fmt.Printf("open socket...\n")
	sockp, err := net.Listen("tcp", viper.GetString("server.port"))
	if err != nil {
		panic("Cannot open port: " + err.Error())
	}
	fmt.Printf("open socket...done\n")

	server = grpc.NewServer(opts...)

	aca.Start(server)
	eca.Start(server)
	tca.Start(server)
	tlsca.Start(server)

	fmt.Printf("start serving...\n")
	server.Serve(sockp)
}

func initVP() {
	var opts []grpc.ServerOption
	if viper.GetBool("peer.tls.enabled") {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file"))
		if err != nil {
			grpclog.Fatalf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)

	//lis, err := net.Listen("tcp", viper.GetString("peer.address"))

	//use a different address than what we usually use for "peer"
	//we override the peerAddress set in chaincode_support.go
	peerAddress := "0.0.0.0:40404"
	var err error
	lis, err = net.Listen("tcp", peerAddress)
	if err != nil {
		return
	}

	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
		return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil
	}

	ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond
	userRunsCC := true

	// Install security object for peer
	var secHelper crypto.Peer
	if viper.GetBool("security.enabled") {
		enrollID := viper.GetString("security.enrollID")
		enrollSecret := viper.GetString("security.enrollSecret")
		var err error

		if viper.GetBool("peer.validator.enabled") {
			testLogger.Debugf("Registering validator with enroll ID: %s", enrollID)
			if err = crypto.RegisterValidator(enrollID, nil, enrollID, enrollSecret); nil != err {
				panic(err)
			}
			testLogger.Debugf("Initializing validator with enroll ID: %s", enrollID)
			secHelper, err = crypto.InitValidator(enrollID, nil)
			if nil != err {
				panic(err)
			}
		} else {
			testLogger.Debugf("Registering non-validator with enroll ID: %s", enrollID)
			if err = crypto.RegisterPeer(enrollID, nil, enrollID, enrollSecret); nil != err {
				panic(err)
			}
			testLogger.Debugf("Initializing non-validator with enroll ID: %s", enrollID)
			secHelper, err = crypto.InitPeer(enrollID, nil)
			if nil != err {
				panic(err)
			}
		}
	}

	pb.RegisterChaincodeSupportServer(grpcServer,
		chaincode.NewChaincodeSupport(chaincode.DefaultChain, getPeerEndpoint, userRunsCC,
			ccStartupTimeout, secHelper))

	grpcServer.Serve(lis)
}

func initAssetManagementChaincode() {
	err := shim.Start(new(AssetManagementChaincode))
	if err != nil {
		panic(err)
	}
}

func initClients() error {
	// Administrator
	if err := crypto.RegisterClient("admin", nil, "admin", "6avZQLwcUe9b"); err != nil {
		return err
	}
	var err error
	administrator, err = crypto.InitClient("admin", nil)
	if err != nil {
		return err
	}

	// Alice
	if err := crypto.RegisterClient("alice", nil, "alice", "NPKYL39uKbkj"); err != nil {
		return err
	}
	alice, err = crypto.InitClient("alice", nil)
	if err != nil {
		return err
	}

	// Bob
	if err := crypto.RegisterClient("bob", nil, "bob", "DRJ23pEQl16a"); err != nil {
		return err
	}
	bob, err = crypto.InitClient("bob", nil)
	if err != nil {
		return err
	}

	return nil
}

func closeListenerAndSleep(l net.Listener) {
	l.Close()
	time.Sleep(2 * time.Second)
}

func getDeploymentSpec(context context.Context, spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {
	fmt.Printf("getting deployment spec for chaincode spec: %v\n", spec)
	var codePackageBytes []byte
	//if we have a name, we don't need to deploy (we are in userRunsCC mode)
	if spec.ChaincodeID.Name == "" {
		var err error
		codePackageBytes, err = container.GetChaincodePackageBytes(spec)
		if err != nil {
			return nil, err
		}
	}
	chaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}
	return chaincodeDeploymentSpec, nil
}

func removeFolders() {
	if err := os.RemoveAll(viper.GetString("peer.fileSystemPath")); err != nil {
		fmt.Printf("Failed removing [%s] [%s]\n", "hyperledger", err)
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables #-}
-- | An ODBC backend for persistent.
module Database.Persist.ODBC
    ( withODBCPool
    , withODBCConn
    , createODBCPool
    , module Database.Persist.Sql
    , ConnectionString
    , OdbcConf (..)
    , openSimpleConn
    ) where

import qualified Control.Exception as E -- (catch, SomeException)
import Database.Persist.Sql
{-
 - hiding (Entity (..))
import Database.Persist.Store
import Database.Persist.GenericSql hiding (Key)
import Database.Persist.GenericSql.Internal
import Database.Persist.EntityDef
-}
import Data.Time(ZonedTime(..), LocalTime(..), Day(..))

import qualified Database.HDBC.ODBC as O
import qualified Database.HDBC as O
import qualified Database.HDBC.SqlValue as HSV
import qualified Data.Convertible as DC

import Control.Monad.IO.Class (MonadIO (..))
import Data.List (intercalate)
import Data.IORef(newIORef)
import qualified Data.Map as Map
import Data.Conduit(Source, yield, MonadBaseControl, MonadResource, bracketP)

-- import Data.ByteString (ByteString)
-- import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
-- import qualified Data.Text.Encoding as T
import Data.Time.LocalTime (localTimeToUTC, utc)
import Data.Text (Text, pack)
import Data.Aeson -- (Object(..), (.:))
import Control.Monad (mzero)
import Data.Int (Int64)

-- | An @HDBC-odbc@ connection string.  A simple example of connection
-- string would be @DSN=hdbctest1@.
type ConnectionString = String

-- | Create an ODBC connection pool and run the given
-- action.  The pool is properly released after the action
-- finishes using it.  Note that you should not use the given
-- 'ConnectionPool' outside the action since it may be already
-- been released.
withODBCPool :: MonadIO m
             => ConnectionString
             -- ^ Connection string to the database.
             -> Int
             -- ^ Number of connections to be kept open in
             -- the pool.
             -> (ConnectionPool -> m a)
             -- ^ Action to be executed that uses the
             -- connection pool.
             -> m a
withODBCPool ci = withSqlPool $ open' ci

-- | Create an ODBC connection pool.  Note that it's your
-- responsability to properly close the connection pool when
-- unneeded.  Use 'withODBCPool' for an automatic resource
-- control.
createODBCPool :: MonadIO m
               => ConnectionString
               -- ^ Connection string to the database.
               -> Int
               -- ^ Number of connections to be kept open
               -- in the pool.
               -> m ConnectionPool
createODBCPool ci = createSqlPool $ open' ci

-- | Same as 'withODBCPool', but instead of opening a pool
-- of connections, only one connection is opened.
withODBCConn :: (MonadIO m, MonadBaseControl IO m)
             => ConnectionString -> (Connection -> m a) -> m a
withODBCConn = withSqlConn . open'

open' :: ConnectionString -> IO Connection
open' cstr = do
    O.connectODBC cstr >>= openSimpleConn

-- | Generate a persistent 'Connection' from an odbc 'O.Connection'
openSimpleConn :: O.Connection -> IO Connection
openSimpleConn conn = do
    smap <- newIORef $ Map.empty
    return Connection
        { connPrepare       = prepare' conn
        , connStmtMap       = smap
        , connInsertSql     = insertSql'
        , connClose         = O.disconnect conn
        , connMigrateSql    = migrate'
        , connBegin         = const
                     $ E.catch (O.commit conn) (\(_ :: E.SomeException) -> return ())
            -- there is no nested transactions.
            -- Transaction begining means that previous commited
        , connCommit        = const $ O.commit   conn
        , connRollback      = const $ O.rollback conn
        , connEscapeName    = escape
        , connNoLimit       = "" -- "LIMIT ALL"
        , connRDBMS         = "odbc" -- ?
        }

prepare' :: O.Connection -> Text -> IO Statement
prepare' conn sql = do
#if DEBUG
    putStrLn $ "Database.Persist.ODBC.prepare': sql = " ++ T.unpack sql
#endif
    stmt <- O.prepare conn $ T.unpack sql

    return Statement
        { stmtFinalize  = O.finish stmt
        , stmtReset     = return () -- rollback conn ?
        , stmtExecute   = execute' stmt
        , stmtQuery     = withStmt' stmt
        }

insertSql' :: DBName -> [DBName] -> DBName -> InsertSqlResult
insertSql' t cols id' = ISRSingle $ pack $ concat
    [ "INSERT INTO "
    , T.unpack $ escape t
    , "("
    , intercalate "," $ map (T.unpack . escape) cols
    , ") VALUES("
    , intercalate "," (map (const "?") cols)
    , ") RETURNING "
    , T.unpack $ escape id'
    ]

execute' :: O.Statement -> [PersistValue] -> IO Int64
execute' query vals = fmap fromInteger $ O.execute query $ map (HSV.toSql . P) vals

withStmt' :: MonadResource m
          => O.Statement
          -> [PersistValue]
          -> Source m [PersistValue]
withStmt' stmt vals = do
#if DEBUG
    liftIO $ putStrLn $ "withStmt': vals: " ++ show vals
#endif
    bracketP openS closeS pull
  where
    openS       = execute' stmt vals >> return ()
    closeS _    = O.finish stmt
    pull x      = do
        mr <- liftIO $ O.fetchRow stmt
        maybe (return ())
              (\r -> do
#if DEBUG
                    liftIO $ putStrLn $ "withStmt': yield: " ++ show r
                    liftIO $ putStrLn $ "withStmt': yield2: " ++ show (map (unP . HSV.fromSql) r)
#endif
                    yield (map (unP . HSV.fromSql) r)
                    pull x
              )
              mr

escape :: DBName -> Text
escape (DBName s) =
    T.pack $ {- '"' : -} go (T.unpack s) {- ++ "\""-}
  where
    go "" = ""
    go ('"':xs) = "\"\"" ++ go xs
    go (x:xs) = x : go xs

-- | Information required to connect to a PostgreSQL database
-- using @persistent@'s generic facilities.  These values are the
-- same that are given to 'withODBCPool'.
data OdbcConf = OdbcConf
    { odbcConnStr  :: ConnectionString
      -- ^ The connection string.
    , odbcPoolSize :: Int
      -- ^ How many connections should be held on the connection pool.
    }

instance PersistConfig OdbcConf where
    type PersistConfigBackend OdbcConf = SqlPersistT
    type PersistConfigPool OdbcConf = ConnectionPool
    createPoolConfig (OdbcConf cs size) = createODBCPool cs size
    runPool _ = runSqlPool
    loadConfig (Object o) = do
        cstr    <- o .: "connStr"
        pool    <- o .: "poolsize"
        return $ OdbcConf cstr pool
    loadConfig _ = mzero

    applyEnv c0 = return c0

-- | Avoid orphan instances.
newtype P = P { unP :: PersistValue } deriving Show

instance DC.Convertible P HSV.SqlValue where
    safeConvert (P (PersistText t))             = Right $ HSV.toSql t
    safeConvert (P (PersistByteString bs))      = Right $ HSV.toSql bs
    safeConvert (P (PersistInt64 i))            = Right $ HSV.toSql i
    safeConvert (P (PersistRational r))         = Right $ HSV.toSql r
    safeConvert (P (PersistDouble d))           = Right $ HSV.toSql d
    safeConvert (P (PersistBool b))             = Right $ HSV.toSql b
    safeConvert (P (PersistDay d))              = Right $ HSV.toSql d
    safeConvert (P (PersistTimeOfDay t))        = Right $ HSV.toSql t
    safeConvert (P (PersistUTCTime t))          = Right $ HSV.toSql t
    safeConvert (P (PersistZonedTime (ZT t)))   = Right $ HSV.toSql t
    safeConvert (P PersistNull)                 = Right $ HSV.SqlNull
    safeConvert (P (PersistList l))             = Right $ HSV.toSql $ listToJSON l
    safeConvert (P (PersistMap m))              = Right $ HSV.toSql $ mapToJSON m
    safeConvert p@(P (PersistObjectId _))       = Left $ DC.ConvertError
        { DC.convSourceValue   = show p
        , DC.convSourceType    = "P (PersistValue)"
        , DC.convDestType      = "SqlValue"
        , DC.convErrorMessage  = "Refusing to serialize a PersistObjectId to an ODBC value" }

-- FIXME: check if those are correct and complete.
instance DC.Convertible HSV.SqlValue P where
    safeConvert (HSV.SqlString s)        = Right $ P $ PersistText $ T.pack s
    safeConvert (HSV.SqlByteString bs)   = Right $ P $ PersistByteString bs
    safeConvert v@(HSV.SqlWord32 _)      = Left $ DC.ConvertError
        { DC.convSourceValue   = show v
        , DC.convSourceType    = "SqlValue"
        , DC.convDestType      = "P (PersistValue)"
        , DC.convErrorMessage  = "There is no conversion from SqlWord32 to PersistValue" }
    safeConvert v@(HSV.SqlWord64 _)      = Left $ DC.ConvertError
        { DC.convSourceValue   = show v
        , DC.convSourceType    = "SqlValue"
        , DC.convDestType      = "P (PersistValue)"
        , DC.convErrorMessage  = "There is no conversion from SqlWord64 to PersistValue" }
    safeConvert (HSV.SqlInt32 i)         = Right $ P $ PersistInt64 $ fromIntegral i
    safeConvert (HSV.SqlInt64 i)         = Right $ P $ PersistInt64 i
    safeConvert (HSV.SqlInteger i)       = Right $ P $ PersistInt64 $ fromIntegral i
    safeConvert (HSV.SqlChar c)          = Right $ P $ PersistText $ T.singleton c
    safeConvert (HSV.SqlBool b)          = Right $ P $ PersistBool b
    safeConvert (HSV.SqlDouble d)        = Right $ P $ PersistDouble d
    safeConvert (HSV.SqlRational r)      = Right $ P $ PersistRational r
    safeConvert (HSV.SqlLocalDate d)     = Right $ P $ PersistDay d
    safeConvert (HSV.SqlLocalTimeOfDay t)= Right $ P $ PersistTimeOfDay t
    safeConvert (HSV.SqlZonedLocalTimeOfDay td tz)
                    = Right $ P $ PersistZonedTime $ ZT $ ZonedTime (LocalTime (ModifiedJulianDay 0) td) tz
    safeConvert (HSV.SqlLocalTime t)     = Right $ P $ PersistUTCTime $ localTimeToUTC utc t
    safeConvert (HSV.SqlZonedTime zt)    = Right $ P $ PersistZonedTime $ ZT zt
    safeConvert (HSV.SqlUTCTime t)       = Right $ P $ PersistUTCTime t
    safeConvert (HSV.SqlDiffTime ndt)    = Right $ P $ PersistDouble $ fromRational $ toRational ndt
    safeConvert (HSV.SqlPOSIXTime pt)    = Right $ P $ PersistDouble $ fromRational $ toRational pt
    safeConvert (HSV.SqlEpochTime e)     = Right $ P $ PersistInt64 $ fromIntegral e
    safeConvert (HSV.SqlTimeDiff i)      = Right $ P $ PersistInt64 $ fromIntegral i
    safeConvert (HSV.SqlNull)            = Right $ P PersistNull

migrate' :: [EntityDef a]
         -> (Text -> IO Statement)
         => EntityDef SqlType
         -> IO (Either [Text] [(Bool, Text)])
migrate' _ _ _ = error "migrate is not implemented for ODBC"

{-
    = fmap (fmap $ map showAlterDb) $ do
    let name = entityDB $ entityDef val
    old <- getColumns getter $ entityDef val
    case partitionEithers old of
        ([], old'') -> do
            let old' = partitionEithers old''
            let new = second (map udToPair) $ mkColumns allDefs val
            if null old
                then do
                    let addTable = AddTable $ concat
                            -- Lower case e: see Database.Persistent.GenericSql.Migration
                            [ "CREATe TABLE "
                            , T.unpack $ escape name
                            , "("
                            , T.unpack $ escape $ entityID $ entityDef val
                            , " SERIAL PRIMARY KEY UNIQUE"
                            , concatMap (\x -> ',' : showColumn x) $ fst new
                            , ")"
                            ]
                    let uniques = flip concatMap (snd new) $ \(uname, ucols) ->
                            [AlterTable name $ AddUniqueConstraint uname ucols]
                        references = mapMaybe (getAddReference name) $ fst new
                    return $ Right $ addTable : uniques ++ references
                else do
                    let (acs, ats) = getAlters new old'
                    let acs' = map (AlterColumn name) acs
                    let ats' = map (AlterTable name) ats
                    return $ Right $ acs' ++ ats'
        (errs, _) -> return $ Left errs

data AlterColumn = Type SqlType | IsNull | NotNull | Add Column | Drop
                 | Default String | NoDefault | Update String
                 | AddReference DBName | DropReference DBName
type AlterColumn' = (DBName, AlterColumn)

data AlterTable = AddUniqueConstraint DBName [DBName]
                | DropConstraint DBName

data AlterDB = AddTable Stringmr <-
             | AlterColumn DBName AlterColumn'
             | AlterTable DBName AlterTable

-- | Returns all of the columns in the given table currently in the database.
getColumns :: (Text -> IO Statement)
           -> EntityDef
           -> IO [Either Text (Either Column (DBName, [DBName]))]
getColumns getter def = do
    stmt <- getter "SELECT column_name,is_nullable,udt_name,column_default FROM information_schema.columns WHERE table_name=? AND column_name <> ?"
    let vals =
            [ PersistText $ unDBName $ entityDB def
            , PersistText $ unDBName $ entityID def
            ]
    cs <- runResourceT $ withStmt stmt vals $$ helper
    stmt' <- getter
        "SELECT constraint_name, column_name FROM information_schema.constraint_column_usage WHERE table_name=? AND column_name <> ? ORDER BY constraint_name, column_name"
    us <- runResourceT $ withStmt stmt' vals $$ helperU
    return $ cs ++ us
  where
    getAll front = do
        x <- CL.head
        case x of
            Nothing -> return $ front []
            Just [PersistText con, PersistText col] ->
                getAll (front . (:) (con, col))
            Just _ -> getAll front -- FIXME error message?
    helperU = do
        rows <- getAll id
        return $ map (Right . Right . (DBName . fst . head &&& map (DBName . snd)))
               $ groupBy ((==) `on` fst) rows
    helper = do
        x <- CL.head
        case x of
            Nothing -> return []
            Just x' -> do
                col <- liftIO $ getColumn getter (entityDB def) x'
                let col' = case col of
                            Left e -> Left e
                            Right c -> Right $ Left c
                cols <- helper
                return $ col' : cols

getAlters :: ([Column], [(DBName, [DBName])])
          -> ([Column], [(DBName, [DBName])])
          -> ([AlterColumn'], [AlterTable])
getAlters (c1, u1) (c2, u2) =
    (getAltersC c1 c2, getAltersU u1 u2)
  where
    getAltersC [] old = map (\x -> (cName x, Drop)) old
    getAltersC (new:news) old =
        let (alters, old') = findAlters new old
         in alters ++ getAltersC news old'

    getAltersU :: [(DBName, [DBName])]
               -> [(DBName, [DBName])]
               -> [AlterTable]
    getAltersU [] old = map DropConstraint $ filter (not . isManual) $ map fst old
    getAltersU ((name, cols):news) old =
        case lookup name old of
            Nothing -> AddUniqueConstraint name cols : getAltersU news old
            Just ocols ->
                let old' = filter (\(x, _) -> x /= name) old
                 in if sort cols == sort ocols
                        then getAltersU news old'
                        else  DropConstraint name
                            : AddUniqueConstraint name cols
                            : getAltersU news old'

    -- Don't drop constraints which were manually added.
    isManual (DBName x) = "__manual_" `T.isPrefixOf` x

getColumn :: (Text -> IO Statement)
          -> DBName -> [PersistValue]
          -> IO (Either Text Column)
getColumn getter tname [PersistText x, PersistText y, PersistText z, d] =
    case d' of
        Left s -> return $ Left s
        Right d'' ->
            case getType z of
                Left s -> return $ Left s
                Right t -> do
                    let cname = DBName x
                    ref <- getRef cname
                    return $ Right $ Column cname (y == "YES") t d'' Nothing ref
  where
    getRef cname = do
        let sql = pack $ concat
                [ "SELECT COUNT(*) FROM "
                , "information_schema.table_constraints "
                , "WHERE table_name=? "
                , "AND constraint_type='FOREIGN KEY' "
                , "AND constraint_name=?"
                ]
        let ref = refName tname cname
        stmt <- getter sql
        runResourceT $ withStmt stmt
                     [ PersistText $ unDBName tname
                     , PersistText $ unDBName ref
                     ] $$ do
            Just [PersistInt64 i] <- CL.head
            return $ if i == 0 then Nothing else Just (DBName "", ref)
    d' = case d of
            PersistNull   -> Right Nothing
            PersistText t -> Right $ Just t
            _ -> Left $ pack $ "Invalid default column: " ++ show d
    getType "int4"        = Right $ SqlInt32
    getType "int8"        = Right $ SqlInt64
    getType "varchar"     = Right $ SqlString
    getType "date"        = Right $ SqlDay
    getType "bool"        = Right $ SqlBool
    getType "timestamp"   = Right $ SqlDayTime
    getType "timestamptz" = Right $ SqlDayTimeZoned
    getType "float4"      = Right $ SqlReal
    getType "float8"      = Right $ SqlReal
    getType "bytea"       = Right $ SqlBlob
    getType "time"        = Right $ SqlTime
    getType a             = Right $ SqlOther a
getColumn _ _ x =
    return $ Left $ pack $ "Invalid result from information_schema: " ++ show x

findAlters :: Column -> [Column] -> ([AlterColumn'], [Column])
findAlters col@(Column name isNull type_ def _maxLen ref) cols =
    case filter (\c -> cName c == name) cols of
        [] -> ([(name, Add col)], cols)
        Column _ isNull' type_' def' _maxLen' ref':_ ->
            let refDrop Nothing = []
                refDrop (Just (_, cname)) = [(name, DropReference cname)]
                refAdd Nothing = []
                refAdd (Just (tname, _)) = [(name, AddReference tname)]
                modRef =
                    if fmap snd ref == fmap snd ref'
                        then []
                        else refDrop ref' ++ refAdd ref
                modNull = case (isNull, isNull') of
                            (True, False) -> [(name, IsNull)]
                            (False, True) ->
                                let up = case def of
                                            Nothing -> id
                                            Just s -> (:) (name, Update $ T.unpack s)
                                 in up [(name, NotNull)]
                            _ -> []
                modType = if type_ == type_' then [] else [(name, Type type_)]
                modDef =
                    if def == def'
                        then []
                        else case def of
                                Nothing -> [(name, NoDefault)]
                                Just s -> [(name, Default $ T.unpack s)]
             in (modRef ++ modDef ++ modNull ++ modType,
                 filter (\c -> cName c /= name) cols)

-- | Get the references to be added to a table for the given column.
getAddReference :: DBName -> Column -> Maybe AlterDB
getAddReference table (Column n _nu _t _def _maxLen ref) =
    case ref of
        Nothing -> Nothing
        Just (s, _) -> Just $ AlterColumn table (n, AddReference s)

showColumn :: Column -> String
showColumn (Column n nu t def _maxLen ref) = concat
    [ T.unpack $ escape n
    , " "
    , showSqlType t
    , " "
    , if nu then "NULL" else "NOT NULL"
    , case def of
        Nothing -> ""
        Just s -> " DEFAULT " ++ T.unpack s
    ]

showSqlType :: SqlType -> String
showSqlType SqlString = "VARCHAR"
showSqlType SqlInt32 = "INT4"
showSqlType SqlInt64 = "INT8"
showSqlType SqlReal = "DOUBLE PRECISION"
showSqlType SqlDay = "DATE"
showSqlType SqlTime = "TIME"
showSqlType SqlDayTime = "TIMESTAMP"
showSqlType SqlDayTimeZoned = "TIMESTAMP WITH TIME ZONE"
showSqlType SqlBlob = "BYTEA"
showSqlType SqlBool = "BOOLEAN"
showSqlType (SqlOther t) = T.unpack t

showAlterDb :: AlterDB -> (Bool, Text)
showAlterDb (AddTable s) = (False, pack s)
showAlterDb (AlterColumn t (c, ac)) =
    (isUnsafe ac, pack $ showAlter t (c, ac))
  where
    isUnsafe Drop = True
    isUnsafe _ = False
showAlterDb (AlterTable t at) = (False, pack $ showAlterTable t at)

showAlterTable :: DBName -> AlterTable -> String
showAlterTable table (AddUniqueConstraint cname cols) = concat
    [ "ALTER TABLE "
    , T.unpack $ escape table
    , " ADD CONSTRAINT "
    , T.unpack $ escape cname
    , " UNIQUE("
    , intercalate "," $ map (T.unpack . escape) cols
    , ")"
    ]
showAlterTable table (DropConstraint cname) = concat
    [ "ALTER TABLE "
    , T.unpack $ escape table
    , " DROP CONSTRAINT "
    , T.unpack $ escape cname
    ]

showAlter :: DBName -> AlterColumn' -> String
showAlter table (n, Type t) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " ALTER COLUMN "
        , T.unpack $ escape n
        , " TYPE "
        , showSqlType t
        ]
showAlter table (n, IsNull) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " ALTER COLUMN "
        , T.unpack $ escape n
        , " DROP NOT NULL"
        ]
showAlter table (n, NotNull) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " ALTER COLUMN "
        , T.unpack $ escape n
        , " SET NOT NULL"
        ]
showAlter table (_, Add col) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " ADD COLUMN "
        , showColumn col
        ]
showAlter table (n, Drop) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " DROP COLUMN "
        , T.unpack $ escape n
        ]
showAlter table (n, Default s) =
    concat
        [ "ALTER TABLE "
        , T.unpack $ escape table
        , " ALTER COLUMN "
        , T.unpack $ escape n
        , " SET DEFAULT "
        , s
        ]
showAlter table (n, NoDefault) = concat
    [ "ALTER TABLE "
    , T.unpack $ escape table
    , " ALTER COLUMN "
    , T.unpack $ escape n
    , " DROP DEFAULT"
    ]
showAlter table (n, Update s) = concat
    [ "UPDATE "
    , T.unpack $ escape table
    , " SET "
    , T.unpack $ escape n
    , "="
    , s
    , " WHERE "
    , T.unpack $ escape n
    , " IS NULL"
    ]
showAlter table (n, AddReference t2) = concat
    [ "ALTER TABLE "
    , T.unpack $ escape table
    , " ADD CONSTRAINT "
    , T.unpack $ escape $ refName table n
    , " FOREIGN KEY("
    , T.unpack $ escape n
    , ") REFERENCES "
    , T.unpack $ escape t2
    ]
showAlter table (_, DropReference cname) = concat
    [ "ALTER TABLE "
    , T.unpack (escape table)
    , " DROP CONSTRAINT "
    , T.unpack $ escape cname
    ]
-}
{-
refName :: DBName -> DBName -> DBName
refName (DBName table) (DBName column) =
    DBName $ T.concat [table, "_", column, "_fkey"]

udToPair :: UniqueDef -> (DBName, [DBName])
udToPair ud = (uniqueDBName ud, map snd $ uniqueFields ud)
-}

redpajama_set_name: RedPajamaGithub


text:
#sb-title-inner,#sb-info-inner,#sb-loading-inner,div.sb-message{font-family:"HelveticaNeue-Light","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:200;color:#444444;}
#sb-container{position:fixed;margin:0;padding:0;top:0;left:0;z-index:999;text-align:left;visibility:hidden;display:none;}
#sb-overlay{position:relative;height:100%;width:100%;}
#sb-wrapper{position:absolute;visibility:hidden;width:100px;}
#sb-wrapper-inner{position:relative;border:1px solid #EAEAEA;overflow:hidden;height:100px;padding:4px;background:#FFFFFF;}
#sb-body{position:relative;height:100%;}
#sb-body-inner{position:absolute;height:100%;width:100%;}
#sb-player.html{height:100%;overflow:auto;}
#sb-body img{border:none;}
#sb-loading{position:relative;height:100%;}
#sb-loading-inner{position:absolute;font-size:14px;line-height:24px;height:24px;top:50%;margin-top:-12px;width:100%;text-align:center;}
#sb-loading-inner span{background:url(loading.gif) no-repeat;padding-left:0px;display:inline-block;height:40px;padding-right:34px;}
#sb-body,#sb-loading{background-color:#FFFFFF;}
#sb-title,#sb-info{position:relative;margin:0;padding:0;overflow:hidden;}
#sb-title,#sb-title-inner{height:26px;line-height:26px;}
#sb-title-inner{font-size:16px;}
#sb-info,#sb-info-inner{height:20px;line-height:20px;}
#sb-info-inner{font-size:12px;}
#sb-nav{float:right;height:16px;padding:2px 0;width:45%;}
#sb-nav a{display:block;float:right;height:16px;width:16px;margin-left:3px;cursor:pointer;background-repeat:no-repeat;}
#sb-nav-close{background-image:url(close.png);}
#sb-nav-next{background-image:url(next.png);}
#sb-nav-previous{background-image:url(previous.png);}
#sb-nav-play{background-image:url(play.png);}
#sb-nav-pause{background-image:url(pause.png);}
#sb-counter{float:left;width:45%;padding-left:6px;color:#444444;}
#sb-counter a{padding:0 4px 0 0;text-decoration:none;cursor:pointer;color:#444444;}
#sb-counter a.sb-counter-current{text-decoration:underline;}
div.sb-message{font-size:12px;padding:10px;text-align:center;}
div.sb-message a:link,div.sb-message a:visited{color:#444444;text-decoration:underline;}

/*  Custom Changes  */
#sb-wrapper-inner {padding-bottom:25px;-moz-box-shadow: 0px 1px 3px #dedede;-webkit-box-shadow:0px 1px 3px #dedede;}
#sb-info {margin-top:-23px !important;margin-right:6px;z-index:999;}
#sb-counter {color:#6f6f6f;font-weight:bold;font-size:10px;}


text:
@class PDFDocument;

typedef enum : NSUInteger {
    SplitShowScreenModePreview,
    SplitShowScreenModeWindow,
    SplitShowScreenModeFullscreen,
} SplitShowScreenMode;

@interface SplitShowScreen : NSObject<NSCoding>

@property (readonly) NSString *name;
@property (readonly) CGDirectDisplayID displayID;
@property (readonly) NSScreen *screen;
@property PDFDocument *document;
@property SplitShowScreenMode mode;
@property BOOL showTimer;

+ (instancetype)previewScreen;
+ (instancetype)windowScreen;
+ (instancetype)screenWithScreen:(SplitShowScreen*)screen;

- (instancetype)initWithDisplayID:(CGDirectDisplayID)displayID;
- (instancetype)initWithScreen:(NSScreen*)screen;

- (BOOL)isPseudoScreen;
- (BOOL)isAvailable;

- (BOOL)isEqualToSplitShowScreen:(SplitShowScreen*)screen;

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Monster Manager Loader</title>
</head>
<body>
<script type="text/javascript" src="dist/monster-manager-loader.min.js"></script>
</body>
</html>


text:
package com.lindar.sergent;

import com.anarsoft.vmlens.concurrent.junit.ConcurrentTestRunner;
import com.anarsoft.vmlens.concurrent.junit.ThreadCount;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.stream.IntStream;

@RunWith(ConcurrentTestRunner.class)
public class IntGeneratorMultiThreadedTest {
    private static final int SIZE_CHECK = 20_001;
    private final static int THREAD_COUNT = 4;

    @Before
    public void setUp() {
    }

    @Test
    @ThreadCount(THREAD_COUNT)
    public void randMultiThreadedSingleInt() {
        Sergent sergent = SergentFactory.newInstance();
        IntStream.rangeClosed(0, SIZE_CHECK).forEach(i -> {
            Integer number = sergent.intGenerator().randInt();
            Assert.assertNotNull("Failed to generate random number", number);
        });
    }

}


text:
module Avatax
  module Api
    class Utilities < Base
    end
  end
end


text:
package au.edu.uts.eng.remotelabs.rigclient.rig.internal;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map.Entry;

import au.edu.uts.eng.remotelabs.rigclient.rig.IRig;
import au.edu.uts.eng.remotelabs.rigclient.rig.IRigSession.Session;
import au.edu.uts.eng.remotelabs.rigclient.type.RigFactory;
import au.edu.uts.eng.remotelabs.rigclient.util.ConfigFactory;
import au.edu.uts.eng.remotelabs.rigclient.util.IConfig;
import au.edu.uts.eng.remotelabs.rigclient.util.ILogger;
import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory;

/**
 * Macro substituter for rig client information discovery
 * (getAttribute call).
 *

 * Substitutes macro variables into a string.  All variables must be prefixed
 * with '--' and end in '--'. The following is the
 * list of macro variable name and macro value pairs.
 *

 *
__HOSTNAME__ -

 *
__IP__ -

 *

 *  The algorithm for determining the values is:
 *
 *     1. If the property 'Rig_Client_IP_Address' is set, the __IP__ value is
 *        the configured value, and the __HOSTNAME__ value is determined from
 *        that IP.
 *     2. If the 'Listening_Network_Interface' property is set, the __IP__
 *        and __HOSTNAME__ values are determined from the configured network
 *        interface name.
 *     3. If neither are set, the __IP__ and __HOSTNAME__ are determined from
 *        the first iterated network interface (eth0 on Linux systems).
 */
public class AttributeMacroSubstituter
{
    /** Configured IP address to use as IP and discover hostname from. */
    private String ip;

    /** Configured network interface name to discover IP and hostname from. */
    private String nic;

    /** Logger. */
    private ILogger logger;

    public AttributeMacroSubstituter()
    {
        this.logger = LoggerFactory.getLoggerInstance();

        final IConfig conf = ConfigFactory.getInstance();
        if ((this.ip = conf.getProperty("Rig_Client_IP_Address")) != null && this.ip.length() > 0)
        {
            this.logger.info("Providing network information based on the configured IP: " + this.ip + ".");
            this.nic = null;
        }
        else if ((this.nic = conf.getProperty("Listening_Network_Interface")) != null && this.nic.length() > 0)
        {
            this.logger.info("Providing network information based on the configured network interface name " +
                    this.nic + ".");
            this.ip = null;
        }
        else
        {
            this.ip = null;
            this.nic = null;
        }
    }

    /**
     * Substitutes the marcos with their run-time determined values.
     *
     * @param str macro string
     * @return string with macros replaced
     * @throws Exception error detected network information
     */
    public String substitueMacros(String str) throws Exception
    {
        StringBuilder buf = new StringBuilder();
        IRig rig = RigFactory.getRigInstance();

        for (String tok : str.split("__"))
        {
            if ("IP".equalsIgnoreCase(tok))
            {
                buf.append(this.findNetworkMacroValue(false));
            }
            else if ("HOSTNAME".equalsIgnoreCase(tok))
            {
                buf.append(this.findNetworkMacroValue(true));
            }
            else if ("USER".equalsIgnoreCase(tok))
            {
                for (Entry<String, Session> user : rig.getSessionUsers().entrySet())
                {
                    if (user.getValue() == Session.MASTER)
                    {
                        buf.append(user.getKey());
                    }
                }
            }
            else if ("RIG_NAME".equalsIgnoreCase(tok))
            {
                buf.append(rig.getName());
            }
            else if ("RIG_TYPE".equalsIgnoreCase(tok))
            {
                buf.append(rig.getType());
            }
            else
            {
                buf.append(tok);
            }
        }

        return buf.toString();
    }

    /**
     * Finds and returns either the host name or IP of a network interface.
     * The network interface used is either:
     *

     *
The network interface with the configured IP address, if the IP
     *  address is set.

     *
The network interface with the configured device name, if the
     *  device name is configured and the IP address is not configured.

     *
The first iterated non-loopback network interface if neither
     *  the network interface IP address or network device name is
     *  configured.

     *

     *
     * @param returnHostname true if the host name is to be returned, \
     *        otherwise the IP address is returned
     * @return host name or IP network host name or IP
     * @throws Exception error finding network information or no viable \
     *         network interface
     */
    private String findNetworkMacroValue(boolean returnHostname) throws Exception
    {
        NetworkInterface inf = null;

        /* If IP configured, use the configured value. */
        if (this.ip != null)
        {
            if (returnHostname)
            {
                inf = NetworkInterface.getByInetAddress(InetAddress.getByName(this.ip));
            }
            else
            {
                return this.ip;
            }
        }
        /* If NIC configured, determined the (first)IP of the NIC. */
        else if (this.nic != null)
        {
            inf = NetworkInterface.getByName(this.nic);

        }
        /* Otherwise, use first non-loopback device. */
        else
        {
            Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
            while (nics.hasMoreElements())
            {
                inf = nics.nextElement();
                if (inf.isLoopback())
                {
                    inf = null;
                }
                else
                {
                    break;
                }
            }
        }

        if (inf == null)
        {
            this.logger.warn("Unable to find any viable network interfaces for network information macro substitution.");
            throw new Exception(" no network interface found");
        }

        Enumeration<InetAddress> addrs = inf.getInetAddresses();
        while (addrs.hasMoreElements())
        {
            InetAddress addr = addrs.nextElement();
            if (!(addr instanceof Inet4Address)) // Only interested in IPv4 currently
            {
                continue;
            }

            if (returnHostname)
            {
                return addr.getHostName();
            }
            else
            {
                return addr.getHostAddress();
            }
        }

        this.logger.warn("Unable to find an IP address for network interface " + inf.getDisplayName() + " as it" +
                " appears to have none.");
        throw new Exception(" no addresses found for interface " + inf.getDisplayName());
    }
}


text:
#ifndef INCLUDE_filter_h__
#define INCLUDE_filter_h__

#include BLIK_LIBGIT2_U_common_h //original-code:"common.h"
#include BLIK_LIBGIT2_U_git2__filter_h //original-code:"git2/filter.h"

/* Amount of file to examine for NUL byte when checking binary-ness */
#define GIT_FILTER_BYTES_TO_CHECK_NUL 8000

/* Possible CRLF values */
typedef enum {
	GIT_CRLF_GUESS = -1,
	GIT_CRLF_BINARY = 0,
	GIT_CRLF_TEXT,
	GIT_CRLF_INPUT,
	GIT_CRLF_CRLF,
	GIT_CRLF_AUTO,
} git_crlf_t;

extern void git_filter_free(git_filter *filter);

/*
 * Available filters
 */

extern git_filter *git_crlf_filter_new(void);
extern git_filter *git_ident_filter_new(void);

#endif


text:
**Severity Level: Warning**

##Description
Parameters must have a default value as uninitialized parameters will lead to potential bugs in the scripts.

##How to Fix

To fix a violation of this rule, please specify a default value for all parameters.

##Example

Wrong:

```
function Test($Param1)
{
	$Param1
}
```

Correct:

```
function Test($Param1 = $null)
{
	$Param1
}
```


text:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>sample</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <outputDirectory>RED-INF/lib</outputDirectory>
      <useProjectArtifact>false</useProjectArtifact>
      <unpack>false</unpack>
      <scope>provided</scope>
    </dependencySet>
  </dependencySets>
</assembly>


text:
static void
test_stdlib_hello()
{
	stdlib_allocator_t alloc;
}

static void
test_tracing_hello()
{
	tracing_allocator_t alloc;
	unfact::byte_t* ptr0 = alloc.allocate(10);
	unfact::byte_t* ptr1 = alloc.allocate(20);
	alloc.deallocate(ptr1);
	alloc.deallocate(ptr0);
}

void test_memory()
{
	test_stdlib_hello();
	test_tracing_hello();
}


text:
@implementation SingleEntityRelatedToMappedEntityUsingDefaultsID
@end

@implementation _SingleEntityRelatedToMappedEntityUsingDefaults

+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription insertNewObjectForEntityForName:@"SingleEntityRelatedToMappedEntityUsingDefaults" inManagedObjectContext:moc_];
}

+ (NSString*)entityName {
	return @"SingleEntityRelatedToMappedEntityUsingDefaults";
}

+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription entityForName:@"SingleEntityRelatedToMappedEntityUsingDefaults" inManagedObjectContext:moc_];
}

- (SingleEntityRelatedToMappedEntityUsingDefaultsID*)objectID {
	return (SingleEntityRelatedToMappedEntityUsingDefaultsID*)[super objectID];
}

+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
	NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];

	if ([key isEqualToString:@"singleEntityRelatedToMappedEntityUsingDefaultsIDValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"singleEntityRelatedToMappedEntityUsingDefaultsID"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
	}

	return keyPaths;
}

@dynamic singleEntityRelatedToMappedEntityUsingDefaultsID;

- (short)singleEntityRelatedToMappedEntityUsingDefaultsIDValue {
	NSNumber *result = [self singleEntityRelatedToMappedEntityUsingDefaultsID];
	return [result shortValue];
}

- (void)setSingleEntityRelatedToMappedEntityUsingDefaultsIDValue:(short)value_ {
	[self setSingleEntityRelatedToMappedEntityUsingDefaultsID:[NSNumber numberWithShort:value_]];
}

- (short)primitiveSingleEntityRelatedToMappedEntityUsingDefaultsIDValue {
	NSNumber *result = [self primitiveSingleEntityRelatedToMappedEntityUsingDefaultsID];
	return [result shortValue];
}

- (void)setPrimitiveSingleEntityRelatedToMappedEntityUsingDefaultsIDValue:(short)value_ {
	[self setPrimitiveSingleEntityRelatedToMappedEntityUsingDefaultsID:[NSNumber numberWithShort:value_]];
}

@dynamic mappedEntity;

@end


text:
package oauthserver

import "net/http"

type Mux interface {
	Handle(pattern string, handler http.Handler)
	HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}

type Endpoints interface {
	// Install registers one or more http.Handlers into the given mux.
	// It is expected that the provided prefix will serve all operations.
	// prefix MUST NOT end in a slash.
	Install(mux Mux, prefix string)
}


text:
exports.getWidget = function(feather, cb) {
  cb(null, {
    name: "api_tester.disallowClientContentTemplateOnServerTest",
    path: "widgets/disallowClientContentTemplateOnServerTest/"
  });
};


text:
<?php
namespace SCSS\CourseBundle\Entity;

use SCSS\UtilityBundle\Traits\SluggableTrait;
use SCSS\UtilityBundle\Traits\TimestampableTrait;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="SCSS\CourseBundle\Repository\RequirementRepository")
 * @ORM\Table(name="requirement")
 */
class Requirement
{
    use SluggableTrait;
    use TimestampableTrait;

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @ORM\Column(type="string")
     * @Assert\Length(
     *      min = "1",
     *      max = "250",
     *      minMessage = "Name must be at least {{ limit }} characters length",
     *      maxMessage = "Name cannot be longer than {{ limit }} characters length"
     * )
     * @var string
     */
    protected $name;

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name
     *
     * @param string $name name
     *
     * @return Requirement
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set description
     *
     * @param string $description string
     *
     * @return Requirement
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @ORM\ManyToOne(targetEntity="SCSS\CourseBundle\Entity\Requirement", inversedBy="requirement")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     */
    protected $parent = '';

    /**
     * Get parent
     *
     * @return Requirement
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Set requirement
     *
     * @param Requirement $parent parent
     *
     * @return Requirement
     */
    public function setParent(Requirement $parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @ORM\ManyToOne(targetEntity="SCSS\CourseBundle\Entity\Course", inversedBy="requirement")
     * @ORM\JoinColumn(name="course_id", referencedColumnName="id")
     */
    protected $course = '';

    /**
     * Get course
     *
     * @return Course
     */
    public function getCourse()
    {
        return $this->course;
    }

    /**
     * Set course
     *
     * @param Course $course course
     *
     * @return Requirement
     */
    public function setCourse(Course $course)
    {
        $this->course = $course;

        return $this;
    }

    /**
     * Optional
     *
     * @param  boolean        $optional optional
     * @return boolean|Course
     */
    protected $optional;

    /**
     * Is optional
     * @param  boolean|null        $optional optional
     * @return boolean|Requirement
     */
    public function isOptional($optional = null)
    {
        if (null != $optional && is_bool($optional)) {
            $this->optional = $optional;

            return $this;
        }

        return $this->optional;
    }
}


text:
package io.shtanko.featuretemplate.di.module;

import android.content.Context;
import dagger.Module;
import dagger.Provides;
import io.shtanko.featuretemplate.App;
import javax.inject.Singleton;

@Module public class AppModule {

  private App app;

  public AppModule(App app) {
    this.app = app;
  }

  @Provides @Singleton App provideApp() {
    return app;
  }
}


text:
<?php
namespace Cobase\DemoBundle\Service;

use Cobase\DemoBundle\Form\Model\CatModel;
use Cobase\DemoBundle\Form\Type\CatType;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormFactory;

class CatService
{
    /**
     * @var FormFactory
     */
    protected $formFactory;

    /**
     * @param FormFactory $formFactory
     */
    public function __construct(FormFactory $formFactory)
    {
        $this->formFactory = $formFactory;
    }

    /**
     * @param CatModel $catModel
     * @return Form
     */
    public function getCatForm(CatModel $catModel)
    {
        return $this->formFactory->create(
            new CatType(get_class($catModel)), $catModel
        );
    }

    /**
     * @param Form $form
     *
     * @return string
     */
    public function patCatByForm(Form $form)
    {
        $catModel = $form->getData();

        return str_repeat($catModel->getName() . " ", $catModel->getAge() );
    }
}


text:
<services>

    <service id="desktop_finder.preparesell_mdl_preparesell">
        <class>preparesell_finder_preparesell</class>
    </service>
    <service id="prepare_goods">
        <class>preparesell_prepare_goods</class>
    </service>
    <service id="prepare_prepare">
        <class>preparesell_prepare_prepare</class>
    </service>
    <service id="prepare_order">
        <class>preparesell_prepare_order</class>
    </service>
    <service id="b2c_cart_process_apps">
        <class>preparesell_cart_process_special</class>
    </service>
     <service id="firevent_type">
        <class>preparesell_service_firevent_action</class>
    </service>
    <service id="b2c_order_cancel_finish" optname="预售订单作废完成库存处理">
        <class>preparesell_prepare_ordercancel</class>
    </service>
    <service id="b2c_order_create_finish" optname="预售订单完成库存处理">
        <class>preparesell_prepare_ordercreate</class>
    </service>
    <service id="b2c_mdl_goods.filter" optname="预售排他">
        <class>preparesell_prepare_promotion</class>
    </service>
    <service id="b2c_allow_delete_goods">
        <class>preparesell_prepare_goods</class>
    </service>
</services>


text:
package command.turtle;

import model.Turtle;
import command.Command;

/**
 * turns turtle to an absolute heading
 * returns number of degrees moved
 *
 * @author GA
 *
 */
public class HeadingCommand extends Command {
    private Turtle myTurtle;

    public HeadingCommand (Turtle t) {
        myTurtle = t;
    }

    @Override
    public double calculateValue () {
        return myTurtle.getHeading();

    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>http::async_write_header</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../ref.html" title="This Page Intentionally Left Blank 2/2">
<link rel="prev" href="boost__beast__http__write_header/overload2.html" title="http::write_header (2 of 2 overloads)">
<link rel="next" href="boost__beast__http__write.html" title="http::write">

Home
Libraries
People
FAQ
More

http::async_write_header

        Write a header to a stream asynchronously using a serializer.

        Synopsis

        Defined in header <boost/beast/http/write.hpp>

template<
    class AsyncWriteStream,
    bool isRequest,
    class Body,
    class Fields,
    class WriteHandler = net::default_completion_token_t<            executor_type<AsyncWriteStream>>>
DEDUCED
async_write_header(
    AsyncWriteStream& stream,
    serializer< isRequest, Body, Fields >& sr,
    WriteHandler&& handler = net::default_completion_token_t< executor_type< AsyncWriteStream >>{});

        Description

        This function is used to write a header to a stream asynchronously using
        a caller-provided HTTP/1 serializer. The function call always returns immediately.
        The asynchronous operation will continue until one of the following conditions
        is true:

            The function serializer::is_header_done returns true

            An error occurs.

        This operation is implemented in terms of zero or more calls to the stream's
        async_write_some function,
        and is known as a composed operation. The program must
        ensure that the stream performs no other writes until this operation completes.

        Parameters

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  stream

                  The stream to which the data is to be written. The type must support
                  the AsyncWriteStream concept.

                  sr

                  The serializer to use. The object must remain valid at least until
                  the handler is called; ownership is not transferred.

                  handler

                  The completion handler to invoke when the operation completes.
                  The implementation takes ownership of the handler by performing
                  a decay-copy. The equivalent function signature of the handler
                  must be:

void handler(
    error_code const& error,        // result of operation
    std::size_t bytes_transferred   // the number of bytes written to the stream
);

                  Regardless of whether the asynchronous operation completes immediately
                  or not, the handler will not be invoked from within this function.
                  Invocation of the handler will be performed in a manner equivalent
                  to using net::post.

        Remarks

        The implementation will call serializer::split with the value true on the serializer passed in.

        See Also

        serializer

Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
USE AdventureWorks2014;
GO

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

USE AdventureWorks2014;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Component\Webspace\Url;

use Sulu\Component\Webspace\Url;
use Sulu\Component\Webspace\Webspace;

/**
 * Provides urls for given webspace.
 */
interface WebspaceUrlProviderInterface
{
    /**
     * Returns urls for given webspace.
     *
     * @param Webspace $webspace
     * @param string $environment
     *
     * @return Url[]
     */
    public function getUrls(Webspace $webspace, $environment);
}


text:
package rooms;

import java.util.Scanner;

public class ReggiesRoom {

	private static Scanner input;

	public static void Reroom()
	{
		//What do you call a programmer from Finland?

		String doorChoice;
		String moralChoice;

		input = new Scanner(System.in);

		System.out.print("Once outside Reggie's office Chad notices that the lights are still on.");
		System.out.print("\nReggie, or Regginald as he prefers, is Blue Ring's tech manager. Although well liked no one really listens to him.");
		System.out.print("\nIn fact unless something brakes around the office Reggie is often forgotten.");
		System.out.print("\nWhat was I talking about again? Oh yeah, Reggie.");
		System.out.print("\nIf we want a key card we either get it from him or the boss's office.");
		System.out.print("OPEN DOOR or KEEP GOING? >>>");
		doorChoice = input.nextLine();
		 if(doorChoice.equals("OPEN DOOR")||doorChoice.equals("open door"))
		 {
			 System.out.print("\nChad opens the door to find Reggie tinkering away at some mechanical doodad.");
			 System.out.print("\nReggie: Hello Chad, working late I see.");
			 System.out.print("\nYou know it wouldn't hurt to say something to the man.");
			 System.out.print("\nRight you're one of those silent protagonists. That would explain why you're just staring at him.");
			 System.out.print("\nI guess I'll just do the talking then, Reggie?");
			 System.out.print("\nReggie: Who's there?");
			 System.out.print("\nThe Tooth Fairy.");
			 System.out.print("\nReggie: Really?");
			 System.out.print("\nNo I'm the narrator and because Chad doesn't talk much I'm going to have to be his voice.");
			 System.out.print("\nReggie: Fair enough, what do ya need?");
			 System.out.print("\nWe need a key card because Chad's is busted. Got any spare?");
			 System.out.print("\nReggie: I might have one in the back somewhere.");
			 System.out.print("\nGreat, mind grabbing it for us?");
			 System.out.print("\nReggie: I suppose I can. Wait here, and don't touch anything while I'm away.");
			 System.out.print("\nReggie leaves going through a door in the corner of the office.");
			 System.out.print("\nI heard he has some cool stuff in that box over there if you want a peek, or we could just sit here I suppose.");
			 System.out.print("LOOK IN BOX or WAIT? >>>");
			 moralChoice = input.nextLine();
			 	if(moralChoice.equals("LOOK IN BOX")||moralChoice.equals("look in box"))
			 	{
			 		System.out.print("\nChad begins looking through the box and finds what looks to be a VR helmet.");
			 		System.out.print("\nI read a book about someone being stuck in one of those, better leave it alone.");
			 		System.out.print("\nAlso in the box is a tiki mask with four brightly colored feathers.");
			 		System.out.print("\nHey I remember him, didn't he hangout with a wombat with fingerless gloves?");
			 		System.out.print("\nAt the very bottom of the box is a can of yellow paint along with a nametag that says Stanley.");
			 		System.out.print("\nWho's Stanley?");
			 		System.out.print("\nThe doorknob begins to shift and Chad hurriedly puts everything back in the box.");

			 	}
			 	if(moralChoice.equals("WAIT")||moralChoice.equals("wait"))
			 	{
			 		System.out.print("\nThe clock in Reggie's office clicks loudly.");
			 		System.out.print("\n....");
			 		System.out.print("\nDid you say something?");
			 		System.out.print("\nNo? Right you don't talk.");
			 		System.out.print("\n....");
			 		System.out.print("\nWhere's Reggie? Shoudn't take that long for a key card");

			 	}
			 	System.out.print("\nReggie enters the room with a key card in hand and gives it to Chad.");
			 	System.out.print("\nReggie: Here you are one key card.");
			 	System.out.print("\nThanks Reggie.");
			 	System.out.print("\nReggie: No problem Chad's always been good to me, even if he doesn't talk much.");
			 	System.out.print("\nWell Chad I guess that's all we need, it's time to go home.");
			 	System.out.print("\nChad shakes Reggie's hand then walks out of the office.");
			 	System.out.print("\nAs Chad is about to walk home Reggie comes up behind him and taps him on the shoulder.");
			 	System.out.print("\nReggie: Wanna grab a drink Chad?");
			 	System.out.print("\nA window opens on one side of the building and a man's head can be seen poking out.");
			 	System.out.print("\nDid someone say drinks?");
			 	System.out.print("\nReggie: Wait hold up, are you the narrator?");
			 	System.out.print("\nNo I'm the tooth fairy. Now are we going or not because I know a great place two blocks down from here and...");
			 	System.out.print("\nGame Over ending 7.");

		 }
		 if(doorChoice.equals("KEEP GOING")||doorChoice.equals("keep going"))
		 {
			 System.out.print("To the boss's office then.");
			 System.out.print("\nHopefully the janitor won't be there.");
			 BossOffice.Boroom();
		 }

	}
	//Nerdic.
}


text:
var mb = require('./build/Release/monkeyboard');

var playIndex;

console.log("Initialiserer");
//mb.init();
//var playStatus = mb.getPlayStatus();
//console.log("playStatus: ", playStatus);
//mb.playStream(0, 5);
//mb.setVolume(16);

mb.asyncTest(function(err, data) {
    console.log("Callback", arguments);
});

console.log("Scanner");
var programs = mb.scan(function(err, data) {
    console.log("doScan callback", arguments);

});
//console.log("Programs: ", programs);

/*
while(1) {
    playStatus = mb.getPlayStatus();
    console.log("playStatus: " + playStatus);
    playIndex = mb.getPlayIndex();
    console.log("playIndex: " + playIndex);
    playIndex = mb.getPlayIndex();
    console.log("playIndex: " + playIndex);
}
*/
mb.shutDown();

//var ffi = require("ffi");
//var lib = ffi.Library(null, {
//    "DABAutoSearch" : ["int", ["int"]]
//});


text:
import {getConfig} from 'helptos';

const symbols = getConfig('../../../config/symbols.json', __dirname);

function interruptionMsg(data) {

    return [
        ``
    ]
};

export function start(data) {
    return `${data.group.name} leaves the ${data.place.name}.`;
}

export function success(data) {
    return `${data.group.name} arrived in a ${data.place.name}. Let's see what we will find in here.`;
}

export function interrupt(data, count) {

    if (!count) {
        return `${data.member}`;
    }

    let messages = [];

    for (let i = 0; i < count; i++) {
        const member = groupSum.members[Math.floor(Math.random() * groupSum.members.length)].name

    }

    return messages[0];
}


text:
| Supported Targets | ESP32 | ESP32-C3 | ESP32-S2 | ESP32-S3 |
| ----------------- | ----- | -------- | -------- | -------- |

Efuse on ESP32-C2 not supported

This project is for testing if the application can be built with a particular sdkconfig setting.

To add new configuration, create one more sdkconfig.ci.NAME file in this directory.
To make the configuration target-specific, add a CONFIG_IDF_TARGET="name" line.

If you need to test for anything other than building, create another test project.


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_6544744</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753461989</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Gemeente Laarbeek > t Hof</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Gemeente Laarbeek,t Hof</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>t Hof</Appelation>
        <LocationNameType>populated place</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>5.59167</Longitude>
        <Latitude>51.51083</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/6544744</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
Some of the contributed modules are fetched from github.

* https://github.com/md-systems/redirect: 12/2 -2016


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="Content-Language" content="en-us" />
  <meta http-equiv="imagetoolbar" content="false" />
  <meta name="MSSmartTagsPreventParsing" content="true" />
  <title>Getting listed in the Integrations Directory | GitHub Developer Guide</title>

  <link rel="alternate" type="application/atom+xml" title="API Changes" href="/changes.atom" />

  <link href="/assets/stylesheets/application.css" rel="stylesheet" type="text/css" />

      EEme:Developer

Integrations Directory

Reference

Webhooks

Guides

Libraries

Getting your integration listed

Listing requirements

Technical requirements

Choose your type of listing

Send us your information

Listing requirements

Provide the right contacts

We want to be sure GitHub can contact your team, if needed. Specifically, we're asking for:

A technical support contact

A security contact

An escalation contact

All three are for GitHub-use only. If there's an urgent issue that needs your attention, we'll contact your escalation contact and expect a response within one business day. A delayed response from your escalation contact may result in temporary or permanent de-listing of your integration from the directory.

Provide standard links

We'd like to have a minimum set of links to include in every integration listing, so that our users have all the information they need. These are:

Pricing - If your integration costs money or has differed priced tiers of service, please include this URL.

Documentation - Please provide a URL with more information on how to use your integration.

Terms of service - Please provide the Terms of Service URL for users using your integration.

Privacy Policy - If different than Terms of Service, please include the URL here.

Support - Please provide a URL or email address for users to contact you directly.

Status - You should provide us a URL that will be updated when your application is down or experiencing problems. This could be a status site, a blog, a Twitter account, or more. This URL should be publicly accessible.

Installation - Provide the URL for direct installation for users. Note the OAuth requirement below.

Provide updates to your listing

We want GitHub users to have consistent messaging within the Integrations Directory and your
marketing site. As your product changes, keep your Integration Directory listing up to date. We ask that you refresh the information at least once a year. Please send updates to partnerships@github.com.

Provide categories for your listing

Help GitHub users find your integration faster with the appropriate categories. Please send us your suggested categories for the listing. We reserve the right to remove categories from a listing, but we won't add any categories without your approval. Currently, the following categories are available:

Code

Collaborate

Ship

If your integration supports both GitHub.com and GitHub Enterprise, please let us know.

Technical requirements

Use TLS

Anytime you display GitHub data in your integration, use TLS. If you also use webhooks to receive updated data from GitHub, use SSL/TLS there too.

Delete GitHub data once you lose access to the information

Once you realize you've lost access to a user, organization, repository, or its related objects,
delete that information in your system within 60 days.

Choose your type of listing

We offer two types of listings: OAuth installation listings and "learn more" listings.

OAuth installation listing

This is our preferred type of listing wherever possible.

The OAuth installation listings are used so customers can immediately install your integration directly
within GitHub's UI. To use this type of listing, provide a URL that will immediately redirect to
GitHub's OAuth authorization flow.

We are happy to help you identify if your integration can already support this. If you'd like a direct installation from the Integrations Directory, your provided installation URL should always forward the user immediately to an OAuth authorization screen. You should never add interstitial pages within that flow.

"Learn more" listing

The "learn more" listing is used when a user cannot use GitHub OAuth to sign up for an account within
your integration. You will provide a URL that will link a "learn more" button within your
listing to your website. This type of listing is only used when OAuth is not available before
account creation.

Send us your information

In addition to this checklist, please follow the Marketing Guidelines as well.  The best format for delivery is Markdown (.md) or plain text (.txt).

Please attach images at the proper resolution. We aren't able to extract photos from PDFs or Word docs.

Once you're ready, just send the materials over email to partnerships@github.com. Thanks! We're looking forward to reviewing your listing.

Overview

Getting your integration listed

Marketing guidelines

This website is a public GitHub repository. Please help us by forking the project and adding to it.

API Status


text:
package org.apache.pluto.container.om.portlet.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;

import org.apache.pluto.container.om.portlet.ContainerRuntimeOption;
import org.apache.pluto.container.om.portlet.CustomPortletMode;
import org.apache.pluto.container.om.portlet.CustomWindowState;
import org.apache.pluto.container.om.portlet.EventDefinition;
import org.apache.pluto.container.om.portlet.Filter;
import org.apache.pluto.container.om.portlet.FilterMapping;
import org.apache.pluto.container.om.portlet.Listener;
import org.apache.pluto.container.om.portlet.PortletApplicationDefinition;
import org.apache.pluto.container.om.portlet.PortletDefinition;
import org.apache.pluto.container.om.portlet.PublicRenderParameter;
import org.apache.pluto.container.om.portlet.SecurityConstraint;
import org.apache.pluto.container.om.portlet.UserAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Portlet application definition
 *
 * @author Scott Nicklous
 */
public class PortletApplicationDefinitionImpl implements
      PortletApplicationDefinition {

   /** Logger. */
   private static final Logger LOG = LoggerFactory.getLogger(PortletApplicationDefinitionImpl.class);

   private String id;
   private String name;
   private String contextPath;
   private String version = "3.0";
   private String resourceBundle;
   private String defaultNamespace;

   private final List<PublicRenderParameter> prps = new ArrayList<PublicRenderParameter>();
   private final List<PortletDefinition> portlets = new ArrayList<PortletDefinition>();
   private final List<EventDefinition> events =     new ArrayList<EventDefinition>();
   private final List<CustomPortletMode> cpms =     new ArrayList<CustomPortletMode>();
   private final List<CustomWindowState> cwss =     new ArrayList<CustomWindowState>();
   private final List<UserAttribute> uattrs =       new ArrayList<UserAttribute>();
   private final List<Filter> filters =             new ArrayList<Filter>();
   private final List<FilterMapping> fmaps =        new ArrayList<FilterMapping>();
   private final List<ContainerRuntimeOption> cros = new ArrayList<ContainerRuntimeOption>();

   // for the locale - encoding mappings from the web.xml
   private final Map<Locale, String> localemap = new HashMap<Locale, String>();

   private final List<Listener> listeners = new ArrayList<Listener>();
   private final List<SecurityConstraint> constraints = new ArrayList<SecurityConstraint>();

   /**
    * Default constructor
    */
   public PortletApplicationDefinitionImpl() {
   }

   /**
    * Copy constructor. This class is written such that the accessors copy the
    * objects being returned, so the return values can be directly used in the
    * copy constructor.
    *
    * @param pad     The portlet application definition
    */
   public PortletApplicationDefinitionImpl(PortletApplicationDefinition pad) {
      this.contextPath = pad.getContextPath();
      this.id = pad.getId();
      this.name = pad.getName();
      this.version = pad.getVersion();
      this.resourceBundle = pad.getResourceBundle();
      this.defaultNamespace = pad.getDefaultNamespace();

      for (PortletDefinition pd : pad.getPortlets()) {
         portlets.add(pd);
      }
      for (EventDefinition item : pad.getEventDefinitions()) {
         events.add(item);
      }
      for (PublicRenderParameter prp : pad.getPublicRenderParameters()) {
         prps.add(prp);
      }
      for (CustomPortletMode cpm : pad.getCustomPortletModes()) {
         cpms.add(cpm);
      }
      for (CustomWindowState item : pad.getCustomWindowStates()) {
         cwss.add(item);
      }
      for (UserAttribute ua : pad.getUserAttributes()) {
         uattrs.add(ua);
      }
      for (Filter f : pad.getFilters()) {
         filters.add(f);
      }
      for (FilterMapping fm : pad.getFilterMappings()) {
         fmaps.add(fm);
      }
      for (ContainerRuntimeOption cro : pad.getContainerRuntimeOptions()) {
         cros.add(cro);
      }

      localemap.putAll(pad.getLocaleEncodingMappings());

      if (pad.getListeners() != null) {
         for (Listener l : pad.getListeners()) {
            listeners.add(new ListenerImpl(l));
         }
      }
      constraints.addAll(pad.getSecurityConstraints());

   }

   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#getName()
    */
   @Override
   public String getName() {
      return name;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#setName(java.lang.String)
    */
   @Override
   public void setName(String name) {
      this.name = name;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#getContextPath()
    */
   @Override
   public String getContextPath() {
      return contextPath;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#setContextPath(java.lang.String)
    */
   @Override
   public void setContextPath(String contextPath) {
      this.contextPath = contextPath;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#getVersion()
    */
   @Override
   public String getVersion() {
      return version;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#setVersion(java.lang.String)
    */
   @Override
   public void setVersion(String version) {
      this.version = version;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#getResourceBundle()
    */
   @Override
   public String getResourceBundle() {
      return resourceBundle;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#setResourceBundle(java.lang.String)
    */
   @Override
   public void setResourceBundle(String resourceBundle) {
      this.resourceBundle = resourceBundle;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#getDefaultNamespace()
    */
   @Override
   public String getDefaultNamespace() {
      return (defaultNamespace == null) ? XMLConstants.NULL_NS_URI : defaultNamespace;
   }

   /* (non-Javadoc)
    * @see org.apache.pluto.container.om.portlet.PortletApplicationDefinition#setDefaultNamespace(java.lang.String)
    */
   @Override
   public void setDefaultNamespace(String defaultNamespace) {
      this.defaultNamespace = defaultNamespace;
   }

   @Override
   public PortletDefinition getPortlet(String portletName) {
      PortletDefinition pd = null;
      for (PortletDefinition item : portlets) {
         if (item.getPortletName().equals(portletName)) {
            pd = new PortletDefinitionImpl(item);
         }
      }
      return pd;
   }

   @Override
   public List<PortletDefinition> getPortlets() {
      ArrayList<PortletDefinition> ret = new ArrayList<PortletDefinition>();
      for (PortletDefinition pd : portlets) {
         ret.add(new PortletDefinitionImpl(pd));
      }
      return ret;
   }

   /**
    * The portlet name can end with the wildcard character '*'. The wildcard
    * matches any suffix. For filter mapping.
    *
    * @return     The list of matching portlets
    */
   @Override
   public List<PortletDefinition> getMatchingPortlets(String portletName) {
      ArrayList<PortletDefinition> ret = new ArrayList<PortletDefinition>();
      String match = portletName.replaceAll("^(.*)\\*$",  "$1");
      for (PortletDefinition pd : portlets) {
         if (pd.getPortletName().startsWith(match)) {
            ret.add(new PortletDefinitionImpl(pd));
         }
      }
      return ret;
   }

   @Override
   public void addPortlet(PortletDefinition pd) {
      if (portlets.remove(pd)) {
         LOG.debug("Removed duplicate portlet: " + pd.getPortletName());
      }
      portlets.add( pd);
   }

   @Override
   public boolean removePortlet(PortletDefinition pd) {
      return portlets.remove(pd);
   }

   @Override
   public List<EventDefinition> getEventDefinitions() {
      ArrayList<EventDefinition> items = new ArrayList<EventDefinition>();
      for (EventDefinition item : events) {
         items.add(new EventDefinitionImpl(item));
      }
      return items;
   }

   @Override
   public EventDefinition getEventDefinition(QName qn) {
      EventDefinition ret = null;
      for (EventDefinition item : events) {
         if (item.getQName().equals(qn)) {
            ret = new EventDefinitionImpl(item);
         }
      }
      return ret;
   }

   @Override
   public void addEventDefinition(EventDefinition ed) {
      if (events.remove(ed)) {
         LOG.debug("Removed duplicate event definition: " + ed.getQName());
      }
      events.add(ed);
   }

   @Override
   public boolean removeEventDefinition(EventDefinition ed) {
      return events.remove(ed);
   }

   @Override
   public PublicRenderParameter getPublicRenderParameter(String identifier) {
      PublicRenderParameter ret = null;
      for (PublicRenderParameter prp : prps) {
         if (prp.getIdentifier().equals(identifier)) {
            ret = new PublicRenderParameterImpl(prp);
         }
      }
      return ret;
   }

   @Override
   public List<PublicRenderParameter> getPublicRenderParameters() {
      ArrayList<PublicRenderParameter> items = new ArrayList<PublicRenderParameter>();
      for (PublicRenderParameter item : prps) {
         items.add(new PublicRenderParameterImpl(item));
      }
      return items;
   }

   @Override
   public void addPublicRenderParameter(PublicRenderParameter prp) {
      int ii = prps.indexOf(prp);
      if (ii >= 0) {

         PublicRenderParameter tprp = prps.get(ii);
         prps.remove(prp);

         StringBuilder txt = new StringBuilder(128);
         txt.append("Removed duplicate public render parameter definition for QName: ");
         txt.append(tprp.getQName());
         txt.append(", id: ").append(tprp.getIdentifier());
         LOG.debug(txt.toString());
      }
      prps.add(prp);
   }

   @Override
   public boolean removePublicRenderParameter(PublicRenderParameter prp) {
      return prps.remove(prp);
   }

   @Override
   public CustomPortletMode getCustomPortletMode(String arg) {
      CustomPortletMode ret = null;
      for (CustomPortletMode item : cpms) {
         if (item.getPortletMode().equals(arg)) {
            ret = new CustomPortletModeImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<CustomPortletMode> getCustomPortletModes() {
      ArrayList<CustomPortletMode> items = new ArrayList<CustomPortletMode>();
      for (CustomPortletMode item : cpms) {
         items.add(new CustomPortletModeImpl(item));
      }
      return items;
   }

   @Override
   public void addCustomPortletMode(CustomPortletMode cpm) {
      if (cpms.remove(cpm)) {
         LOG.debug("Removed duplicate custom portlet mode: " + cpm.getPortletMode());
      }
      cpms.add(cpm);
   }

   @Override
   public boolean removeCustomPortletMode(CustomPortletMode pm) {
      return cpms.remove(pm);
   }

   @Override
   public CustomWindowState getCustomWindowState(String arg) {
      CustomWindowState ret = null;
      for (CustomWindowState item : cwss) {
         if (item.getWindowState().equals(arg)) {
            ret = new CustomWindowStateImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<CustomWindowState> getCustomWindowStates() {
      ArrayList<CustomWindowState> items = new ArrayList<CustomWindowState>();
      for (CustomWindowState item : cwss) {
         items.add(new CustomWindowStateImpl(item));
      }
      return items;
   }

   @Override
   public void addCustomWindowState(CustomWindowState cws) {
      if (cwss.remove(cws)) {
         LOG.debug("Removed duplicate custom window state: " + cws.getWindowState());
      }
      cwss.add(cws);
   }

   @Override
   public boolean removeCustomWindowState(CustomWindowState ws) {
      return cwss.remove(ws);
   }

   @Override
   public UserAttribute getUserAttribute(String arg) {
      UserAttribute ret = null;
      for (UserAttribute item : uattrs) {
         if (item.getName().equals(arg)) {
            ret = new UserAttributeImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<UserAttribute> getUserAttributes() {
      ArrayList<UserAttribute> items = new ArrayList<UserAttribute>();
      for (UserAttribute item : uattrs) {
         items.add(new UserAttributeImpl(item));
      }
      return items;
   }

   @Override
   public void addUserAttribute(UserAttribute ua) {
      if (uattrs.remove(ua)) {
         LOG.debug("Removed duplicate user attribute: " + ua.getName());
      }
      uattrs.add(ua);
   }

   @Override
   public boolean removeUserAttribute(UserAttribute ua) {
      return uattrs.remove(ua);
   }

   @Override
   public Filter getFilter(String arg) {
      Filter ret = null;
      for (Filter item : filters) {
         if (item.getFilterName().equals(arg)) {
            ret = new FilterImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<Filter> getFilters() {
      ArrayList<Filter> items = new ArrayList<Filter>();
      for (Filter item : filters) {
         items.add(new FilterImpl(item));
      }
      return items;
   }

   @Override
   public void addFilter(Filter filter) {
      // If the filter class is null, remove the filter definition, otherwise replace it
      boolean removed = filters.remove(filter);

      if (removed) {
         LOG.debug("Removed duplicate filter definition: " + filter.getFilterName());
      }

      // If a filter class is present, add the new one. Otherwise, if the filter was
      // removed, get rid of the filter mapping as well.
      if (filter.getFilterClass() != null && filter.getFilterClass().length() > 0) {
         filters.add(filter);
         // sort by ordinal. for JSR286 portlets, the ordinal will always be 0, so
         // the list will remain in the original order.
         Collections.sort(filters, new FilterComparator());
      } else {
         LOG.debug("No filter class for filter. Deleting filter mapping. filter name: " + filter.getFilterName());
         removeFilterMapping(getFilterMapping(filter.getFilterName()));
      }
   }

   @Override
   public boolean removeFilter(Filter filter) {
      return filters.remove(filter);
   }

   @Override
   public FilterMapping getFilterMapping(String arg) {
      FilterMapping ret = null;
      for (FilterMapping item : fmaps) {
         if (item.getFilterName().equals(arg)) {
            ret = new FilterMappingImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<FilterMapping> getFilterMappings() {
      ArrayList<FilterMapping> items = new ArrayList<FilterMapping>();
      for (FilterMapping item : fmaps) {
         items.add(new FilterMappingImpl(item));
      }
      return items;
   }

   @Override
   public void addFilterMapping(FilterMapping fm) {
      // If the filter mapping has no portlet names, remove the filter mapping definition, otherwise replace it
      if (fmaps.remove(fm)) {
         LOG.debug("Removed duplicate filter mapping: " + fm.getFilterName());
      }
      if (fm.getPortletNames().size() > 0) {
         fmaps.add(fm);
      } else {
         LOG.debug("No portlet names for filter mapping. Filter name: " + fm.getFilterName());
      }
   }

   @Override
   public boolean removeFilterMapping(FilterMapping fm) {
      return fmaps.remove(fm);
   }

   @Override
   public ContainerRuntimeOption getContainerRuntimeOption(String arg) {
      ContainerRuntimeOption ret = null;
      for (ContainerRuntimeOption item : cros) {
         if (item.getName().equals(arg)) {
            ret = new ContainerRuntimeOptionImpl(item);
         }
      }
      return ret;
   }

   @Override
   public List<ContainerRuntimeOption> getContainerRuntimeOptions() {
      ArrayList<ContainerRuntimeOption> items = new ArrayList<ContainerRuntimeOption>();
      for (ContainerRuntimeOption item : cros) {
         items.add(new ContainerRuntimeOptionImpl(item));
      }
      return items;
   }

   @Override
   public void addContainerRuntimeOption(ContainerRuntimeOption cro) {
      if (cros.remove(cro)) {
         LOG.debug("Removed duplicate container runtime option: " + cro.getName());
      }
      cros.add(cro);
   }

   @Override
   public boolean removeRuntimeOption(ContainerRuntimeOption cro) {
      return cros.remove(cro);
   }

   @Override
   public Listener getListener(String name) {
      for (Listener l : listeners) {
         if (l.getListenerName().equals(name)) {
            return new ListenerImpl(l);
         }
      }
      return null;
   }

   @Override
   public List<Listener> getListeners() {
      ArrayList<Listener> list = new ArrayList<Listener>();
      for (Listener l : listeners) {
         list.add(new ListenerImpl(l));
      }
      return list;
   }

   @Override
   public void addListener(Listener listener) {

      // Remove the listener if already present. This is based on the listener class
      // for JSR 286 portlets and on the listener name for JSR 362 portlets

      if (version.equals("3.0")) {
         for (int ii = 0; ii < listeners.size(); ii++) {
            if (listeners.get(ii).getListenerName().equals(listener.getListenerName())) {
               listeners.remove(ii);
               LOG.debug("Removed duplicate listener with name: " + listener.getListenerName());
               break;
            }
         }
      } else {

         // If the listener class is null, remove the listener definition, otherwise replace it
         if (listeners.remove(listener)) {
            LOG.debug("Removed duplicate listener for class: " + listener.getListenerClass());
         }
      }

      if (listener.getListenerClass() != null && listener.getListenerClass().length() > 0) {
         listeners.add(listener);
         // sort by ordinal. for JSR286 portlets, the ordinal will always be 0, so
         // the list will remain in the original order.
         Collections.sort(listeners, new ListenerComparator());
      } else {
         LOG.debug("No listener class for listener: " + listener.getListenerName());
      }
   }

   @Override
   public boolean removeListener(Listener listener) {
      return listeners.remove(listener);
   }

   @Override
   public List<SecurityConstraint> getSecurityConstraints() {
      ArrayList<SecurityConstraint> scs = new ArrayList<SecurityConstraint>();
      for (SecurityConstraint sc : constraints) {
         scs.add(new SecurityConstraintImpl(sc));
      }
      return scs;
   }

   @Override
   public void addSecurityConstraint(SecurityConstraint sc) {
      if (constraints.remove(sc)) {
         LOG.debug("Removed duplicate security constraint: " + sc.getUserDataConstraint().getTransportGuarantee());
      }
      constraints.add(sc);
   }

   @Override
   public boolean removeSecurityCOnstraint(SecurityConstraint sc) {
      return constraints.remove(sc);
   }

   @Override
   public Map<Locale, String> getLocaleEncodingMappings() {
      Map<Locale, String> lem = new HashMap<Locale, String>();
      for (Locale l : localemap.keySet()) {
         lem.put((Locale) l.clone(), localemap.get(l));
      }
      return lem;
   }

   @Override
   public void addLocaleEncodingMapping(Locale locale, String encoding) {
      localemap.put(locale, encoding);
   }

   @Override
   public String removeLocaleEncodingMapping(Locale locale) {
      return localemap.remove(locale);
   }

}