text:
typedef enum
{
   kLSHTTPContinueStatusCode                       = 100,
   kLSHTTPSwitchingProtocolsStatusCode             = 101,
   kLSHTTPOKStatusCode                             = 200,
   kLSHTTPCreatedStatusCode                        = 201,
   kLSHTTPAcceptedStatusCode                       = 202,
   kLSHTTPNonAuthoritativeInformationStatusCode    = 203,
   kLSHTTPNoContentStatusCode                      = 204,
   kLSHTTPResetContentStatusCode                   = 205,
   kLSHTTPPartialContentStatusCode                 = 206,
   kLSHTTPMultipleChoicesStatusCode                = 300,
   kLSHTTPMovedPermanentlyStatusCode               = 301,
   kLSHTTPFoundStatusCode                          = 302,
   kLSHTTPSeeOtherStatusCode                       = 303,
   kLSHTTPNotModifiedStatusCode                    = 304,
   kLSHTTPUseProxyStatusCode                       = 305,
   kLSHTTPTemporaryRedirectStatusCode              = 307,
   kLSHTTPBadRequestStatusCode                     = 400,
   kLSHTTPUnauthorizedStatusCode                   = 401,
   kLSHTTPPaymentRequiredStatusCode                = 402,
   kLSHTTPForbiddenStatusCode                      = 403,
   kLSHTTPNotFoundStatusCode                       = 404,
   kLSHTTPMethodNotAllowedStatusCode               = 405,
   kLSHTTPNotAcceptableStatusCode                  = 406,
   kLSHTTPProxyAuthenticationRequiredStatusCode    = 407,
   kLSHTTPRequestTimeoutStatusCode                 = 408,
   kLSHTTPConflictStatusCode                       = 409,
   kLSHTTPGoneStatusCode                           = 410,
   kLSHTTPLengthRequiredStatusCode                 = 411,
   kLSHTTPPreconditionFailedStatusCode             = 412,
   kLSHTTPRequestEntityTooLargeStatusCode          = 413,
   kLSHTTPRequestURITooLongStatusCode              = 414,
   kLSHTTPUnsupportedMediaTypeStatusCode           = 415,
   kLSHTTPRequestedRangeNotSatisfiableStatusCode   = 416,
   kLSHTTPExpectationFailedStatusCode              = 417,
   kLSHTTPInternalServerErrorStatusCode            = 500,
   kLSHTTPNotImplementedStatusCode                 = 501,
   kLSHTTPBadGatewayStatusCode                     = 502,
   kLSHTTPServiceUnavailableStatusCode             = 503,
   kLSHTTPGatewayTimeoutStatusCode                 = 504,
   kLSHTTPHTTPVersionNotSupportedStatusCode        = 505
} LSHTTPStatusCode;
////////////////////////////////////////////////////////////////////////////////
@protocol LSHTTPRequest;
@protocol LSHTTPHeaders;
@protocol LSHTTPBody;
////////////////////////////////////////////////////////////////////////////////

#pragma mark -
////////////////////////////////////////////////////////////////////////////////
//! HTTP response message protocol.
@protocol LSHTTPResponse <NSObject>

//! Original HTTP request message.
@property (atomic, retain, readonly) id<LSHTTPRequest> request;

//! HTTP status code.
@property (atomic, assign, readonly) LSHTTPStatusCode statusCode;

//! HTTP reason phrase.
@property (atomic, assign, readonly) NSString *reasonPhrase;

//! HTTP header fields.
@property (atomic, retain, readonly) id<LSHTTPHeaders> headers;

//! HTTP reponse message body.
@property (atomic, retain, readonly) id<LSHTTPBody> body;

//! Check whether response is successful.
//! @returns YES if client's request was successfully received, understood and
//!   accepted; NO - otherwise.
- (BOOL)isSuccessful;

@end

#pragma mark -
////////////////////////////////////////////////////////////////////////////////
//! HTTP response message object-oriented wrapper.
@interface LSHTTPResponse : NSObject <LSHTTPResponse>

//! Initialize HTTP response message.
//! @param request Original HTTP request message.
//! @param code HTTP status code.
//! @param headersValues HTTP header fields values.
//! @param bodyData HTTP response message body data.
//! @returns HTTP response message.
- (instancetype)initWithRequest:(id<LSHTTPRequest>)request
   statusCode:(LSHTTPStatusCode)code headersValues:(NSDictionary *)headersValues
   bodyData:(NSData *)bodyData;

@end


text:
/*****  Dictionary Primitives Facility Implementation  *****/

/***************************
 *****  Facility Name  *****
 ***************************/

#define FacilityName pfDICTIONARY

/*******************************************
 ******  Header and Declaration Files  *****
 *******************************************/

/*****  System  *****/
#include "Vk.h"

/*****  Facility  *****/
#include "VFragment.h"

#include "selector.h"
#include "uvector.h"

#include "venvir.h"
#include "verr.h"
#include "vfac.h"
#include "vstdio.h"
#include "vprimfns.h"

#include "RTblock.h"
#include "RTdictionary.h"
#include "RTlink.h"
#include "RTlstore.h"
#include "RTptoken.h"
#include "RTvector.h"

#include "RTcharuv.h"
#include "RTintuv.h"
#include "RTrefuv.h"

#include "VCollectionOf.h"
#include "VCollectionOfStrings.h"

/*****  Self  *****/
#include "PFdictionary.h"

/*******************************
 *******************************
 *****  Primitive Indices  *****
 *******************************
 *******************************/
/*---------------------------------------------------------------------------
 * Three entries must be made in this file for every primitive in the system -
 * one to assign the primitive an index, one to define its code body, and one
 * to describe it to the virtual machine and debugger.  This section contains
 * the entries that assign indices to the primitives.
 *
 * The numeric indices associated in this section with each of the primitives
 * are the system wide 'indices' by which the primitives are known.  These
 * indices are stored in permanent object memory;  consequently, once assigned,
 * they must not be changed or deleted.  To avoid an fatal error at system
 * startup, the largest index assigned in this section must be less than
 * 'V_PF_MaxPrimitiveIndex' (see "vprimfns.h").
 * If necessary this maximum can be increased.
 *---------------------------------------------------------------------------
 */
/*======================================*
 *  This module currently has indices:  *
 *	  77 -  79			*
 *	 111 - 114			*
 *	 151 - 153                      *
 *======================================*/

/***************************************************
 *****  Property Update and Access Primitives  *****
 ***************************************************/

#define XLocateOrAddDictionaryPropertySlot	 77
#define XLocateDictionaryPropertySlot		 78
#define XDeleteDictionaryPropertySlot		 79

/***************************************************
 *****  Selector Update and Access Primitives  *****
 ***************************************************/

#define XLocateOrAddEntryInDictionaryOf		111
#define XLocateEntryInDictionaryOf		112
#define XDeleteFromDictionaryOf			113
#define XDictionaryContents			114

/*******************************************************
 *****  String Store Update and Access Primitives  *****
 *******************************************************/

#define XLocateOrAddToStringStore		151
#define XLocateInStringStore			152
#define XDeleteFromStringStore			153

/***********************************
 ***********************************
 *****  Primitive Definitions  *****
 ***********************************
 ***********************************/

/************************************************
 *****  Property Slot Definition Primitive  *****
 ************************************************/

V_DefinePrimitive (LocateOrAddDictionaryPropertySlot) {
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pDictionary = rCurrent.storeCPD ();

    if (RTYPE_C_Dictionary != pDictionary->RType ()) {
	pTask->loadDucWithNA ();
	return;
    }

    DSC_Descriptor propertySlotDescriptor;

    M_CPD *pPropertySubsetCPD = rtDICTIONARY_CPD_PropertySubsetCPD (pDictionary);
    if (rCurrent.holdsAScalarReference ()) {
	rtREFUV_Type_Reference propertySlotReference;

	rtLINK_LocateOrAddFromRef (
	    pPropertySubsetCPD,
	    &DSC_Descriptor_Scalar (rCurrent),
	    &propertySlotReference
	);

	propertySlotDescriptor.constructConstant (
	    V_TOTSC_PToken,
	    rtDICTIONARY_CPD_PropertyPrototypesCPD (pDictionary),
	    propertySlotReference
	);
    }
    else if (rCurrent.holdsALink ()) {
	propertySlotDescriptor.constructLink (
	    rtDICTIONARY_CPD_PropertyPrototypesCPD (pDictionary), rtLINK_LocateOrAddFromLC (
		pPropertySubsetCPD, DSC_Descriptor_Link (rCurrent), NilOf (rtLINK_CType**)
	    )
	);
    }
    else {
	rCurrent.complainAboutBadPointerType ("LocateOrAddDictionaryPropertySlot");
	propertySlotDescriptor.construct ();
    }
    rtDICTIONARY_Align (pDictionary);

    pPropertySubsetCPD->release ();

    pTask->loadDucWithMoved (propertySlotDescriptor);
}

/********************************************
 *****  Property Slot Access Primitive  *****
 ********************************************/

V_DefinePrimitive (LocateDictionaryPropertySlot) {
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pDictionary = rCurrent.storeCPD ();

    if (RTYPE_C_Dictionary != pDictionary->RType ()) {
	pTask->loadDucWithNA ();
	return;
    }

    M_CPD *pPropertySubsetCPD = rtDICTIONARY_CPD_PropertySubsetCPD (pDictionary);
    if (rCurrent.holdsAScalarReference ()) {
	rtREFUV_Type_Reference propertySlotReference;

	if (rtLINK_LookupUsingRefKey (
		pPropertySubsetCPD,
		&DSC_Descriptor_Scalar (rCurrent),
		rtLINK_LookupCase_EQ,
		INT_MAX,
		&propertySlotReference
	    )
	)
	{
	    DSC_Descriptor propertySlotDescriptor;
	    propertySlotDescriptor.constructConstant (
		V_TOTSC_PToken,
		rtDICTIONARY_CPD_PropertyPrototypesCPD (pDictionary),
		propertySlotReference
	    );
	    pTask->loadDucWithMoved (propertySlotDescriptor);
	}
	else
	    pTask->loadDucWithNA ();
    }
    else if (rCurrent.holdsALink ()) {
	rtLINK_CType *pLocationsLC;
	rtLINK_CType *pLocatedLC;
	rtLINK_LookupUsingLCKey (
	    pPropertySubsetCPD,
	    DSC_Descriptor_Link (rCurrent),
	    rtLINK_LookupCase_EQ,
	    INT_MAX,
	    &pLocationsLC,
	    &pLocatedLC
	);

	VDescriptor* pGuardedDatum = pTask->loadDucWithGuardedDatum (pLocatedLC);
	if (pGuardedDatum) {
	    DSC_Descriptor iGuardedDatum;
	    iGuardedDatum.constructLink (
		rtDICTIONARY_CPD_PropertyPrototypesCPD (pDictionary), pLocationsLC
	    );
	    pGuardedDatum->setToMoved (iGuardedDatum);
	}
	else
	    pLocationsLC->release ();
    }
    else rCurrent.complainAboutBadPointerType ("LocateOrAddDictionaryPropertySlot");

    pPropertySubsetCPD->release ();
}

/**********************************************
 *****  Property Slot Deletion Primitive  *****
 **********************************************/

V_DefinePrimitive (DeleteDictionaryPropertySlot) {
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pDictionary = rCurrent.storeCPD ();

    if (RTYPE_C_Dictionary != pDictionary->RType ()) {
	pTask->loadDucWithNA ();
	return;
    }

    M_CPD *pPropertySubsetCPD = rtDICTIONARY_CPD_PropertySubsetCPD (pDictionary);
    if (rCurrent.holdsAScalarReference ()) {
	pTask->loadDucWithBoolean (
	    rtLINK_DeleteRefSelectedElement (
		pPropertySubsetCPD, &DSC_Descriptor_Scalar (rCurrent)
	    )
	);
    }
    else if (rCurrent.holdsALink ()) {
	rtLINK_CType *pDeletedLC;
	rtLINK_DeleteLCSelectedElements (
	    pPropertySubsetCPD, DSC_Descriptor_Link (rCurrent), &pDeletedLC
	);
	pTask->loadDucWithPredicateResult (pDeletedLC, pDeletedLC->Complement ());
    }
    else {
	rCurrent.complainAboutBadPointerType ("LocateOrAddDictionaryPropertySlot");
    }
    pPropertySubsetCPD->release ();
}

/*****************************************************
 *****  Associative Result Generation Utilities  *****
 *****************************************************/

/*---------------------------------------------------------------------------
 *****  Utility to return a 'Locate' primitive scalar result.
 *
 *  Arguments:
 *	pDictionary		- a standard CPD for the dictionary searched.
 *	rAssociativeResult	- a reference to an associative result object.
 *
 *  Returns:
 *	NOTHING
 *
 *****/
PrivateFnDef void LoadAWithScalarLocateResult (
    VPrimitiveTask *pTask, M_CPD *pDictionary, VAssociativeResult &rAssociation
) {
    if (!rAssociation.targetReferenceIsValid ())
	pTask->loadDucWithNA ();
    else {
	M_CPD *pDictionaryPToken = rAssociation.targetPToken ();
	pDictionary->retain ();
	pDictionaryPToken->retain ();
	pTask->loadDucWithReference (
	    pDictionary, pDictionaryPToken, rAssociation.targetReferenceScalar ()
	);
    }
}

/*---------------------------------------------------------------------------
 *****  Utility to return a 'Locate' primitive collection result.
 *
 *  Arguments:
 *	pDictionary		- a standard CPD for the dictionary searched.
 *	pDistribution		- a standard CPD for the distribution u-vector
 *				  to be applied to the result.  'distribution'
 *				  will be ASSIGNED into the result.
 *	pLocatedLC		- an optional ('Nil' if absent) address of a
 *				  link constructor specifying the selectors
 *				  (relative to the positional state of
 *				  'distribution') actually found.  'pLocatedLC'
 *                                will be ASSIGNED into the result.
 *	pLocationsLC		- the address of a link constructor specifying
 *				  the dictionary positions of the found
 *				  selectors.  'pLocationsLC' will be ASSIGNED
 *				  into the result.
 *
 *  Returns:
 *	NOTHING
 *
 *****/
PrivateFnDef void LoadAWithGeneralLocateResult (
    VPrimitiveTask*		pTask,
    M_CPD*			pDictionary,
    M_CPD*			pDistribution,
    rtLINK_CType*		pLocatedLC,
    rtLINK_CType*		pLocationsLC
)
{
    VDescriptor* pGuardedDatum = pTask->loadDucWithGuardedDatum (pLocatedLC);
    if (pGuardedDatum) {
	pDictionary->retain ();

	DSC_Descriptor iGuardedDatum;
	iGuardedDatum.constructLink (pDictionary, pLocationsLC);

	pGuardedDatum->setToMoved (iGuardedDatum);

	if (pDistribution) {
	    pTask->distributeDuc (pDistribution);
	    pDistribution->release ();
	}
    }
    else {
	if (pDistribution)
	    pDistribution->release ();
	pLocationsLC->release ();
    }
}

/*************************************
 *****  Set Insertion Primitive  *****
 *************************************/

V_DefinePrimitive (LocateOrAddToSet) {
    static char const *const pThisPrimitive = "LocateOrAddToSet";

/*****  Acquire and decode the argument...  *****/
    M_CPD *pSet;
    switch (V_TOTSC_Primitive) {
    case XLocateOrAddEntryInDictionaryOf:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent (KS__LocateOrAddDictionaryEntry4);
	    return;
	}
	pSet = pTask->ducDictionary ();
	break;

    case XLocateOrAddToStringStore:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent ("clusterInsert:");
	    return;
	}
	pSet = pTask->ducStore ();
	pSet->retain ();
	break;

    default:
	pTask->raiseUnimplementedAliasException (pThisPrimitive);
	break;
    }

/*****  ...decode the key type, ...  *****/
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pKeyStore = rCurrent.storeCPD ();

    RTYPE_Type xKeyPointerRType = rCurrent.pointerRType ();

/*****  ... perform the operation, ...  *****/
    VAssociativeResult iAssociation (true);
    M_CPD *pDistribution;
    switch (pKeyStore->RType ()) {
    case RTYPE_C_ValueStore:
	if (RTYPE_C_IntUV == xKeyPointerRType) {
	    VCollectionOfUnsigned32 iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.insertInto (pSet, pDistribution, iAssociation);
	}
	break;

    case RTYPE_C_Block:
    case RTYPE_C_ListStore: {
	    VCollectionOfStrings iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.insertInto (pSet, pDistribution, iAssociation);
	}
	break;

    default:
	pSet->release ();
	pTask->raiseException (
	    EC__InternalInconsistency,
	    "%s: Not A String/Selector Store: '%s'",
	    pThisPrimitive,
	    pKeyStore->RTypeName ()
	);
	break;
    }

/*****  ... and return the result:  *****/
    if (!iAssociation.isValid ())
	pTask->loadDucWithNA ();
    else if (iAssociation.isScalar ())
	LoadAWithScalarLocateResult (pTask, pSet, iAssociation);
    else LoadAWithGeneralLocateResult (
	pTask,
	pSet,
	pDistribution,
	NilOf (rtLINK_CType*),
	iAssociation.claimedTargetReference ()
    );
    pSet->release ();
}

/**************************************************
 *****  String/Selector Set Locate Primitive  *****
 **************************************************/

V_DefinePrimitive (LocateInSet) {
    static char const *const pThisPrimitive = "LocateInSet";

/*****  Acquire and decode the argument...  *****/
    M_CPD *pSet;
    switch (V_TOTSC_Primitive) {
    case XLocateEntryInDictionaryOf:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent (KS__LocateDictionaryEntryFor);
	    return;
	}
	pSet = pTask->ducDictionary ();
	break;
    case XLocateInStringStore:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent ("clusterLocate:");
	    return;
	}
	pSet = pTask->ducStore ();
	pSet->retain ();
	break;
    default:
	pTask->raiseUnimplementedAliasException (pThisPrimitive);
	break;
    }

/*****  ...decode the selector type presented to this routine, ...  *****/
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pKeyStore = rCurrent.storeCPD ();

    RTYPE_Type xKeyPointerRType = rCurrent.pointerRType ();

/*****  ... perform the operation, ...  *****/
    M_CPD *pDistribution;
    VAssociativeResult iAssociation (true);
    switch (pKeyStore->RType ()) {
    case RTYPE_C_ValueStore:
	if (RTYPE_C_IntUV == xKeyPointerRType) {
	    VCollectionOfUnsigned32 iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.locateIn (pSet, pDistribution, iAssociation);
	}
	break;

    case RTYPE_C_Block:
    case RTYPE_C_ListStore: {
	    VCollectionOfStrings iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.locateIn (pSet, pDistribution, iAssociation);
	}
	break;

    default:
	pSet->release ();
	pTask->raiseException (
	    EC__InternalInconsistency,
	    "%s: Not A String/Selector Store: '%s'",
	    pThisPrimitive,
	    pKeyStore->RTypeName ()
	);
	break;
    }

/*****  ... and return the result:  *****/
    if (!iAssociation.isValid ())
	pTask->loadDucWithNA ();
    else if (iAssociation.isScalar ())
	LoadAWithScalarLocateResult (pTask, pSet, iAssociation);
    else LoadAWithGeneralLocateResult (
	pTask,
	pSet,
	pDistribution,
	iAssociation.claimedSourceReference (),
	iAssociation.claimedTargetReference ()
    );
    pSet->release ();
}

/**************************************************
 *****  String/Selector Set Delete Primitive  *****
 **************************************************/

V_DefinePrimitive (DeleteFromSet) {
    static char const *const pThisPrimitive = "DeleteFromSet";

/*****  Acquire and decode the argument...  *****/
    M_CPD *pSet;
    switch (V_TOTSC_Primitive) {
    case XDeleteFromDictionaryOf:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent (KS__DeleteDictionaryEntryFor);
	    return;
	}
	pSet = pTask->ducDictionary ();
	break;
    case XDeleteFromStringStore:
	if (!pTask->loadDucWithNextParameterAsMonotype ()) {
	    pTask->sendBinaryConverseWithCurrent ("clusterDelete:");
	    return;
	}
	pSet = pTask->ducStore ();
	pSet->retain ();
	break;
    default:
	pTask->raiseUnimplementedAliasException (pThisPrimitive);
	break;
    }

/*****  ...decode the selector type presented to this routine, ...  *****/
    DSC_Descriptor& rCurrent = pTask->getCurrent ();

    M_CPD *pKeyStore = rCurrent.storeCPD ();

    RTYPE_Type xKeyPointerRType = rCurrent.pointerRType ();

/*****  ... perform the operation, ...  *****/
    M_CPD *pDistribution;
    VAssociativeResult iAssociation (true);
    switch (pKeyStore->RType ()) {
    case RTYPE_C_ValueStore:
	if (RTYPE_C_IntUV == xKeyPointerRType) {
	    VCollectionOfUnsigned32 iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.deleteFrom (pSet, pDistribution, iAssociation);
	}
	break;

    case RTYPE_C_Block:
    case RTYPE_C_ListStore: {
	    VCollectionOfStrings iKeys (V_TOTSC_PToken, rCurrent);
	    iKeys.deleteFrom (pSet, pDistribution, iAssociation);

	}
	break;

    default:
	pSet->release ();
	pTask->raiseException (
	    EC__InternalInconsistency,
	    "%s: Not A String/Selector Store: '%s'",
	    pThisPrimitive,
	    pKeyStore->RTypeName ()
	);
	break;
    }

/*****  ... and return the result:  *****/
    if (!iAssociation.isValid ())
	pTask->loadDucWithNA ();
    else if (iAssociation.isScalar ())
	pTask->loadDucWithBoolean (iAssociation.sourceReferenceIsValid ());
    else {
	rtLINK_CType *pDeletedLC = iAssociation.claimedSourceReference ();
	pTask->loadDucWithPredicateResult (pDeletedLC, pDeletedLC->Complement ());
	if (pDistribution) {
	    pTask->distributeDuc (pDistribution);
	    pDistribution->release ();
	}
    }
    pSet->release ();
}

/********************************************
 *****  Selector Enumeration Primitive  *****
 ********************************************/

V_DefinePrimitive (DictionaryContents) {
/*****  Obtain the result's container space, ... *****/
    M_ASD *pContainerSpace = pTask->codScratchPad ();

/*****  Obtain the dictionary's contents, ... *****/
    M_CPD *pContentVector; {
	M_CPD *pDictionary = pTask->getSelf ().dictionaryCPD ();
	pContentVector = rtDICTIONARY_Contents (pContainerSpace, pDictionary);
	pDictionary->release ();
    }

/*****  Create an l-store around the vector, ... *****/
    M_CPD *pLStorePTokenCPD = rtPTOKEN_New (pContainerSpace, 1);
    rtLINK_CType *pLStoreDefinitionLC = rtLINK_RefConstructor (pLStorePTokenCPD, -1);
    rtLINK_AppendRepeat (
	pLStoreDefinitionLC, 0, rtVECTOR_CPD_ElementCount (pContentVector)
    );
    pLStoreDefinitionLC->Close (pContentVector, rtVECTOR_CPx_PToken);

    M_CPD *pLStoreCPD = rtLSTORE_NewCluster (pLStoreDefinitionLC, pContentVector);

    pContentVector->release ();
    pLStoreDefinitionLC->release ();

/*****  Load the Duc and return ... *****/
    pTask->loadDucWithReference (pLStoreCPD, pLStorePTokenCPD, 0);
}

/************************************
 ************************************
 *****  Primitive Descriptions  *****
 ************************************
 ************************************/
/*---------------------------------------------------------------------------
 * Three entries must be made in this file for every primitive in the system -
 * one to assign the primitive an index, one to define its code body, and one
 * to describe it to the virtual machine and debugger.  This section contains
 * the entries that describe the primitives to the virtual machine and
 * debugger.
 *---------------------------------------------------------------------------
 */

BeginDescriptions

/***************************************************
 *****  Property Update and Access Primitives  *****
 ***************************************************/

    PD (XLocateOrAddDictionaryPropertySlot,
	"LocateOrAddDictionaryPropertySlot",
	LocateOrAddDictionaryPropertySlot)
    PD (XLocateDictionaryPropertySlot,
	"LocateDictionaryPropertySlot",
	LocateDictionaryPropertySlot)
    PD (XDeleteDictionaryPropertySlot,
	"DeleteDictionaryPropertySlot",
	DeleteDictionaryPropertySlot)

/***************************************************
 *****  Selector Update and Access Primitives  *****
 ***************************************************/

    PD (XLocateOrAddEntryInDictionaryOf,
	"LocateOrAddEntryInDictionaryOf",
	LocateOrAddToSet)
    PD (XLocateEntryInDictionaryOf,
	"LocateEntryInDictionaryOf",
	LocateInSet)
    PD (XDeleteFromDictionaryOf,
	"DeleteFromDictionaryOf",
	DeleteFromSet)

    PD (XDictionaryContents,
	"DictionaryContents",
	DictionaryContents)

/*******************************************************
 *****  String Store Update and Access Primitives  *****
 *******************************************************/

    PD (XLocateOrAddToStringStore,
	"XLocateOrAddToStringStore",
	LocateOrAddToSet)
    PD (XLocateInStringStore,
	"XLocateInStringStore",
	LocateInSet)
    PD (XDeleteFromStringStore,
	"XDeleteFromStringStore",
	DeleteFromSet)

EndDescriptions

/*******************************************************
 *****  The Primitive Dispatch Vector Initializer  *****
 *******************************************************/

/*---------------------------------------------------------------------------
 *****  Internal routine to initialize a portion of the primitive function
 *****	dispatch vector at system startup.
 *
 *  Arguments:
 *	NONE
 *
 *  Returns:
 *	NOTHING - Executed for side effect only.
 *
 *****/
PublicFnDef void pfDICTIONARY_InitDispatchVector () {
    VPrimitiveTask::InstallPrimitives (PrimitiveDescriptions, PrimitiveDescriptionCount);
}

/*********************************
 *****  Facility Definition  *****
 *********************************/

FAC_DefineFacility
{
    switch (FAC_RequestTypeField)
    {
    FAC_FDFCase_FacilityIdAsString (pfDICTIONARY);
    FAC_FDFCase_FacilityDescription ("Dictionary Primitives Implementation");
    default:
        break;
    }
}

redpajama_set_name: RedPajamaGithub


text: A package for writing micro-services in Go


text:
package org.whispercomm.c2dm4j.impl;

import org.junit.Before;
import org.junit.Test;
import org.whispercomm.c2dm4j.Message;
import org.whispercomm.c2dm4j.MessageBuilder;
import org.whispercomm.c2dm4j.ResponseType;
import org.whispercomm.c2dm4j.auth.AuthToken;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

/**
 * Unit tests for {@link SuccessResponseImpl}.
 *
 * @author David R. Bild
 *
 */
public class SuccessResponseImplTest {
	private static final String REGISTRATION_ID = "My Registration Id";
	private static final String COLLAPSE_KEY = "My Collapse Key";
	private static final String AUTH_TOKEN = "My Auth Token";
	private static final String SENT_MESSAGE_ID = "My Sent Message Id";

	private Message message;

	private AuthToken token;

	@Before
	public void setup() {
		message = new MessageBuilder().registrationId(REGISTRATION_ID)
				.collapseKey(COLLAPSE_KEY).build();
		token = new AuthToken(AUTH_TOKEN);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructorRejectsNullMessage() {
		new SuccessResponseImpl(SENT_MESSAGE_ID, null);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructorRejectsNullSentMessageId() {
		new SuccessResponseImpl(null, message);
	}

	@Test
	public void getResponseTypeReturnsSuccessType() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message)
						.getResponseType(),
				is(ResponseType.Success));
	}

	@Test
	public void getSentMessageIdReturnsConstructorSuppliedId() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message)
						.getSentMessageId(),
				is(SENT_MESSAGE_ID));
	}

	@Test
	public void getMessageReturnsConstructorSuppliedMessage() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message).getMessage(),
				is(message));
	}

	@Test
	public void hasUpdatedAuthTokenIsFalseWhenNotSuppliedOrNull() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message)
						.hasUpdatedAuthToken(),
				is(false));
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message, null)
						.hasUpdatedAuthToken(),
				is(false));
	}

	@Test
	public void hasUpdatedAuthTokenIsTrueWhenSupplied() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message, token)
						.hasUpdatedAuthToken(),
				is(true));
	}

	@Test
	public void getUpdatedAuthTokenReturnsSuppliedToken() {
		assertThat(
				new SuccessResponseImpl(SENT_MESSAGE_ID, message, token)
						.getUpdatedAuthToken(),
				is(token));
	}

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.networkservices.v1beta1.model;

/**
 * Describe the destination for traffic to be routed to.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Network Services API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class TcpRouteRouteDestination extends com.google.api.client.json.GenericJson {

  /**
   * Required. The URL of a BackendService to route traffic to.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String serviceName;

  /**
   * Optional. Specifies the proportion of requests forwarded to the backend referenced by the
   * serviceName field. This is computed as: weight/Sum(weights in this destination list). For non-
   * zero values, there may be some epsilon from the exact proportion defined here depending on the
   * precision an implementation supports. If only one serviceName is specified and it has a weight
   * greater than 0, 100% of the traffic is forwarded to that backend. If weights are specified for
   * any one service name, they need to be specified for all of them. If weights are unspecified for
   * all services, then, traffic is distributed in equal proportions to all of them.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer weight;

  /**
   * Required. The URL of a BackendService to route traffic to.
   * @return value or {@code null} for none
   */
  public java.lang.String getServiceName() {
    return serviceName;
  }

  /**
   * Required. The URL of a BackendService to route traffic to.
   * @param serviceName serviceName or {@code null} for none
   */
  public TcpRouteRouteDestination setServiceName(java.lang.String serviceName) {
    this.serviceName = serviceName;
    return this;
  }

  /**
   * Optional. Specifies the proportion of requests forwarded to the backend referenced by the
   * serviceName field. This is computed as: weight/Sum(weights in this destination list). For non-
   * zero values, there may be some epsilon from the exact proportion defined here depending on the
   * precision an implementation supports. If only one serviceName is specified and it has a weight
   * greater than 0, 100% of the traffic is forwarded to that backend. If weights are specified for
   * any one service name, they need to be specified for all of them. If weights are unspecified for
   * all services, then, traffic is distributed in equal proportions to all of them.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getWeight() {
    return weight;
  }

  /**
   * Optional. Specifies the proportion of requests forwarded to the backend referenced by the
   * serviceName field. This is computed as: weight/Sum(weights in this destination list). For non-
   * zero values, there may be some epsilon from the exact proportion defined here depending on the
   * precision an implementation supports. If only one serviceName is specified and it has a weight
   * greater than 0, 100% of the traffic is forwarded to that backend. If weights are specified for
   * any one service name, they need to be specified for all of them. If weights are unspecified for
   * all services, then, traffic is distributed in equal proportions to all of them.
   * @param weight weight or {@code null} for none
   */
  public TcpRouteRouteDestination setWeight(java.lang.Integer weight) {
    this.weight = weight;
    return this;
  }

  @Override
  public TcpRouteRouteDestination set(String fieldName, Object value) {
    return (TcpRouteRouteDestination) super.set(fieldName, value);
  }

  @Override
  public TcpRouteRouteDestination clone() {
    return (TcpRouteRouteDestination) super.clone();
  }

}


text:
<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

/**
 * @Annotation
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class Traverse extends Constraint
{
    public $traverse = true;

    public function __construct($options = null)
    {
        if (\is_array($options) && \array_key_exists('groups', $options)) {
            throw new ConstraintDefinitionException(sprintf('The option "groups" is not supported by the constraint %s', __CLASS__));
        }

        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultOption()
    {
        return 'traverse';
    }

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}


text:
<?php

use Tres\package_manager\Autoload;

define('ROOT', dirname(__DIR__));

require_once(ROOT.'/Tres/package_manager/Autoload.php');

$manifest = require('manifest.php');
$autoload = new Autoload(ROOT.'/examples', $manifest);

echo John_Doe\examples\ExampleClassOne::sayHello();
echo alias\Name::sayHello();
(new app\controllers\ExampleController);
echo Tres\more_examples\ExampleClass3::showMsg();
echo password_hash('secure hash', PASSWORD_BCRYPT).'<br />';
echo Tres\examples\ExampleClassTwo::sayBye();


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/ship/components/armor/shared_arm_kessel_rebel_sorosuub_spidershell_plating.iff"
	result.attribute_template_id = 8
	result.stfName("space/space_item","arm_kessel_rebel_sorosuub_spidershell_plating_n")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package com.syang7081.actfrademo.activityfragmentdatademo;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by syang7081 on 2/11/2017.
 */

public class FragmentLevelThree extends BaseFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) {
        View view = inflater.inflate(R.layout.fragment_level_three, container, false);
        return view;
    }

    @Override
    public void onReceiveData(List<Bundle> bundles) {
        super.onReceiveData(bundles);
        Log.d("FragmentLevelThree", "received data: " + bundles.toString());
        /* send data to root activity
        Bundle b = new Bundle();
        b.putString("Greeting", "Hello Activity, this is from " + this);
        List<Bundle> list = new ArrayList<>();
        list.add(b);
        ((BaseActivity) getActivity()).onReceiveData(list);
        */
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Hatfield.EnviroData.DataAcquisition.XML;
using Hatfield.EnviroData.DataAcquisition.CSV;
using Hatfield.EnviroData.WQDataProfile;

namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Importer
{
    public class ESDATDataImporter : DataImporterBase
    {
        private IWQDefaultValueProvider _wqDefaultValueProvider;

        public ESDATDataImporter(ResultLevel thresholdLevel, IWQDefaultValueProvider wqDefaultValueProvider)
            : base(thresholdLevel)
        {
            _wqDefaultValueProvider = wqDefaultValueProvider;
        }

        public override bool IsDataSupported(IDataToImport dataToImport)
        {
            return dataToImport is ESDATDataToImport;
        }

        public override IExtractedDataset<T> Extract<T>(IDataToImport dataToImport)
        {
            var extractedDataset = new ExtractedDataset<T>(_thresholdLevel);

            ChemistryFileChildObjectExtractConfiguration chemistryDataExtractConfiguration = null;
            SampleFileChildObjectExtractConfiguration sampleDataExtractConfiguration = null;

            var castedDataToImport = dataToImport as ESDATDataToImport;

            if (castedDataToImport == null)
            {
                extractedDataset.AddParsingResult(new BaseResult(ResultLevel.FATAL, "Data to Import needs to be ESDATDataToImport"));
            }

            try
            {
                chemistryDataExtractConfiguration = _extractConfigurations.Where(x => x is ChemistryFileChildObjectExtractConfiguration)
                                                                            .Cast<ChemistryFileChildObjectExtractConfiguration>()
                                                                            .SingleOrDefault();
            }
            catch (Exception ex)
            {
                chemistryDataExtractConfiguration = null;
                extractedDataset.AddParsingResult(new BaseResult(ResultLevel.FATAL, "ESDAT data importer needs to have one and only one Chemistry file extract configuration"));

            }

            try
            {
                sampleDataExtractConfiguration = _extractConfigurations.Where(x => x is SampleFileChildObjectExtractConfiguration)
                                                                            .Cast<SampleFileChildObjectExtractConfiguration>()
                                                                            .SingleOrDefault();
            }
            catch (Exception ex)
            {
                sampleDataExtractConfiguration = null;
                extractedDataset.AddParsingResult(new BaseResult(ResultLevel.FATAL, "ESDAT data importer needs to have one and only one Sample file extract configuration"));
            }

            var model = new T();

            if (castedDataToImport.HeaderFileToImport == null)
            {
                var castedModel = model as ESDATModel;
                castedModel.LabName = _wqDefaultValueProvider.DefaultOrganizationName;
                extractedDataset.AddParsingResults(new List<IResult> {
                    new BaseResult(ResultLevel.WARN, "Header file is null, use the default organization name in the default value provider")
                });
            }
            else
            {
                var headerFileExtractResults = ExtractHeaderFile(model, _extractConfigurations, castedDataToImport.HeaderFileToImport);
                extractedDataset.AddParsingResults(headerFileExtractResults);
            }

            if (chemistryDataExtractConfiguration != null && sampleDataExtractConfiguration != null)
            {

                var chemistryFileExtractResults = ExtractChemistryFileData(model, chemistryDataExtractConfiguration, castedDataToImport.ChemistryFileToImport);
                extractedDataset.AddParsingResults(chemistryFileExtractResults);

                var sampleFileExtractResults = ExtractSampleFileData(model, sampleDataExtractConfiguration, castedDataToImport.SampleFileToImport);
                extractedDataset.AddParsingResults(sampleFileExtractResults);

            }

            extractedDataset.AddParsingResults(new List<IResult> { new ParsingResult(ResultLevel.DEBUG, "Extract data into ESDAT model", model, null) });

            return extractedDataset;
        }

        private IEnumerable<IResult> ExtractHeaderFile(object model, IList<IExtractConfiguration> extractConfiguration, IDataToImport xmlDataToImport)
        {
            var results = new List<IResult>();
            IDataSourceLocation currentLocation = null;
            foreach (var configuration in extractConfiguration.Where(x => x is ISimpleExtractConfiguration))
            {
                if (configuration is SimpleXMLExtractConfiguration)
                {
                    currentLocation = new XMLDataSourceLocation(((SimpleXMLExtractConfiguration)configuration).ElementName, ((SimpleXMLExtractConfiguration)configuration).AttributeName);
                }

                results.AddRange(((SimpleXMLExtractConfiguration)configuration).ExtractData(model, xmlDataToImport, currentLocation));

            }

            return results;
        }

        private IEnumerable<IResult> ExtractChemistryFileData(object model, ChemistryFileChildObjectExtractConfiguration configuration, IDataToImport dataToImport)
        {
            var extractResults = configuration.ExtractData(model, dataToImport);

            return extractResults;
        }

        private IEnumerable<IResult> ExtractSampleFileData(object model, SampleFileChildObjectExtractConfiguration configuration, IDataToImport dataToImport)
        {
            var extractResults = configuration.ExtractData(model, dataToImport);

            return extractResults;
        }

    }
}


text:
<?php

/**
 * 模块服务提供者
 */

namespace Y80x86ol\LaravelModules;

use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Request;
use Y80x86ol\LaravelModules\FileSystem;

class LaravelModulesServiceProvider extends ServiceProvider
{

    private $moduleName = '';
    private $modulesPath = '';
    private $currentModulePath = '';
    private $allModulesNameList = [];

    public function __construct($app)
    {
        parent::__construct($app);
    }

    /**
     * 启动服务提供者.
     *
     * @return void
     */
    public function boot(Request $request)
    {
        //获取所有模块名字
        $this->getAllModulesNameList();

        //获取模块数据
        $this->getModulePath($request);

        //注册主路由
        $this->registerMainRoute();

        //注册所有模块静态资源
        $this->registerPublic();

        //注册所有模块数据库
        $this->registerMigrations();

        //注册所有模块配置文件
        $this->registerConfig();

        //注册所有模块语言包
        $this->registerTranslations();

        if ($this->moduleName) {
            //注册路由
            $this->registerRoute();

            //注册视图
            $this->registerView();
        }
    }

    /**
     * 在容器中注册服务提供者.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Modules', function ($app) {
            return new Module(config('modules'));
        });
    }

    /**
     * 获取所有模块名字
     */
    private function getAllModulesNameList()
    {
        $allmodulesNameList = FileSystem::getAllModules();
        $this->allModulesNameList = $allmodulesNameList;
    }

    /**
     * 获取模块信息
     * @param Request $request 请求类
     */
    private function getModulePath($request)
    {
        //先判断是否是二级域名
        $modulesConfig = config("modules");
        if (isset($modulesConfig['sub_domain']) && array_key_exists($request->getHost(), $modulesConfig['sub_domain'])) {
            $moduleName = $modulesConfig['sub_domain'][$request->getHost()];
        } else {
            //通过URI地址获取当前路由指定模块
            $uri = trim($request->path(), '/');
            $uriArray = explode('/', $uri);
            $moduleName = current($uriArray);
        }

        $this->moduleName = strtolower($moduleName);
        $this->modulesPath = base_path() . '/app/Modules/';
        $this->currentModulePath = $this->modulesPath . $moduleName . '/';
    }

    /**
     * 注册主路由
     */
    private function registerMainRoute()
    {
        $moduleRoutePath = $this->modulesPath . 'routes.php';
        if (file_exists($moduleRoutePath)) {
            if (!$this->app->routesAreCached()) {
                require $moduleRoutePath;
            }
        }
    }

    /**
     * 注册独立模块路由
     */
    private function registerRoute()
    {
        $currentModuleRoutePath = $this->currentModulePath . 'routes.php';
        if (file_exists($currentModuleRoutePath)) {
            if (!$this->app->routesAreCached()) {
                require $currentModuleRoutePath;
            }
        }
    }

    /**
     * 注册视图
     *
     * 使用:return view('currentModuleName::car.view');
     */
    private function registerView()
    {
        $viewPath = $this->currentModulePath . 'Http/Views/';
        $this->loadViewsFrom($viewPath, $this->moduleName);

        //发布扩展包视图
        $this->publishes([
            $viewPath => base_path('resources/views/vendor/courier'),
        ]);
    }

    /**
     * 注册所有模块语言包
     *
     * 使用:echo trans('currentModuleName::messages.welcome');
     */
    private function registerTranslations()
    {
        foreach ($this->allModulesNameList as $moduleName) {
            $translationsPath = $this->modulesPath . $moduleName . '/Translations';

            $moduleName = strtolower($moduleName);
            if (file_exists($translationsPath)) {
                $this->loadTranslationsFrom($translationsPath, $moduleName);

                //发布语言包
                $this->publishes([
                    $translationsPath => base_path('resources/lang/vendor/courier'),
                ]);
            }
        }
    }

    /**
     * 注册所有模块配置文件
     *
     * 使用:$value = config('courier.option');
     */
    private function registerConfig()
    {
        foreach ($this->allModulesNameList as $moduleName) {
            $configPath = $this->modulesPath . $moduleName . '/' . strtolower($moduleName) . '.php';

            $moduleName = strtolower($moduleName);
            if (file_exists($configPath)) {
                $this->publishes([
                    $configPath => config_path($moduleName . '.php'),
                ]);
            }
        }
    }

    /**
     * 注册所有模块静态资源
     *
     * 模块下的静态资源均发布到对应的模块名字下,且名字均为小写
     */
    private function registerPublic()
    {
        foreach ($this->allModulesNameList as $moduleName) {
            $publicPath = $this->modulesPath . $moduleName . '/Public';

            $moduleName = strtolower($moduleName);
            if (file_exists($publicPath)) {
                $this->publishes([$publicPath => public_path('modules/' . $moduleName),], $moduleName);
            }
        }
    }

    /**
     * 注册所有模块数据库迁移
     *
     */
    private function registerMigrations()
    {
        foreach ($this->allModulesNameList as $moduleName) {
            $migrationsPath = $this->modulesPath . $moduleName . '/Migrations';
            if (file_exists($migrationsPath)) {
                $this->loadMigrationsFrom($migrationsPath);
            }
        }
    }

}


text:
    Question text
    <textarea id="txtText" ng-model="$ctrl.question.text" class="form-control input-large" rows="10"></textarea>

        <input id="multiselect" type="checkbox" ng-model="$ctrl.question.multiSelect"/>
        Multiselect question

<fieldset class="answers">
    <legend>
        Answers
        <button class="btn btn-success btn-xs" ng-click="$ctrl.addNewAnswer()" type="button">Add new</button>
    </legend>

            Answer text
            <textarea id="answer-text-{{$index}}" ng-model="answer.text" class="form-control input-large" rows="2"></textarea>

                <input type="checkbox" ng-model="answer.right"/>
                Correct answer

        <button class="btn btn-danger answers-delete" ng-click="$ctrl.deleteAnswer($index)" type="button">Remove</button>

</fieldset>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="refresh" content="0; URL=doc/html/index.html">

    Automatic redirection failed, click this
    link

© Copyright Joel de Guzman, 2003-2006

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


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Linq;
using System.Web.Hosting;
using Alienlab.Web.Security.Resources;
using Alienlab.Web.Security.Store;

namespace Alienlab.Web.Security {

    /// <summary>
    /// Custom XML implementation of <c>System.Web.Security.RoleProvider</c>
    /// </summary>
    public class XmlRoleProvider : RoleProviderBase, IDisposable {

        #region Fields  ///////////////////////////////////////////////////////////////////////////

        string _file;
        private XmlRoleStore _store;

        #endregion

        #region Properties  ///////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets the roles.
        /// </summary>
        /// <value>The roles.</value>
        protected List<XmlRole> Roles { get { return this.Store.Roles; } }

        /// <summary>
        /// Gets the role store.
        /// </summary>
        /// <value>The role store.</value>
        protected XmlRoleStore Store {
            get {
                return _store ?? (_store = new XmlRoleStore(_file));
            }
        }

        #endregion

        #region Construct / Destruct //////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlRoleProvider"/> class.
        /// </summary>
        public XmlRoleProvider() {
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose() {
            Store.Dispose();
        }

        #endregion

        #region Methods ///////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Adds the specified user names to the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="usernames">A string array of user names to be added to the specified roles.</param>
        /// <param name="roleNames">A string array of the role names to add the specified user names to.</param>
        public override void AddUsersToRoles(string[] usernames, string[] roleNames) {

            if (usernames == null)
                throw new ArgumentNullException("usernames");
            if (roleNames == null)
                throw new ArgumentNullException("roleNames");

            var comparer = this.Comparer;
            lock (SyncRoot) {
                foreach (string rolename in roleNames) {
                    XmlRole role = this.GetRole(rolename);
                    if (role != null) {
                        foreach (string username in usernames) {
                            if (!role.Users.Contains(username, comparer))
                                role.Users.Add(username);
                        }
                    }
                }
                this.Store.Save();
            }
        }

        /// <summary>
        /// Adds a new role to the data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to create.</param>
        public override void CreateRole(string roleName) {

            if (roleName == null)
                throw new ArgumentNullException("roleName");
            if (roleName.IndexOf(',') > 0)
                throw new ArgumentException(Messages.RoleCannotContainCommas);

            XmlRole role = this.GetRole(roleName);
            if (role == null) {
                role = new XmlRole {
                    Name = roleName,
                    Users = new List<string>()
                };
                lock (SyncRoot) {
                    this.Store.Roles.Add(role);
                    this.Store.Save();
                }
            }
            else
                throw new ProviderException(Messages.RoleExists.F(roleName));
        }

        /// <summary>
        /// Removes a role from the data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to delete.</param>
        /// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param>
        /// <returns>
        /// true if the role was successfully deleted; otherwise, false.
        /// </returns>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) {

            if (roleName == null)
                throw new ArgumentNullException("roleName");

            lock (SyncRoot) {
                XmlRole role = this.GetRole(roleName);
                if (role != null) {
                    if (throwOnPopulatedRole && (role.Users.Count > 0))
                        throw new ProviderException(Messages.CannotDeletePopulatedRole);
                    this.Store.Roles.Remove(role);
                    this.Store.Save();

                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// Gets an array of user names in a role where the user name contains the specified user name to match.
        /// </summary>
        /// <param name="roleName">The role to search in.</param>
        /// <param name="usernameToMatch">The user name to search for.</param>
        /// <returns>
        /// A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role.
        /// </returns>
        public override string[] FindUsersInRole(string roleName, string usernameToMatch) {

            if (roleName == null)
                throw new ArgumentNullException("roleName");
            if (usernameToMatch == null)
                throw new ArgumentNullException("usernameToMatch");

            var comparison = this.Comparison;
            var query = from role in this.Roles.AsQueryable()
                        from user in role.Users
                        where (user.IndexOf(usernameToMatch, comparison) >= 0)
                                && role.Name.Equals(roleName, comparison)
                        select user;
            lock (SyncRoot) {
                return query.ToArray();
            }
        }

        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the roles stored in the data source for the configured applicationName.
        /// </returns>
        public override string[] GetAllRoles() {
            var query = from r in this.Roles
                        select r.Name;
            lock (SyncRoot) {
                return query.ToArray();
            }
        }

        /// <summary>
        /// Gets the role.
        /// </summary>
        /// <param name="roleName">The name.</param>
        /// <returns></returns>
        public XmlRole GetRole(string roleName) {

            if (roleName == null)
                throw new ArgumentNullException("roleName");

            var query = from r in this.Roles
                        where r.Name.Equals(roleName, this.Comparison)
                        select r;
            lock (SyncRoot) {
                return query.FirstOrDefault();
            }
        }

        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <param name="username">The user to return a list of roles for.</param>
        /// <returns>
        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        /// </returns>
        public override string[] GetRolesForUser(string username) {

            if (username == null)
                throw new ArgumentNullException("username");
            var query = from r in this.Roles
                        where r.Users.Contains(username, this.Comparer)
                        select r.Name;
            lock (SyncRoot) {
                return query.ToArray();
            }
        }

        /// <summary>
        /// Gets a list of users in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to get the list of users for.</param>
        /// <returns>
        /// A string array containing the names of all the users who are members of the specified role for the configured applicationName.
        /// </returns>
        public override string[] GetUsersInRole(string roleName) {

            XmlRole role = this.GetRole(roleName);
            if (role != null) {
                lock (SyncRoot) {
                    return role.Users.ToArray();
                }
            }
            throw new ProviderException(Messages.RoleNotExists.F(roleName));
        }

        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="username">The user name to search for.</param>
        /// <param name="roleName">The role to search in.</param>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        public override bool IsUserInRole(string username, string roleName) {

            if (username == null)
                throw new ArgumentNullException("username");

            XmlRole role = this.GetRole(roleName);
            if (role != null) {
                lock (SyncRoot) {
                    return role.Users.Contains(username, this.Comparer);
                }
            }
            else
                throw new ProviderException(Messages.RoleNotExists.F(roleName));
        }

        /// <summary>
        /// Removes the specified user names from the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="usernames">A string array of user names to be removed from the specified roles.</param>
        /// <param name="roleNames">A string array of role names to remove the specified user names from.</param>
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) {

            if (usernames == null)
                throw new ArgumentNullException("usernames");
            if (roleNames == null)
                throw new ArgumentNullException("roleNames");

            var comparer = this.Comparer;
            var query = from r in this.Roles
                        where roleNames.Contains(r.Name, comparer)
                        select r;
            lock (SyncRoot) {
                foreach (XmlRole role in query) {
                    foreach (string username in usernames) {
                        role.Users.Remove(username);
                    }
                }
                this.Store.Save();
            }
        }

        /// <summary>
        /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to search for in the data source.</param>
        /// <returns>
        /// true if the role name already exists in the data source for the configured applicationName; otherwise, false.
        /// </returns>
        public override bool RoleExists(string roleName) {
            return this.GetRole(roleName) != null;
        }

        #region - Initialize -

        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        public override void Initialize(string name, NameValueCollection config) {

            if (config == null)
                throw new ArgumentNullException("config");

            // prerequisite
            if (string.IsNullOrWhiteSpace(name)) {
                name = "XmlRoleProvider";
            }
            if (string.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config.Add("description", "XML Role Provider");
            }

            // initialize the base class
            base.Initialize(name, config);

            // initialize provider fields
            string fileName = config.GetString("fileName", "Roles.xml");
            string folder = config.GetString("folder", "~/App_Data/");

            if (!folder.EndsWith("/")) folder += "/";
            _file = HostingEnvironment.MapPath(string.Format("{0}{1}", folder, fileName));
        }
        #endregion
        #endregion
    }
}


text:
package com.github.dockerjava.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.async.ResultCallback;

/**
 * Handler that decodes an incoming byte stream into objects of T and calls {@link ResultCallback#onNext(Object)}
 *
 * @author Marcus Linke
 */
public class JsonResponseCallbackHandler<T> extends SimpleChannelInboundHandler<ByteBuf> {

    private static ObjectMapper objectMapper = new ObjectMapper();

    private TypeReference<T> typeReference;

    private ResultCallback<T> callback;

    public JsonResponseCallbackHandler(TypeReference<T> typeReference, ResultCallback<T> callback) {
        this.typeReference = typeReference;
        this.callback = callback;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        msg.discardReadBytes();

        T object = null;

        try {
            object = objectMapper.readValue(buffer, typeReference);
        } catch (Exception e) {
            callback.onError(e);
            throw new RuntimeException(e);
        }

        callback.onNext(object);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        callback.onError(cause);
        ctx.close();
    }
}


text:
package bitcoind

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/OpenBazaar/spvwallet"
	"github.com/btcsuite/btcd/blockchain"
	"github.com/btcsuite/btcd/btcec"
	"github.com/btcsuite/btcd/chaincfg"
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcd/wire"
	"github.com/btcsuite/btcrpcclient"
	btc "github.com/btcsuite/btcutil"
	hd "github.com/btcsuite/btcutil/hdkeychain"
	"github.com/btcsuite/btcutil/txsort"
	"github.com/btcsuite/btcwallet/wallet/txrules"
	"github.com/op/go-logging"
	b39 "github.com/tyler-smith/go-bip39"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

var log = logging.MustGetLogger("bitcoind")

const (
	Account = "OpenBazaar"
)

type BitcoindWallet struct {
	params           *chaincfg.Params
	repoPath         string
	trustedPeer      string
	masterPrivateKey *hd.ExtendedKey
	masterPublicKey  *hd.ExtendedKey
	listeners        []func(spvwallet.TransactionCallback)
	rpcClient        *btcrpcclient.Client
	binary           string
	controlPort      int
	useTor           bool
	started          bool
	scriptsToAdd     [][]byte
}

var connCfg *btcrpcclient.ConnConfig = &btcrpcclient.ConnConfig{
	Host:                 "localhost:8332",
	HTTPPostMode:         true, // Bitcoin core only supports HTTP POST mode
	DisableTLS:           true, // Bitcoin core does not provide TLS by default
	DisableAutoReconnect: false,
	DisableConnectOnNew:  false,
}

func NewBitcoindWallet(mnemonic string, params *chaincfg.Params, repoPath string, trustedPeer string, binary string, username string, password string, useTor bool, torControlPort int) *BitcoindWallet {
	seed := b39.NewSeed(mnemonic, "")
	mPrivKey, _ := hd.NewMaster(seed, params)
	mPubKey, _ := mPrivKey.Neuter()

	if params.Name == chaincfg.TestNet3Params.Name || params.Name == chaincfg.RegressionNetParams.Name {
		connCfg.Host = "localhost:18332"
	}

	connCfg.User = username
	connCfg.Pass = password

	if trustedPeer != "" {
		trustedPeer = strings.Split(trustedPeer, ":")[0]
	}

	w := BitcoindWallet{
		params:           params,
		repoPath:         repoPath,
		trustedPeer:      trustedPeer,
		masterPrivateKey: mPrivKey,
		masterPublicKey:  mPubKey,
		binary:           binary,
		controlPort:      torControlPort,
		useTor:           useTor,
	}
	return &w
}

func (w *BitcoindWallet) BuildArguments(rescan bool) []string {
	notify := `curl -d %s http://localhost:8330/`
	args := []string{"-walletnotify=" + notify, "-server"}
	if rescan {
		args = append(args, "-rescan")
	}
	args = append(args, "-torcontrol=127.0.0.1:"+strconv.Itoa(w.controlPort))

	if w.params.Name == chaincfg.TestNet3Params.Name {
		args = append(args, "-testnet")
	} else if w.params.Name == chaincfg.RegressionNetParams.Name {
		args = append(args, "-regtest")
	}
	if w.trustedPeer != "" {
		args = append(args, "-connect="+w.trustedPeer)
	}
	if w.useTor {
		socksPort := defaultSocksPort(w.controlPort)
		args = append(args, "-listen", "-proxy:127.0.0.1:"+strconv.Itoa(socksPort), "-onlynet=onion")
	}
	return args
}

func (w *BitcoindWallet) Start() {
	w.shutdownIfActive()
	args := w.BuildArguments(false)
	client, _ := btcrpcclient.New(connCfg, nil)
	w.rpcClient = client
	go startNotificationListener(client, w.listeners)

	cmd := exec.Command(w.binary, args...)
	go cmd.Start()
	ticker := time.NewTicker(time.Second * 30)
	go func() {
		for range ticker.C {
			log.Fatal("Failed to connect to bitcoind")
		}
	}()
	for {
		_, err := client.GetBlockCount()
		if err == nil {
			break
		}
		time.Sleep(time.Second)
	}
	ticker.Stop()
	log.Info("Connected to bitcoind")
	w.started = true
	go w.addScripts()
}

func (w *BitcoindWallet) addScripts() {
	for _, script := range w.scriptsToAdd {
		w.AddWatchedScript(script)
	}
}

// If bitcoind is already running let's shut it down so we restart it with our options
func (w *BitcoindWallet) shutdownIfActive() {
	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		return
	}
	client.RawRequest("stop", []json.RawMessage{})
	client.Shutdown()
	time.Sleep(5 * time.Second)
}

func (w *BitcoindWallet) CurrencyCode() string {
	if w.params.Name == chaincfg.MainNetParams.Name {
		return "btc"
	} else {
		return "tbtc"
	}
}

func (w *BitcoindWallet) IsDust(amount int64) bool {
	return txrules.IsDustAmount(btc.Amount(amount), 25, txrules.DefaultRelayFeePerKb)
}

func (w *BitcoindWallet) MasterPrivateKey() *hd.ExtendedKey {
	return w.masterPrivateKey
}

func (w *BitcoindWallet) MasterPublicKey() *hd.ExtendedKey {
	return w.masterPublicKey
}

func (w *BitcoindWallet) CurrentAddress(purpose spvwallet.KeyPurpose) btc.Address {
	addr, _ := w.rpcClient.GetAccountAddress(Account)
	return addr
}

func (w *BitcoindWallet) NewAddress(purpose spvwallet.KeyPurpose) btc.Address {
	addr, _ := w.rpcClient.GetNewAddress(Account)
	return addr
}

func (w *BitcoindWallet) DecodeAddress(addr string) (btc.Address, error) {
	return btc.DecodeAddress(addr, w.params)
}

func (w *BitcoindWallet) ScriptToAddress(script []byte) (btc.Address, error) {
	_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, w.params)
	if err != nil {
		return nil, err
	}
	if len(addrs) == 0 {
		return nil, errors.New("unknown script")
	}
	return addrs[0], nil
}

func (w *BitcoindWallet) AddressToScript(addr btc.Address) ([]byte, error) {
	return txscript.PayToAddrScript(addr)
}

func (w *BitcoindWallet) HasKey(addr btc.Address) bool {
	_, err := w.rpcClient.DumpPrivKey(addr)
	if err != nil {
		return false
	}
	return true
}

func (w *BitcoindWallet) Balance() (confirmed, unconfirmed int64) {
	resp, _ := w.rpcClient.RawRequest("getwalletinfo", []json.RawMessage{})
	type walletInfo struct {
		Balance     float64 `json:"balance"`
		Unconfirmed float64 `json:"unconfirmed_balance"`
	}
	respBytes, _ := resp.MarshalJSON()
	i := new(walletInfo)
	json.Unmarshal(respBytes, i)
	c, _ := btc.NewAmount(i.Balance)
	u, _ := btc.NewAmount(i.Unconfirmed)
	return int64(c.ToUnit(btc.AmountSatoshi)), int64(u.ToUnit(btc.AmountSatoshi))
}

func (w *BitcoindWallet) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
	blockinfo, err := w.rpcClient.GetBlockHeaderVerbose(hash)
	if err != nil {
		return 0, err
	}
	return blockinfo.Height, nil
}

func (w *BitcoindWallet) Transactions() ([]spvwallet.Txn, error) {
	var ret []spvwallet.Txn
	resp, err := w.rpcClient.ListTransactions(Account)
	if err != nil {
		return ret, err
	}
	for _, r := range resp {
		amt, err := btc.NewAmount(r.Amount)
		if err != nil {
			return ret, err
		}
		ts := time.Unix(r.TimeReceived, 0)
		height := int32(0)
		if r.Confirmations > 0 {
			h, err := chainhash.NewHashFromStr(r.BlockHash)
			if err != nil {
				return ret, err
			}
			height, err = w.GetBlockHeight(h)
			if err != nil {
				return ret, err
			}
		}
		t := spvwallet.Txn{
			Txid:      r.TxID,
			Value:     int64(amt.ToUnit(btc.AmountSatoshi)),
			Height:    height,
			Timestamp: ts,
		}
		ret = append(ret, t)
	}
	return ret, nil
}

func (w *BitcoindWallet) GetTransaction(txid chainhash.Hash) (spvwallet.Txn, error) {
	includeWatchOnly := false
	t := spvwallet.Txn{}
	resp, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
	if err != nil {
		return t, err
	}
	t.Txid = resp.TxID
	t.Value = int64(resp.Amount * 100000000)
	t.Height = int32(resp.BlockIndex)
	t.Timestamp = time.Unix(resp.TimeReceived, 0)
	t.WatchOnly = false
	return t, nil
}

func (w *BitcoindWallet) GetConfirmations(txid chainhash.Hash) (uint32, uint32, error) {
	includeWatchOnly := true
	resp, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
	if err != nil {
		return 0, 0, err
	}
	return uint32(resp.Confirmations), uint32(resp.BlockIndex), nil
}

func (w *BitcoindWallet) ChainTip() (uint32, chainhash.Hash) {
	var ch chainhash.Hash
	info, err := w.rpcClient.GetInfo()
	if err != nil {
		return uint32(0), ch
	}
	h, err := w.rpcClient.GetBestBlockHash()
	if err != nil {
		return uint32(0), ch
	}
	return uint32(info.Blocks), *h
}

func (w *BitcoindWallet) Spend(amount int64, addr btc.Address, feeLevel spvwallet.FeeLevel) (*chainhash.Hash, error) {
	amt, err := btc.NewAmount(float64(amount) / 100000000)
	if err != nil {
		return nil, err
	}
	return w.rpcClient.SendFrom(Account, addr, amt)
}

func (w *BitcoindWallet) BumpFee(txid chainhash.Hash) (*chainhash.Hash, error) {
	includeWatchOnly := false
	tx, err := w.rpcClient.GetTransaction(&txid, &includeWatchOnly)
	if err != nil {
		return nil, err
	}
	if tx.Confirmations > 0 {
		return nil, spvwallet.BumpFeeAlreadyConfirmedError
	}
	unspent, err := w.rpcClient.ListUnspent()
	if err != nil {
		return nil, err
	}
	for _, u := range unspent {
		if u.TxID == txid.String() {
			if u.Confirmations > 0 {
				return nil, spvwallet.BumpFeeAlreadyConfirmedError
			}
			h, err := chainhash.NewHashFromStr(u.TxID)
			if err != nil {
				continue
			}
			op := wire.NewOutPoint(h, u.Vout)
			script, err := hex.DecodeString(u.ScriptPubKey)
			if err != nil {
				continue
			}
			utxo := spvwallet.Utxo{
				Op:           *op,
				Value:        int64(u.Amount / 100000000),
				ScriptPubkey: script,
			}
			addr, err := btc.DecodeAddress(u.Address, w.params)
			if err != nil {
				continue
			}
			key, err := w.rpcClient.DumpPrivKey(addr)
			if err != nil {
				continue
			}
			hdKey := hd.NewExtendedKey(w.Params().HDPrivateKeyID[:], key.PrivKey.Serialize(), make([]byte, 32), make([]byte, 4), 0, 0, true)
			transactionID, err := w.SweepAddress([]spvwallet.Utxo{utxo}, nil, hdKey, nil, spvwallet.FEE_BUMP)
			if err != nil {
				return nil, err
			}
			return transactionID, nil

		}
	}
	return nil, spvwallet.BumpFeeNotFoundError
}

func (w *BitcoindWallet) GetFeePerByte(feeLevel spvwallet.FeeLevel) uint64 {
	defautlFee := uint64(50)
	var nBlocks json.RawMessage
	switch feeLevel {
	case spvwallet.PRIOIRTY:
		nBlocks = json.RawMessage([]byte(`1`))
	case spvwallet.NORMAL:
		nBlocks = json.RawMessage([]byte(`3`))
	case spvwallet.ECONOMIC:
		nBlocks = json.RawMessage([]byte(`6`))
	default:
		return defautlFee
	}
	resp, err := w.rpcClient.RawRequest("estimatefee", []json.RawMessage{nBlocks})
	if err != nil {
		return defautlFee
	}
	feePerKb, err := strconv.Atoi(string(resp))
	if err != nil {
		return defautlFee
	}
	if feePerKb <= 0 {
		return defautlFee
	}
	fee := feePerKb / 1000
	return uint64(fee)
}

func (w *BitcoindWallet) EstimateFee(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, feePerByte uint64) uint64 {
	tx := wire.NewMsgTx(wire.TxVersion)
	for _, out := range outs {
		output := wire.NewTxOut(out.Value, out.ScriptPubKey)
		tx.TxOut = append(tx.TxOut, output)
	}
	estimatedSize := spvwallet.EstimateSerializeSize(len(ins), tx.TxOut, false, spvwallet.P2PKH)
	fee := estimatedSize * int(feePerByte)
	return uint64(fee)
}

func (w *BitcoindWallet) CreateMultisigSignature(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]spvwallet.Signature, error) {
	var sigs []spvwallet.Signature
	tx := wire.NewMsgTx(1)
	for _, in := range ins {
		ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash))
		if err != nil {
			return sigs, err
		}
		outpoint := wire.NewOutPoint(ch, in.OutpointIndex)
		input := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
		tx.TxIn = append(tx.TxIn, input)
	}
	for _, out := range outs {
		output := wire.NewTxOut(out.Value, out.ScriptPubKey)
		tx.TxOut = append(tx.TxOut, output)
	}

	// Subtract fee
	txType := spvwallet.P2SH_2of3_Multisig
	_, err := spvwallet.LockTimeFromRedeemScript(redeemScript)
	if err == nil {
		txType = spvwallet.P2SH_Multisig_Timelock_2Sigs
	}
	estimatedSize := spvwallet.EstimateSerializeSize(len(ins), tx.TxOut, false, txType)
	fee := estimatedSize * int(feePerByte)
	if len(tx.TxOut) > 0 {
		feePerOutput := fee / len(tx.TxOut)
		for _, output := range tx.TxOut {
			output.Value -= int64(feePerOutput)
		}
	}

	// BIP 69 sorting
	txsort.InPlaceSort(tx)

	signingKey, err := key.ECPrivKey()
	if err != nil {
		return sigs, err
	}

	hashes := txscript.NewTxSigHashes(tx)
	for i := range tx.TxIn {
		sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, ins[i].Value, redeemScript, txscript.SigHashAll, signingKey)
		if err != nil {
			continue
		}
		bs := spvwallet.Signature{InputIndex: uint32(i), Signature: sig}
		sigs = append(sigs, bs)
	}
	return sigs, nil
}

func (w *BitcoindWallet) Multisign(ins []spvwallet.TransactionInput, outs []spvwallet.TransactionOutput, sigs1 []spvwallet.Signature, sigs2 []spvwallet.Signature, redeemScript []byte, feePerByte uint64, broadcast bool) ([]byte, error) {
	tx := wire.NewMsgTx(1)
	for _, in := range ins {
		ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash))
		if err != nil {
			return nil, err
		}
		outpoint := wire.NewOutPoint(ch, in.OutpointIndex)
		input := wire.NewTxIn(outpoint, []byte{}, [][]byte{})
		tx.TxIn = append(tx.TxIn, input)
	}
	for _, out := range outs {
		output := wire.NewTxOut(out.Value, out.ScriptPubKey)
		tx.TxOut = append(tx.TxOut, output)
	}

	// Subtract fee
	txType := spvwallet.P2SH_2of3_Multisig
	_, err := spvwallet.LockTimeFromRedeemScript(redeemScript)
	if err == nil {
		txType = spvwallet.P2SH_Multisig_Timelock_2Sigs
	}
	estimatedSize := spvwallet.EstimateSerializeSize(len(ins), tx.TxOut, false, txType)
	fee := estimatedSize * int(feePerByte)
	if len(tx.TxOut) > 0 {
		feePerOutput := fee / len(tx.TxOut)
		for _, output := range tx.TxOut {
			output.Value -= int64(feePerOutput)
		}
	}

	// BIP 69 sorting
	txsort.InPlaceSort(tx)

	// Check if time locked
	var timeLocked bool
	if redeemScript[0] == txscript.OP_IF {
		timeLocked = true
	}

	for i, input := range tx.TxIn {
		var sig1 []byte
		var sig2 []byte
		for _, sig := range sigs1 {
			if int(sig.InputIndex) == i {
				sig1 = sig.Signature
				break
			}
		}
		for _, sig := range sigs2 {
			if int(sig.InputIndex) == i {
				sig2 = sig.Signature
				break
			}
		}

		witness := wire.TxWitness{[]byte{}, sig1, sig2}

		if timeLocked {
			witness = append(witness, []byte{0x01})
		}
		witness = append(witness, redeemScript)
		input.Witness = witness
	}
	// broadcast
	if broadcast {
		_, err = w.rpcClient.SendRawTransaction(tx, false)
		if err != nil {
			return nil, err
		}
	}
	var buf bytes.Buffer
	tx.BtcEncode(&buf, wire.ProtocolVersion, wire.WitnessEncoding)
	return buf.Bytes(), nil
}

func (w *BitcoindWallet) SweepAddress(utxos []spvwallet.Utxo, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel spvwallet.FeeLevel) (*chainhash.Hash, error) {
	var internalAddr btc.Address
	if address != nil {
		internalAddr = *address
	} else {
		internalAddr = w.CurrentAddress(spvwallet.INTERNAL)
	}
	script, err := txscript.PayToAddrScript(internalAddr)
	if err != nil {
		return nil, err
	}

	var val int64
	var inputs []*wire.TxIn
	additionalPrevScripts := make(map[wire.OutPoint][]byte)
	for _, u := range utxos {
		val += u.Value
		in := wire.NewTxIn(&u.Op, []byte{}, [][]byte{})
		inputs = append(inputs, in)
		additionalPrevScripts[u.Op] = u.ScriptPubkey
	}
	out := wire.NewTxOut(val, script)

	txType := spvwallet.P2PKH
	if redeemScript != nil {
		txType = spvwallet.P2SH_1of2_Multisig
		_, err := spvwallet.LockTimeFromRedeemScript(*redeemScript)
		if err == nil {
			txType = spvwallet.P2SH_Multisig_Timelock_1Sig
		}
	}
	estimatedSize := spvwallet.EstimateSerializeSize(len(utxos), []*wire.TxOut{out}, false, txType)

	// Calculate the fee
	feePerByte := int(w.GetFeePerByte(feeLevel))
	fee := estimatedSize * feePerByte

	outVal := val - int64(fee)
	if outVal < 0 {
		outVal = 0
	}
	out.Value = outVal

	tx := &wire.MsgTx{
		Version:  wire.TxVersion,
		TxIn:     inputs,
		TxOut:    []*wire.TxOut{out},
		LockTime: 0,
	}

	// BIP 69 sorting
	txsort.InPlaceSort(tx)

	// Sign tx
	privKey, err := key.ECPrivKey()
	if err != nil {
		return nil, err
	}
	pk := privKey.PubKey().SerializeCompressed()
	addressPub, err := btc.NewAddressPubKey(pk, w.params)

	getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) {
		if addressPub.EncodeAddress() == addr.EncodeAddress() {
			wif, err := btc.NewWIF(privKey, w.params, true)
			if err != nil {
				return nil, false, err
			}
			return wif.PrivKey, wif.CompressPubKey, nil
		}
		return nil, false, errors.New("Not found")
	})
	getScript := txscript.ScriptClosure(func(addr btc.Address) ([]byte, error) {
		if redeemScript == nil {
			return []byte{}, nil
		}
		return *redeemScript, nil
	})

	// Check if time locked
	var timeLocked bool
	if redeemScript != nil {
		rs := *redeemScript
		if rs[0] == txscript.OP_IF {
			timeLocked = true
			tx.Version = 2
		}
		for _, txIn := range tx.TxIn {
			locktime, err := spvwallet.LockTimeFromRedeemScript(*redeemScript)
			if err != nil {
				return nil, err
			}
			txIn.Sequence = locktime
		}
	}

	hashes := txscript.NewTxSigHashes(tx)
	for i, txIn := range tx.TxIn {
		if redeemScript == nil {
			prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint]
			script, err := txscript.SignTxOutput(w.params,
				tx, i, prevOutScript, txscript.SigHashAll, getKey,
				getScript, txIn.SignatureScript)
			if err != nil {
				return nil, errors.New("Failed to sign transaction")
			}
			txIn.SignatureScript = script
		} else {
			sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, utxos[i].Value, *redeemScript, txscript.SigHashAll, privKey)
			if err != nil {
				return nil, err
			}
			var witness wire.TxWitness
			if timeLocked {
				witness = wire.TxWitness{sig, []byte{}}
			} else {
				witness = wire.TxWitness{[]byte{}, sig}
			}
			witness = append(witness, *redeemScript)
			txIn.Witness = witness
		}
	}

	// broadcast
	_, err = w.rpcClient.SendRawTransaction(tx, false)
	if err != nil {
		return nil, err
	}
	txid := tx.TxHash()
	return &txid, nil
}

func (w *BitcoindWallet) Params() *chaincfg.Params {
	return w.params
}

func (w *BitcoindWallet) AddTransactionListener(callback func(spvwallet.TransactionCallback)) {
	w.listeners = append(w.listeners, callback)
}

func (w *BitcoindWallet) GenerateMultisigScript(keys []hd.ExtendedKey, threshold int, timeout time.Duration, timeoutKey *hd.ExtendedKey) (addr btc.Address, redeemScript []byte, err error) {
	if uint32(timeout.Hours()) > 0 && timeoutKey == nil {
		return nil, nil, errors.New("Timeout key must be non nil when using an escrow timeout")
	}

	if len(keys) < threshold {
		return nil, nil, fmt.Errorf("unable to generate multisig script with "+
			"%d required signatures when there are only %d public "+
			"keys available", threshold, len(keys))
	}

	var ecKeys []*btcec.PublicKey
	for _, key := range keys {
		ecKey, err := key.ECPubKey()
		if err != nil {
			return nil, nil, err
		}
		ecKeys = append(ecKeys, ecKey)
	}

	builder := txscript.NewScriptBuilder()
	if uint32(timeout.Hours()) == 0 {

		builder.AddInt64(int64(threshold))
		for _, key := range ecKeys {
			builder.AddData(key.SerializeCompressed())
		}
		builder.AddInt64(int64(len(ecKeys)))
		builder.AddOp(txscript.OP_CHECKMULTISIG)

	} else {
		ecKey, err := timeoutKey.ECPubKey()
		if err != nil {
			return nil, nil, err
		}
		sequenceLock := blockchain.LockTimeToSequence(false, uint32(timeout.Hours()*6))
		builder.AddOp(txscript.OP_IF)
		builder.AddInt64(int64(threshold))
		for _, key := range ecKeys {
			builder.AddData(key.SerializeCompressed())
		}
		builder.AddInt64(int64(len(ecKeys)))
		builder.AddOp(txscript.OP_CHECKMULTISIG)
		builder.AddOp(txscript.OP_ELSE).
			AddInt64(int64(sequenceLock)).
			AddOp(txscript.OP_CHECKSEQUENCEVERIFY).
			AddOp(txscript.OP_DROP).
			AddData(ecKey.SerializeCompressed()).
			AddOp(txscript.OP_CHECKSIG).
			AddOp(txscript.OP_ENDIF)
	}
	redeemScript, err = builder.Script()
	if err != nil {
		return nil, nil, err
	}

	witnessProgram := sha256.Sum256(redeemScript)

	addr, err = btc.NewAddressWitnessScriptHash(witnessProgram[:], w.params)
	if err != nil {
		return nil, nil, err
	}
	return addr, redeemScript, nil
}

func (w *BitcoindWallet) AddWatchedScript(script []byte) error {
	if !w.started {
		w.scriptsToAdd = append(w.scriptsToAdd, script)
		return nil
	}
	_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, w.params)
	if err != nil {
		return err
	}
	return w.rpcClient.ImportAddressRescan(addrs[0].EncodeAddress(), false)
}

func (w *BitcoindWallet) ReSyncBlockchain(fromHeight int32) {
	w.rpcClient.RawRequest("stop", []json.RawMessage{})
	w.rpcClient.Shutdown()
	time.Sleep(5 * time.Second)
	args := w.BuildArguments(true)
	cmd := exec.Command(w.binary, args...)
	cmd.Start()

	client, err := btcrpcclient.New(connCfg, nil)
	if err != nil {
		log.Error("Could not connect to bitcoind during rescan")
	}
	w.rpcClient = client
}

func (w *BitcoindWallet) Close() {
	if w.rpcClient != nil {
		w.rpcClient.RawRequest("stop", []json.RawMessage{})
		w.rpcClient.Shutdown()
	}
}

func defaultSocksPort(controlPort int) int {
	socksPort := 9050
	if controlPort == 9151 || controlPort == 9051 {
		controlPort--
		socksPort = controlPort
	}
	return socksPort
}


text:
@interface CCFScrollableTabStop()
- (UIColor *)_colorByDarkeningColor:(UIColor *)originalColor;
- (UIBezierPath *)_bezierPathInRect:(CGRect)rect;
- (UIBezierPath *)_triangleBezierPathInRect:(CGRect)rect;
@end

@implementation CCFScrollableTabStop {
    UIColor *_lightColor;
    UIColor *_darkColor;

    CCFScrollableTabStopSide _side;

    BOOL _highlighted;
}

#pragma mark - Synthesized properties

@synthesize highlighted = _highlighted;
@synthesize side = _side;
@synthesize delegate = _delegate;

#pragma mark - Object lifecycle

- (id)initWithFrame:(CGRect)frame colorInfo:(NSDictionary *)colorInfo side:(CCFScrollableTabStopSide)aSide {
    self = [super initWithFrame:frame];
    if( !self ) return nil;

    _lightColor = [colorInfo objectForKey:kCCFScrollableTabLightColor];
    _darkColor = [colorInfo objectForKey:kCCFScrollableTabDarkColor];
    _side = aSide;

    self.backgroundColor = [UIColor clearColor];

    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOpacity = 0.5f;
    self.layer.shadowRadius = 2.0f;
    self.layer.shadowOffset = CGSizeMake(0, 0);

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectInset(self.bounds, 1, 3)];
    self.layer.shadowPath = path.CGPath;

    return self;
}

#pragma mark - Public API

- (void)setHighlighted:(BOOL)highlighted;
{
    _highlighted = highlighted;
    [self setNeedsDisplay];
}

#pragma mark - UIView drawing

- (void)drawRect:(CGRect)rect {
    CGColorSpaceRef colorSoace = CGColorSpaceCreateDeviceRGB();
    const CGFloat locs[2] = {0.0, 1.0};
    NSArray *colors = nil;

    if( _highlighted )
    {
        colors = [NSArray arrayWithObjects:(id)[[self _colorByDarkeningColor:_lightColor] CGColor],
                  (id)[[self _colorByDarkeningColor:_darkColor ]CGColor],nil];
    }
    else
    {
        colors = [NSArray arrayWithObjects:(id)_lightColor.CGColor,(id)_darkColor.CGColor, nil];
    }
    CGGradientRef gradient = CGGradientCreateWithColors(colorSoace, (__bridge CFArrayRef)colors, locs);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSaveGState(ctx);

    UIBezierPath *path = [self _bezierPathInRect:rect];

    CGPathRef pathRef = [path CGPath];
    CGContextAddPath(ctx, pathRef);
    CGContextClip(ctx);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient);

    UIBezierPath *trianglePath = [self _triangleBezierPathInRect:rect];
    UIColor *triangleColor = [UIColor whiteColor];
    if( _highlighted )
        triangleColor = [self _colorByDarkeningColor:triangleColor];
    [triangleColor setFill];
    [trianglePath fill];

    CGContextRestoreGState(ctx);

}

#pragma mark - Private

- (UIColor *)_colorByDarkeningColor:(UIColor *)originalColor {
    CGFloat *oldComponents = (CGFloat *)CGColorGetComponents([originalColor CGColor]);
	CGFloat newComponents[4];

	int numComponents = CGColorGetNumberOfComponents([originalColor CGColor]);

	switch (numComponents)
	{
		case 2:
		{
			//grayscale
			newComponents[0] = oldComponents[0]*0.7;
			newComponents[1] = oldComponents[0]*0.7;
			newComponents[2] = oldComponents[0]*0.7;
			newComponents[3] = oldComponents[1];
			break;
		}
		case 4:
		{
			//RGBA
			newComponents[0] = oldComponents[0]*0.7;
			newComponents[1] = oldComponents[1]*0.7;
			newComponents[2] = oldComponents[2]*0.7;
			newComponents[3] = oldComponents[3];
			break;
		}
	}

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	CGColorRef newColor = CGColorCreate(colorSpace, newComponents);
	CGColorSpaceRelease(colorSpace);

	UIColor *retColor = [UIColor colorWithCGColor:newColor];
	CGColorRelease(newColor);

	return retColor;
}

- (UIBezierPath *)_bezierPathInRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    if( _side == CCFScrollableTabStopLeft )
    {
        [path moveToPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect))];
        [path addLineToPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect))];
        [path addQuadCurveToPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect)) controlPoint:CGPointMake(CGRectGetMaxX(rect) - 10.0, CGRectGetMidY(rect))];
        [path addLineToPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect))];
        [path closePath];
    }
    else
    {
        [path moveToPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect))];
        [path addLineToPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect))];
        [path addQuadCurveToPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)) controlPoint:CGPointMake(CGRectGetMinX(rect) + 10.0, CGRectGetMidY(rect))];
        [path addLineToPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect))];
        [path closePath];
    }
    return path;
}

- (UIBezierPath *)_triangleBezierPathInRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    if( _side == CCFScrollableTabStopRight )
    {
        [path moveToPoint:CGPointMake(11, 14)];
        [path addLineToPoint:CGPointMake(23, 20)];
        [path addLineToPoint:CGPointMake(11, 27)];
        [path closePath];
    }
    else
    {
        [path moveToPoint:CGPointMake(16, 14)];
        [path addLineToPoint:CGPointMake(4, 20)];
        [path addLineToPoint:CGPointMake(16, 26)];
        [path closePath];
    }
    return path;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.highlighted = YES;

    //  scroll...
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.highlighted = NO;
    [_delegate tabStopDidReceiveTouch:self];
}

@end


text:
class PageLayout extends Layout {
    public _snapChildren : boolean = true;
    public _snapDuration : number = 250;
    public _childWidth : number = 1.0;

    constructor(parent : View) {
        super(parent);

        this._scrollArea.buttonSize = 0;

        //this.scrollableY(false);
    }

    snapChildren(value? : boolean) : boolean {
        return getOrSet(this, "snapChildren", this, "_snapChildren", value, this._requestLayout);
    }

    snapDuration(value? : number) : number {
        return getOrSet(this, "snapDuration", this, "_snapDuration", value, this._requestDraw);
    }

    childWidth(value? : number) : number {
        return getOrSet(this, "childWidth", this, "_childWidth", value, this._requestLayout);
    }

    onGetContentRect() : Rect {
        var rect = super.onGetContentRect();
        if (rect.width > 0) {
            var pad = this._contentPadX();
            rect.x -= pad;
            rect.width += pad * 2;
        }
        rect.height += this._scrollBarSize();
        return rect;
    }

    onGetContentSize() : Rect {
        var size = super.onGetContentSize();
        size.height += this._scrollBarSize();
        return size;
    }

    _scrollBarSize() : number {
        if (this._children.length > 1) {
            return this._scrollArea.barSize;
        }
        return 0;
    }

    _stop() {
        this._repositionCurrentScroll(this._snapDuration);
    }

    onLoseFocus() {
        super.onLoseFocus();

        this._stop();
    }

    onLayoutChildren() {
        var barSize = this._scrollBarSize();
        var x = this._marginRect.x;
        var y = this._marginRect.y;
        for (var i=0; i < this._children.length; ++i) {
            var child = this._children[i];
            if (child._visibility === Visibility.Gone) { //TODO isChildContent() etc.
                continue;
            }
            var w = this._marginRect.width * this._childWidth;

            child.x(x + child.marginLeft());
            child.y(y + child.marginTop());
            child.width(w - child.marginLeft() - child.marginRight());
            if (child.wrapHeight()) {
                child.height(child._clampHeight(child.height()));
            }
            else {
                child.height(child._clampHeight(this._marginRect.height - barSize - child.marginTop() - child.marginBottom()));
            }

            x += w + child.marginRight();
        }
    }

    _contentPadX() : number {
        return ((1 - this._childWidth) * (this._marginRect.width / 2));
    }

    _getScrollingViewIndex() : number {
        var x = this._marginRect.centerX();
        var scrollingX = this.scrollingX();

        var closestDistance = null;
        var closest = null;
        for (var i=0; i < this._children.length; ++i) {
            var child = this._children[i];
            if (child.visibility() === Visibility.Visible) {
                var childX = child._marginRect.centerX() + scrollingX;
                var distance = Math.abs(childX - x);
                if (closest === null || distance < closestDistance) {
                    closestDistance = distance;
                    closest = i;
                }
            }
        }
        return closest;
    }

    scrollToChild(index : number, durationMs : number = 250) {
        if (index < 0 || index >= this._children.length) {
            return;
        }
        var child = this._children[index];
        var scrollX = (this._marginRect.x - child._marginRect.x) + child.marginLeft() + this._contentPadX();

        if (Math.floor(scrollX) !== Math.floor(this.scrollingX())) {
            //Scroll only if needed
            if (durationMs > 0) {
                this.scrollToX(scrollX, durationMs);
            }
            else {
                this.scrollingX(scrollX);
            }
        }
    }

    _repositionCurrentScroll(durationMs : number) {
        if (this._snapChildren) {
            var index = this._getScrollingViewIndex();
            if (index !== null) {
                this.scrollToChild(index, durationMs);
            }
        }
    }

    onInterceptInputEvent(state : ViewState, event : InputEvent) : boolean {
        var handled = super.onInterceptInputEvent(state, event);
        if (event.type === InputType.MouseUp && !this._scrollArea.isFlinging()) { //TODO or cancel
            this._stop();
        }
        return handled;
    }

    onInputScroll(event : InputEvent) : boolean {
        var index = this._getScrollingViewIndex();
        if (index !== null) {
            this.scrollToChild(index - event.scroll, this._snapDuration);
            return true;
        }
        return false;
    }

    _transformViews() { //TODO only change visible views
        var left = this._marginRect.x;
        var right = this._marginRect.right();
        var middle = this._marginRect.centerX();

        var scrollingX = this.scrollingX();

        for (var i=0; i < this._children.length; ++i) {
            var child = this._children[i];
            if (child.visibility() === Visibility.Visible) {
                var childX = child._marginRect.centerX() + scrollingX;
                var position = (childX - middle) / this._marginRect.width;

                if (position < -1.0) {
                    position = -1.0;
                }
                else if (position > 1.0) {
                    position = 1.0;
                }
                this.onTransformView(child, position);
            }
        }
    }

    onTransformView(view : View, position : number) {

    }

    onScrollingXChanged() {
        this._transformViews();
    }

    onFlingXEnd() {
        if (!this._scrollArea.isInteracting()) {
            this._repositionCurrentScroll(this._snapDuration);
        }
    }

    onLayoutReady() {
        super.onLayoutReady();

        if (!this._scrollArea.isInteracting()) {
            this._repositionCurrentScroll(0);
        }
        this._transformViews();
    }
}