text:
#if defined( INC_ALL )
  #include "crypt.h"
  #include "keyset.h"
  #include "dbms.h"
#else
  #include "crypt.h"
  #include "keyset/keyset.h"
  #include "keyset/dbms.h"
#endif /* Compiler-specific includes */

/* A structure to store ID information extracted from a certificate before
   it's added to the certificate store */

typedef struct {
	/* User identification data */
	BUFFER( CRYPT_MAX_TEXTSIZE, Clength ) \
	char C[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, SPlength ) \
	char SP[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, Llength ) \
	char L[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, Olength ) \
	char O[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, OUlength ) \
	char OU[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, CNlength ) \
	char CN[ CRYPT_MAX_TEXTSIZE + 8 ];
	BUFFER( CRYPT_MAX_TEXTSIZE, uriLength ) \
	char uri[ CRYPT_MAX_TEXTSIZE + 8 ];
	int Clength, SPlength, Llength, Olength, OUlength, CNlength, uriLength;

	/* Certificate identification data */
	BUFFER( ENCODED_DBXKEYID_SIZE, certIDlength ) \
	char certID[ ENCODED_DBXKEYID_SIZE + 8 ];
	BUFFER( ENCODED_DBXKEYID_SIZE, nameIDlength ) \
	char nameID[ ENCODED_DBXKEYID_SIZE + 8 ];
	BUFFER( ENCODED_DBXKEYID_SIZE, issuerIDlength ) \
	char issuerID[ ENCODED_DBXKEYID_SIZE + 8 ];
	BUFFER( ENCODED_DBXKEYID_SIZE, keyIDlength ) \
	char keyID[ ENCODED_DBXKEYID_SIZE + 8 ];
	int certIDlength, nameIDlength, issuerIDlength, keyIDlength;
	} CERT_ID_DATA;

#ifdef USE_DBMS

/****************************************************************************
*																			*
*								Utility Routines							*
*																			*
****************************************************************************/

/* Get the SQL string to delete data from a given table */

CHECK_RETVAL_PTR \
static char *getDeleteString( IN_ENUM( KEYMGMT_ITEM ) \
								const KEYMGMT_ITEM_TYPE itemType )
	{
	REQUIRES_N( itemType == KEYMGMT_ITEM_PKIUSER || \
				itemType == KEYMGMT_ITEM_PUBLICKEY );

	switch( itemType )
		{
		case KEYMGMT_ITEM_PKIUSER:
			return( "DELETE FROM pkiUsers WHERE " );

		case KEYMGMT_ITEM_PUBLICKEY:
			return( "DELETE FROM certificates WHERE " );
		}

	retIntError_Null();
	}

/****************************************************************************
*																			*
*							Extract ID Information							*
*																			*
****************************************************************************/

/* Extract user identification data from a certificate */

CHECK_RETVAL STDC_NONNULL_ARG( ( 3 ) ) \
static int extractCertNameData( IN_HANDLE const CRYPT_CERTIFICATE iCryptHandle,
								IN_ENUM( CRYPT_CERTTYPE ) \
									const CRYPT_CERTTYPE_TYPE certType,
								OUT CERT_ID_DATA *certIdData )
	{
	static const int nameValue = CRYPT_CERTINFO_SUBJECTNAME;
	static const int altNameValue = CRYPT_CERTINFO_SUBJECTALTNAME;
	MESSAGE_DATA msgData;
	int status;

	assert( isWritePtr( certIdData, sizeof( CERT_ID_DATA ) ) );

	REQUIRES( isHandleRangeValid( iCryptHandle ) );
	REQUIRES( certType == CRYPT_CERTTYPE_CERTIFICATE || \
			  certType == CRYPT_CERTTYPE_REQUEST_CERT || \
			  certType == CRYPT_CERTTYPE_PKIUSER );

	/* Clear return value */
	memset( certIdData, 0, sizeof( CERT_ID_DATA ) );

	/* Extract the DN and altName (URI) components.  This changes the
	   currently selected DN components but this is OK because we've got the
	   certificate locked and the prior state will be restored when we
	   unlock it */
	status = krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
							  ( MESSAGE_CAST ) &nameValue,
							  CRYPT_ATTRIBUTE_CURRENT );
	if( cryptStatusError( status ) )
		return( status );
	setMessageData( &msgData, certIdData->C, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_COUNTRYNAME );
	if( cryptStatusOK( status ) )
		certIdData->Clength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}
	setMessageData( &msgData, certIdData->SP, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_STATEORPROVINCENAME );
	if( cryptStatusOK( status ) )
		certIdData->SPlength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}
	setMessageData( &msgData, certIdData->L, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_LOCALITYNAME );
	if( cryptStatusOK( status ) )
		certIdData->Llength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}
	setMessageData( &msgData, certIdData->O, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_ORGANIZATIONNAME );
	if( cryptStatusOK( status ) )
		certIdData->Olength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}
	setMessageData( &msgData, certIdData->OU, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_ORGANIZATIONALUNITNAME );
	if( cryptStatusOK( status ) )
		certIdData->OUlength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}

	/* The CommonName component is the generic "name" associated with the
	   certificate, to make sure that there's always at least something
	   useful present to identify it we fetch the certificate holder name
	   rather than the specific common name */
	setMessageData( &msgData, certIdData->CN, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_IATTRIBUTE_HOLDERNAME );
	if( cryptStatusOK( status ) )
		certIdData->CNlength = msgData.length;
	else
		{
		if( status != CRYPT_ERROR_NOTFOUND )
			return( status );
		}

	/* PKI user objects don't have URI information so if we're processing
	   one of these we're done */
	if( certType == CRYPT_CERTTYPE_PKIUSER )
		return( CRYPT_OK );

	/* Get the URI for this certificate, in order of likelihood of
	   occurrence */
	setMessageData( &msgData, certIdData->uri, CRYPT_MAX_TEXTSIZE );
	krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
					 ( MESSAGE_CAST ) &altNameValue,
					 CRYPT_ATTRIBUTE_CURRENT );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
							  &msgData, CRYPT_CERTINFO_RFC822NAME );
	if( status == CRYPT_ERROR_NOTFOUND )
		{
		setMessageData( &msgData, certIdData->uri, CRYPT_MAX_TEXTSIZE );
		status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
								  &msgData,
								  CRYPT_CERTINFO_UNIFORMRESOURCEIDENTIFIER );
		}
	if( status == CRYPT_ERROR_NOTFOUND )
		{
		setMessageData( &msgData, certIdData->uri, CRYPT_MAX_TEXTSIZE );
		status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
								  &msgData, CRYPT_CERTINFO_DNSNAME );
		}
	if( cryptStatusOK( status ) )
		{
		int i;

		/* Force the URI (as stored) to lowercase to make case-insensitive
		   matching easier.  In most cases we could ask the back-end to do
		   this but this complicates indexing and there's no reason why we
		   can't do it here */
		for( i = 0; i < msgData.length; i++ )
			certIdData->uri[ i ] = intToByte( toLower( certIdData->uri[ i ] ) );
		certIdData->uriLength = msgData.length;
		}

	return( status );
	}

/* Extract certificate identification data from a certificate */

CHECK_RETVAL STDC_NONNULL_ARG( ( 3 ) ) \
static int extractCertIdData( IN_HANDLE const CRYPT_CERTIFICATE iCryptHandle,
							  IN_ENUM( CRYPT_CERTTYPE ) \
								const CRYPT_CERTTYPE_TYPE certType,
							  INOUT CERT_ID_DATA *certIdData )
	{
	MESSAGE_DATA msgData;
	int status;

	assert( isWritePtr( certIdData, sizeof( CERT_ID_DATA ) ) );

	REQUIRES( isHandleRangeValid( iCryptHandle ) );
	REQUIRES( certType == CRYPT_CERTTYPE_CERTIFICATE || \
			  certType == CRYPT_CERTTYPE_REQUEST_CERT || \
			  certType == CRYPT_CERTTYPE_PKIUSER );

	/* Get general ID information */
	status = getKeyID( certIdData->certID, ENCODED_DBXKEYID_SIZE,
					   &certIdData->certIDlength, iCryptHandle,
					   CRYPT_CERTINFO_FINGERPRINT_SHA1 );
	if( cryptStatusError( status ) )
		return( status );

	/* Get object-specific ID information */
	if( certType == CRYPT_CERTTYPE_CERTIFICATE )
		{
		status = getKeyID( certIdData->nameID, ENCODED_DBXKEYID_SIZE,
						   &certIdData->nameIDlength, iCryptHandle,
						   CRYPT_IATTRIBUTE_SUBJECT );
		if( cryptStatusOK( status ) )
			status = getKeyID( certIdData->issuerID, ENCODED_DBXKEYID_SIZE,
							   &certIdData->issuerIDlength, iCryptHandle,
							   CRYPT_IATTRIBUTE_ISSUERANDSERIALNUMBER );
		if( cryptStatusOK( status ) )
			status = getCertKeyID( certIdData->keyID, ENCODED_DBXKEYID_SIZE,
								   &certIdData->keyIDlength, iCryptHandle );
		return( status );
		}
	if( certType == CRYPT_CERTTYPE_PKIUSER )
		{
		BYTE binaryKeyID[ 64 + 8 ];
		char encKeyID[ CRYPT_MAX_TEXTSIZE + 8 ];
		int binaryKeyIDlength;

		/* Get the PKI user ID.  We can't read this directly since it's
		   returned in text form for use by end users so we have to read the
		   encoded form, decode it, and then turn the decoded binary value
		   into a key ID.  We identify the result as a keyID,
		   (== subjectKeyIdentifier, which it isn't really) but we need to
		   use this to ensure that it's hashed/expanded out to the correct
		   size */
		setMessageData( &msgData, encKeyID, CRYPT_MAX_TEXTSIZE );
		status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
								  &msgData, CRYPT_CERTINFO_PKIUSER_ID );
		if( cryptStatusError( status ) )
			return( status );
		status =  decodePKIUserValue( binaryKeyID, 64, &binaryKeyIDlength,
									  encKeyID, msgData.length );
		if( cryptStatusOK( status ) )
			status = makeKeyID( certIdData->keyID, ENCODED_DBXKEYID_SIZE,
								&certIdData->keyIDlength, CRYPT_IKEYID_KEYID,
								binaryKeyID, binaryKeyIDlength );
		if( cryptStatusOK( status ) )
			status = getKeyID( certIdData->nameID, ENCODED_DBXKEYID_SIZE,
							   &certIdData->nameIDlength, iCryptHandle,
							   CRYPT_IATTRIBUTE_SUBJECT );
		return( status );
		}

	return( CRYPT_OK );
	}

/* Extract certificate identification data from a CRL */

CHECK_RETVAL STDC_NONNULL_ARG( ( 3 ) ) \
static int extractCrlIdData( IN_HANDLE const CRYPT_CERTIFICATE iCryptCRL,
							 IN_HANDLE_OPT \
								const CRYPT_CERTIFICATE iCryptRevokeCert,
							 OUT CERT_ID_DATA *crlIdData )
	{
	int status;

	assert( isWritePtr( crlIdData, sizeof( CERT_ID_DATA ) ) );

	REQUIRES( isHandleRangeValid( iCryptCRL ) );
	REQUIRES( iCryptRevokeCert == CRYPT_UNUSED || \
			  isHandleRangeValid( iCryptRevokeCert ) );

	/* Clear return value */
	memset( crlIdData, 0, sizeof( CERT_ID_DATA ) );

	/* Get general ID information */
	status = getKeyID( crlIdData->issuerID, ENCODED_DBXKEYID_SIZE,
					   &crlIdData->issuerIDlength, iCryptCRL,
					   CRYPT_IATTRIBUTE_ISSUERANDSERIALNUMBER );
	if( cryptStatusError( status ) )
		return( status );

	/* If there's no certificate being revoked present (i.e. we're just
	   adding a set of CRL entries), we're done */
	if( iCryptRevokeCert == CRYPT_UNUSED )
		return( CRYPT_OK );

	/* Get the certificate ID and the name ID of the issuer from the
	   certificate being revoked */
	status = getKeyID( crlIdData->certID, ENCODED_DBXKEYID_SIZE,
					   &crlIdData->certIDlength, iCryptRevokeCert,
					   CRYPT_CERTINFO_FINGERPRINT_SHA1 );
	if( cryptStatusOK( status ) )
		status = getKeyID( crlIdData->nameID, ENCODED_DBXKEYID_SIZE,
						   &crlIdData->nameIDlength, iCryptRevokeCert,
						   CRYPT_IATTRIBUTE_ISSUER );
	return( status );
	}

/****************************************************************************
*																			*
*							Database Add Routines							*
*																			*
****************************************************************************/

/* Add a certificate object (certificate, certificate request, PKI user) to
   a certificate store.  Normally existing rows would be overwritten if we
   added duplicate entries but the UNIQUE constraint on the indices will
   catch this */

CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 6 ) ) \
int addCert( INOUT DBMS_INFO *dbmsInfo,
			 IN_HANDLE const CRYPT_HANDLE iCryptHandle,
			 IN_ENUM( CRYPT_CERTTYPE ) const CRYPT_CERTTYPE_TYPE certType,
			 IN_ENUM( CERTADD ) const CERTADD_TYPE addType,
			 IN_ENUM( DBMS_UPDATE ) const DBMS_UPDATE_TYPE updateType,
			 INOUT ERROR_INFO *errorInfo )
	{
	MESSAGE_DATA msgData;
	BOUND_DATA boundData[ BOUND_DATA_MAXITEMS ], *boundDataPtr = boundData;
	CERT_ID_DATA certIdData;
	BYTE certData[ MAX_CERT_SIZE + 8 ];
	char encodedCertData[ MAX_ENCODED_CERT_SIZE + 8 ];
	const char *sqlString;
	time_t boundDate;
	int certDataLength = DUMMY_INIT, boundDataIndex, status;

	assert( isWritePtr( dbmsInfo, sizeof( DBMS_INFO ) ) );

	REQUIRES( isHandleRangeValid( iCryptHandle ) );
	REQUIRES( certType == CRYPT_CERTTYPE_CERTIFICATE || \
			  certType == CRYPT_CERTTYPE_REQUEST_CERT || \
			  certType == CRYPT_CERTTYPE_PKIUSER );
	REQUIRES( addType > CERTADD_NONE && addType < CERTADD_LAST );
	REQUIRES( updateType > DBMS_UPDATE_NONE && \
			  updateType < DBMS_UPDATE_LAST );
	REQUIRES( errorInfo != NULL );

	/* Extract name-related information from the certificate */
	status = extractCertNameData( iCryptHandle, certType, &certIdData );
	if( ( cryptStatusOK( status ) || status == CRYPT_ERROR_NOTFOUND ) && \
		( certType == CRYPT_CERTTYPE_CERTIFICATE ) )
		{
		setMessageData( &msgData, &boundDate, sizeof( time_t ) );
		status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE_S,
								  &msgData, CRYPT_CERTINFO_VALIDTO );
		}
	else
		{
		if( status == CRYPT_ERROR_NOTFOUND )
			status = CRYPT_OK;
		}
	if( cryptStatusError( status ) )
		{
		/* Convert any low-level certificate-specific error into something
		   generic that makes a bit more sense to the caller */
		retExtArg( CRYPT_ARGERROR_NUM1,
				   ( CRYPT_ARGERROR_NUM1, errorInfo,
					 "Couldn't extract user identification information "
					 "from certificate" ) );
		}

	/* Get the ID information and certificate data from the certificate */
	status = extractCertIdData( iCryptHandle, certType, &certIdData );
	if( cryptStatusOK( status ) )
		{
		status = extractCertData( iCryptHandle,
								  ( certType == CRYPT_CERTTYPE_PKIUSER ) ? \
									CRYPT_ICERTFORMAT_DATA : \
									CRYPT_CERTFORMAT_CERTIFICATE,
								  certData, MAX_CERT_SIZE, &certDataLength );
		}
	if( cryptStatusError( status ) )
		{
		/* Convert any low-level certificate-specific error into something
		   generic that makes a bit more sense to the caller */
		retExtArg( CRYPT_ARGERROR_NUM1,
				   ( CRYPT_ARGERROR_NUM1, errorInfo,
					 "Couldn't extract certificate data from "
					 "certificate" ) );
		}

	/* If this is a partial add (in which we add a certificate item which is
	   in the initial stages of the creation process so that although the
	   item may be physically present in the store it can't be accessed
	   directly) we set the first byte to 0xFF to indicate this.  In
	   addition we set the first two bytes of the IDs that have uniqueness
	   constraints to an out-of-band value to prevent a clash with the
	   finished entry when we complete the issue process and replace the
	   partial version with the full version */
	if( addType == CERTADD_PARTIAL || addType == CERTADD_PARTIAL_RENEWAL )
		{
		const char *escapeStr = ( addType == CERTADD_PARTIAL ) ? \
								KEYID_ESC1 : KEYID_ESC2;

		certData[ 0 ] = 0xFF;
		memcpy( certIdData.issuerID, escapeStr, KEYID_ESC_SIZE );
		memcpy( certIdData.keyID, escapeStr, KEYID_ESC_SIZE );
		memcpy( certIdData.certID, escapeStr, KEYID_ESC_SIZE );
		}

	/* Set up the certificate object data to be written and send it to the
	   database */
	initBoundData( boundDataPtr );
	setBoundData( boundDataPtr, 0, certIdData.C, certIdData.Clength );
	setBoundData( boundDataPtr, 1, certIdData.SP, certIdData.SPlength );
	setBoundData( boundDataPtr, 2, certIdData.L, certIdData.Llength );
	setBoundData( boundDataPtr, 3, certIdData.O, certIdData.Olength );
	setBoundData( boundDataPtr, 4, certIdData.OU, certIdData.OUlength );
	setBoundData( boundDataPtr, 5, certIdData.CN, certIdData.CNlength );
	switch( certType )
		{
		case CRYPT_CERTTYPE_CERTIFICATE:
			setBoundData( boundDataPtr, 6, certIdData.uri,
						  certIdData.uriLength );
			setBoundDataDate( boundDataPtr, 7, &boundDate );
			setBoundData( boundDataPtr, 8, certIdData.nameID,
						  certIdData.nameIDlength );
			setBoundData( boundDataPtr, 9, certIdData.issuerID,
						  certIdData.issuerIDlength );
			setBoundData( boundDataPtr, 10, certIdData.keyID,
						  certIdData.keyIDlength );
			boundDataIndex = 11;
			sqlString = \
			"INSERT INTO certificates VALUES (?, ?, ?, ?, ?, ?, ?,"
											 "?, ?, ?, ?, ?, ?)";
			break;

		case CRYPT_CERTTYPE_REQUEST_CERT:
			setBoundData( boundDataPtr, 6, certIdData.uri,
						  certIdData.uriLength );
			boundDataIndex = 7;
			sqlString = \
			"INSERT INTO certRequests VALUES ('" TEXT_CERTTYPE_REQUEST_CERT "', "
											 "?, ?, ?, ?, ?, ?, ?, ?, ?)";
			break;

		case CRYPT_CERTTYPE_PKIUSER:
			setBoundData( boundDataPtr, 6, certIdData.nameID,
						  certIdData.nameIDlength );
			setBoundData( boundDataPtr, 7, certIdData.keyID,
						  certIdData.keyIDlength );
			boundDataIndex = 8;
			sqlString = \
			"INSERT INTO pkiUsers VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
			break;

		default:
			retIntError();
		}
	setBoundData( boundDataPtr, boundDataIndex++, certIdData.certID,
				  certIdData.certIDlength );
	if( hasBinaryBlobs( dbmsInfo ) )
		{
		setBoundDataBlob( boundDataPtr, boundDataIndex,
						  certData, certDataLength );
		}
	else
		{
		int encodedCertDataLength;

		status = base64encode( encodedCertData, MAX_ENCODED_CERT_SIZE,
							   &encodedCertDataLength, certData,
							   certDataLength, CRYPT_CERTTYPE_NONE );
		if( cryptStatusError( status ) )
			{
			DEBUG_DIAG(( "Couldn't base64-encode data" ));
			assert( DEBUG_WARN );
			retIntError();
			}
		setBoundData( boundDataPtr, boundDataIndex, encodedCertData,
					  encodedCertDataLength );
		}
	status = dbmsUpdate( sqlString, boundDataPtr, updateType );
	if( cryptStatusError( status ) )
		{
		retExtErr( status,
				   ( status, errorInfo, getDbmsErrorInfo( dbmsInfo ),
					 "Certificate add operation failed: " ) );
		}
	return( CRYPT_OK );
	}

/* Add a CRL to a certificate store */

CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 5 ) ) \
int addCRL( INOUT DBMS_INFO *dbmsInfo,
			IN_HANDLE const CRYPT_CERTIFICATE iCryptCRL,
			IN_HANDLE_OPT const CRYPT_CERTIFICATE iCryptRevokeCert,
			IN_ENUM( DBMS_UPDATE ) const DBMS_UPDATE_TYPE updateType,
			INOUT ERROR_INFO *errorInfo )
	{
	BOUND_DATA boundData[ BOUND_DATA_MAXITEMS ], *boundDataPtr = boundData;
	CERT_ID_DATA crlIdData;
	BYTE certData[ MAX_CERT_SIZE + 8 ];
	char encodedCertData[ MAX_ENCODED_CERT_SIZE + 8 ];
	const char *sqlString;
	time_t expiryDate = 0;
	int certDataLength = DUMMY_INIT, boundDataIndex, status;

	assert( isWritePtr( dbmsInfo, sizeof( DBMS_INFO ) ) );

	REQUIRES( isHandleRangeValid( iCryptCRL ) );
	REQUIRES( ( isCertStore( dbmsInfo ) && \
				isHandleRangeValid( iCryptRevokeCert ) ) || \
			  ( !isCertStore( dbmsInfo ) && \
				iCryptRevokeCert == CRYPT_UNUSED ) );
	REQUIRES( updateType > DBMS_UPDATE_NONE && \
			  updateType < DBMS_UPDATE_LAST );
	REQUIRES( errorInfo != NULL );

	/* Get the ID information for the current CRL entry */
	status = extractCrlIdData( iCryptCRL, iCryptRevokeCert, &crlIdData );
	if( cryptStatusOK( status ) )
		status = extractCertData( iCryptCRL, CRYPT_IATTRIBUTE_CRLENTRY,
								  certData, MAX_CERT_SIZE, &certDataLength );
	if( cryptStatusOK( status ) && isCertStore( dbmsInfo ) )
		{
		MESSAGE_DATA msgData;

		setMessageData( &msgData, &expiryDate, sizeof( time_t ) );
		status = krnlSendMessage( iCryptRevokeCert, IMESSAGE_GETATTRIBUTE_S,
								  &msgData, CRYPT_CERTINFO_VALIDTO );
		}
	if( cryptStatusError( status ) )
		{
		/* Convert any low-level certificate-specific error into something
		   generic that makes a bit more sense to the caller */
		retExtArg( CRYPT_ARGERROR_NUM1,
				   ( CRYPT_ARGERROR_NUM1, errorInfo,
					 "Couldn't extract CRL data from CRL" ) );
		}

	/* Set up the certificate object data to be written and send it to the
	   database.  Certificate stores contain extra inforomation that's
	   needed to build a CRL so we have to vary the SQL string depending on
	   the keyset type */
	initBoundData( boundDataPtr );
	if( isCertStore( dbmsInfo ) )
		{
		setBoundDataDate( boundDataPtr, 0, &expiryDate );
		setBoundData( boundDataPtr, 1, crlIdData.nameID,
					  crlIdData.nameIDlength );
		setBoundData( boundDataPtr, 2, crlIdData.issuerID,
					  crlIdData.issuerIDlength );
		setBoundData( boundDataPtr, 3, crlIdData.certID,
					  crlIdData.certIDlength );
		boundDataIndex = 4;
		sqlString = "INSERT INTO CRLs VALUES (?, ?, ?, ?, ?)";

		}
	else
		{
		setBoundData( boundDataPtr, 0, crlIdData.issuerID,
					  crlIdData.issuerIDlength );
		boundDataIndex = 1;
		sqlString = "INSERT INTO CRLs VALUES (?, ?)";
		}
	if( hasBinaryBlobs( dbmsInfo ) )
		{
		setBoundDataBlob( boundDataPtr, boundDataIndex, certData,
						  certDataLength );
		}
	else
		{
		int encodedCertDataLength;

		status = base64encode( encodedCertData, MAX_ENCODED_CERT_SIZE,
							   &encodedCertDataLength, certData,
							   certDataLength, CRYPT_CERTTYPE_NONE );
		if( cryptStatusError( status ) )
			{
			DEBUG_DIAG(( "Couldn't base64-encode data" ));
			assert( DEBUG_WARN );
			retIntError();
			}
		setBoundData( boundDataPtr, boundDataIndex, encodedCertData,
					  encodedCertDataLength );
		}
	status = dbmsUpdate( sqlString, boundDataPtr, updateType );
	if( cryptStatusError( status ) )
		{
		retExtErr( status,
				   ( status, errorInfo, getDbmsErrorInfo( dbmsInfo ),
					 "CRL add operation failed: " ) );
		}

	return( CRYPT_OK );
	}

/* Add an item to the certificate store */

CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
static int setItemFunction( INOUT KEYSET_INFO *keysetInfoPtr,
							IN_HANDLE const CRYPT_HANDLE iCryptHandle,
							IN_ENUM( KEYMGMT_ITEM ) \
								const KEYMGMT_ITEM_TYPE itemType,
							STDC_UNUSED const char *password,
							STDC_UNUSED const int passwordLength,
							IN_FLAGS( KEYMGMT ) const int flags )
	{
	DBMS_INFO *dbmsInfo = keysetInfoPtr->keysetDBMS;
	BOOLEAN seenNonDuplicate = FALSE;
	int type, iterationCount = 0, status;

	assert( isWritePtr( keysetInfoPtr, sizeof( KEYSET_INFO ) ) );

	REQUIRES( keysetInfoPtr->type == KEYSET_DBMS );
	REQUIRES( isHandleRangeValid( iCryptHandle ) );
	REQUIRES( itemType == KEYMGMT_ITEM_PUBLICKEY || \
			  itemType == KEYMGMT_ITEM_REVOCATIONINFO || \
			  itemType == KEYMGMT_ITEM_REQUEST || \
			  itemType == KEYMGMT_ITEM_REVREQUEST || \
			  itemType == KEYMGMT_ITEM_PKIUSER );
	REQUIRES( password == NULL && passwordLength == 0 );
	REQUIRES( flags >= KEYMGMT_FLAG_NONE && flags < KEYMGMT_FLAG_MAX );

	/* Make sure that we've been given a certificate, certificate chain, or
	   CRL (or a PKI user if it's a CA certificate store).  We can't do any
	   more specific checking against the itemType because if it's coming
	   from outside cryptlib it'll just be passed in as a generic
	   certificate object with no distinction between object subtypes */
	status = krnlSendMessage( iCryptHandle, IMESSAGE_GETATTRIBUTE,
							  &type, CRYPT_CERTINFO_CERTTYPE );
	if( cryptStatusError( status ) )
		return( CRYPT_ARGERROR_NUM1 );
	if( isCertStore( dbmsInfo ) )
		{
		/* The only item that can be inserted directly into a CA certificate
		   store is a CA request or PKI user information */
		if( type != CRYPT_CERTTYPE_CERTREQUEST && \
			type != CRYPT_CERTTYPE_REQUEST_CERT && \
			type != CRYPT_CERTTYPE_REQUEST_REVOCATION && \
			type != CRYPT_CERTTYPE_PKIUSER )
			{
			retExtArg( CRYPT_ARGERROR_NUM1,
					   ( CRYPT_ARGERROR_NUM1, KEYSET_ERRINFO,
						 "Invalid item type for CA certificate store" ) );
			}

		if( itemType == KEYMGMT_ITEM_PKIUSER )
			{
			REQUIRES( type == CRYPT_CERTTYPE_PKIUSER );
			return( caAddPKIUser( dbmsInfo, iCryptHandle, KEYSET_ERRINFO ) );
			}

		/* It's a certificate request being added to a CA certificate
		   store */
		REQUIRES( ( itemType == KEYMGMT_ITEM_REQUEST && \
					( type == CRYPT_CERTTYPE_CERTREQUEST || \
					  type == CRYPT_CERTTYPE_REQUEST_CERT ) ) || \
				  ( itemType == KEYMGMT_ITEM_REVREQUEST && \
				    type == CRYPT_CERTTYPE_REQUEST_REVOCATION ) );
		return( caAddCertRequest( dbmsInfo, iCryptHandle, type,
								  ( flags & KEYMGMT_FLAG_UPDATE ) ? \
									TRUE : FALSE,
								  ( flags & KEYMGMT_FLAG_INITIALOP ) ? \
									TRUE : FALSE, KEYSET_ERRINFO ) );
		}
	if( type != CRYPT_CERTTYPE_CERTIFICATE && \
		type != CRYPT_CERTTYPE_CERTCHAIN && \
		type != CRYPT_CERTTYPE_CRL )
		{
		retExtArg( CRYPT_ARGERROR_NUM1,
				   ( CRYPT_ARGERROR_NUM1, KEYSET_ERRINFO,
					 "Item being added must be a CRL or certificate" ) );
		}

	REQUIRES( itemType == KEYMGMT_ITEM_PUBLICKEY || \
			  itemType == KEYMGMT_ITEM_REVOCATIONINFO );

	/* Lock the certificate or CRL for our exclusive use and select the
	   first sub-item (certificate in a certificate chain, entry in a CRL),
	   update the keyset with the certificate(s)/CRL entries, and unlock it
	   to allow others access */
	status = krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
							  MESSAGE_VALUE_TRUE, CRYPT_IATTRIBUTE_LOCKED );
	if( cryptStatusError( status ) )
		return( status );
	status = krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
							  MESSAGE_VALUE_CURSORFIRST,
							  CRYPT_CERTINFO_CURRENT_CERTIFICATE );
	if( cryptStatusError( status ) )
		{
		( void ) krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
								  MESSAGE_VALUE_FALSE,
								  CRYPT_IATTRIBUTE_LOCKED );
		return( status );
		}
	do
		{
		/* Add the certificate or CRL */
		if( type == CRYPT_CERTTYPE_CRL )
			status = addCRL( dbmsInfo, iCryptHandle, CRYPT_UNUSED,
							 DBMS_UPDATE_NORMAL, KEYSET_ERRINFO );
		else
			status = addCert( dbmsInfo, iCryptHandle,
							  CRYPT_CERTTYPE_CERTIFICATE, CERTADD_NORMAL,
							  DBMS_UPDATE_NORMAL, KEYSET_ERRINFO );

		/* An item being added may already be present but we can't fail
		   immediately because what's being added may be a chain containing
		   further certificates or a CRL containing further entries so we
		   keep track of whether we've successfully added at least one item
		   and clear data duplicate errors */
		if( status == CRYPT_OK )
			seenNonDuplicate = TRUE;
		else
			{
			if( status == CRYPT_ERROR_DUPLICATE )
				status = CRYPT_OK;
			}
		}
	while( cryptStatusOK( status ) && \
		   krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
							MESSAGE_VALUE_CURSORNEXT,
							CRYPT_CERTINFO_CURRENT_CERTIFICATE ) == CRYPT_OK && \
		   iterationCount++ < FAILSAFE_ITERATIONS_MED );
	ENSURES( iterationCount < FAILSAFE_ITERATIONS_MED );
	( void ) krnlSendMessage( iCryptHandle, IMESSAGE_SETATTRIBUTE,
							  MESSAGE_VALUE_FALSE, CRYPT_IATTRIBUTE_LOCKED );
	if( cryptStatusOK( status ) && !seenNonDuplicate )
		{
		/* We reached the end of the certificate chain/CRL without finding
		   anything that we could add, return a data duplicate error */
		retExt( CRYPT_ERROR_DUPLICATE,
				( CRYPT_ERROR_DUPLICATE, KEYSET_ERRINFO,
				  "No new %s were found to add to the certificate store",
				  ( type == CRYPT_CERTTYPE_CRL ) ? \
					"CRL entries" : "certificates" ) );
		}

	return( status );
	}

/* Delete an item from the certificate store */

CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 4 ) ) \
static int deleteItemFunction( INOUT KEYSET_INFO *keysetInfoPtr,
							   IN_ENUM( KEYMGMT_ITEM ) \
								const KEYMGMT_ITEM_TYPE itemType,
							   IN_KEYID const CRYPT_KEYID_TYPE keyIDtype,
							   IN_BUFFER( keyIDlength ) const void *keyID,
							   IN_LENGTH_KEYID const int keyIDlength )
	{
	DBMS_INFO *dbmsInfo = keysetInfoPtr->keysetDBMS;
	BOUND_DATA boundData[ BOUND_DATA_MAXITEMS ], *boundDataPtr = boundData;
	char sqlBuffer[ MAX_SQL_QUERY_SIZE + 8 ];
	char encodedKeyID[ ( CRYPT_MAX_TEXTSIZE * 2 ) + 8 ];
	const char *keyName = getKeyName( keyIDtype );
	const char *deleteString = getDeleteString( itemType );
	int encodedKeyIDlength, status;

	assert( isWritePtr( keysetInfoPtr, sizeof( KEYSET_INFO ) ) );
	assert( isReadPtr( keyID, keyIDlength ) );

	REQUIRES( keysetInfoPtr->type == KEYSET_DBMS );
	REQUIRES( itemType == KEYMGMT_ITEM_PUBLICKEY || \
			  itemType == KEYMGMT_ITEM_PKIUSER );
	REQUIRES( ( !isCertStore( dbmsInfo ) && \
				itemType == KEYMGMT_ITEM_PUBLICKEY ) || \
			  ( isCertStore( dbmsInfo ) && \
				itemType == KEYMGMT_ITEM_PKIUSER ) );
	REQUIRES( keyIDtype > CRYPT_KEYID_NONE && \
			  keyIDtype < CRYPT_KEYID_LAST );
	REQUIRES( keyIDlength >= MIN_NAME_LENGTH && \
			  keyIDlength < MAX_ATTRIBUTE_SIZE );

	/* Delete the item from the certificate store */
	status = makeKeyID( encodedKeyID, CRYPT_MAX_TEXTSIZE * 2,
						&encodedKeyIDlength, keyIDtype, keyID, keyIDlength );
	if( cryptStatusError( status ) )
		return( CRYPT_ARGERROR_STR1 );
	if( isCertStore( dbmsInfo ) )
		{
		/* The only item that can be deleted from a CA certificate store is
		   PKI user information */
		if( itemType != KEYMGMT_ITEM_PKIUSER )
			{
			retExtArg( CRYPT_ARGERROR_NUM1,
					   ( CRYPT_ARGERROR_NUM1, KEYSET_ERRINFO,
						 "Invalid operation for CA certificate store" ) );
			}

		return( caDeletePKIUser( dbmsInfo, keyIDtype, keyID, keyIDlength,
								 KEYSET_ERRINFO ) );
		}
	ENSURES( keyName != NULL && deleteString != NULL );
	strlcpy_s( sqlBuffer, MAX_SQL_QUERY_SIZE, deleteString );
	strlcat_s( sqlBuffer, MAX_SQL_QUERY_SIZE, keyName );
	strlcat_s( sqlBuffer, MAX_SQL_QUERY_SIZE, " = ?" );
	initBoundData( boundDataPtr );
	setBoundData( boundDataPtr, 0, encodedKeyID, encodedKeyIDlength );
	status = dbmsUpdate( sqlBuffer, boundDataPtr, DBMS_UPDATE_NORMAL );
	if( cryptStatusError( status ) )
		{
		retExtErr( status,
				   ( status, KEYSET_ERRINFO, getDbmsErrorInfo( dbmsInfo ),
					 "Certificate delete operation failed: " ) );
		}
	return( CRYPT_OK );
	}

/****************************************************************************
*																			*
*							Database Access Routines						*
*																			*
****************************************************************************/

CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
int initDBMSwrite( INOUT KEYSET_INFO *keysetInfoPtr )
	{
	assert( isWritePtr( keysetInfoPtr, sizeof( KEYSET_INFO ) ) );

	REQUIRES( keysetInfoPtr->type == KEYSET_DBMS );

	keysetInfoPtr->setItemFunction = setItemFunction;
	keysetInfoPtr->deleteItemFunction = deleteItemFunction;

	return( CRYPT_OK );
	}
#endif /* USE_DBMS */


text:
import os
import unittest

import pytest

from sparknlp.annotator import *
from sparknlp.base import *
from test.util import SparkContextForTest

@pytest.mark.fast
class AlbertForTokenClassificationTestSpec(unittest.TestCase):
    def setUp(self):
        self.data = SparkContextForTest.spark.read.option("header", "true") \
            .csv(path="file:///" + os.getcwd() + "/../src/test/resources/embeddings/sentence_embeddings.csv")

    def runTest(self):
        document_assembler = DocumentAssembler() \
            .setInputCol("text") \
            .setOutputCol("document")

        tokenizer = Tokenizer().setInputCols("document").setOutputCol("token")

        token_classifier = AlbertForTokenClassification.pretrained() \
            .setInputCols(["document", "token"]) \
            .setOutputCol("ner")

        pipeline = Pipeline(stages=[
            document_assembler,
            tokenizer,
            token_classifier
        ])

        model = pipeline.fit(self.data)
        model.transform(self.data).show()
        print(token_classifier.getClasses())
        print(token_classifier.getBatchSize())

redpajama_set_name: RedPajamaGithub


text:
package javasmmr.zoowsome.models.animals;

public class Wolf extends Mammal {
	public Wolf(String name, int nrOfLegs, float normalBodyTemp, float percBodyHair, double maintenanceCost, double dangerPerc) {
		super(maintenanceCost, dangerPerc);
		this.setName(name);
		this.setNrOfLegs(nrOfLegs);
		this.setNormalBodyTemp(normalBodyTemp);
		this.setPercBodyHair(percBodyHair);
	}
	public Wolf() {
		this.setName("John Snow");
		this.setNrOfLegs(4);
		this.setNormalBodyTemp(38.0f);
		this.setPercBodyHair(100.0f);
	}
}


text:
require 'spec_helper'
require 'omniauth/strategies/saml'

RSpec.describe 'processing of SAMLResponse in dependencies' do
  let(:mock_saml_response) { File.read('spec/fixtures/authentication/saml_response.xml') }
  let(:saml_strategy) { OmniAuth::Strategies::SAML.new({}) }
  let(:session_mock) { {} }
  let(:settings) { OpenStruct.new({ soft: false, idp_cert_fingerprint: 'something' }) }
  let(:auth_hash) { Gitlab::Auth::Saml::AuthHash.new(saml_strategy) }

  subject { auth_hash.authn_context }

  before do
    allow(saml_strategy).to receive(:session).and_return(session_mock)
    allow_next_instance_of(OneLogin::RubySaml::Response) do |instance|
      allow(instance).to receive(:is_valid?).and_return(true)
    end
    saml_strategy.send(:handle_response, mock_saml_response, {}, settings ) { }
  end

  it 'can extract AuthnContextClassRef from SAMLResponse param' do
    is_expected.to eq 'urn:oasis:names:tc:SAML:2.0:ac:classes:Password'
  end
end


text:
package com.wordwise.util;

import java.util.List;

import android.app.Activity;
import android.content.Loader;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wordwise.R;
import com.wordwise.loader.TranslationLoader;
import com.wordwise.loader.WordLoader;
import com.wordwise.model.GameManagerContainer;
import com.wordwise.server.dto.DTOTranslation;
import com.wordwise.server.dto.DTOWord;

/**
 * This is a helper class that encapsulates implementation for asynchronously
 * loading data from the server
 *
 * @author Ugur Adiguzel, Dragan Mileski, Giovanni Maia
 * */
public class LoaderHelper {
	// type of the data that can be loaded from the server
	public enum LoaderType {
		TRANSLATION_LOADER, WORD_LOADER,
	}
	// UI elements
	private LinearLayout loadingFailed;
	private TextView loadingFailedText;
	private Button retryButton, nextGameButton;
	private LinearLayout loading;
	private ProgressBar progress;

	@SuppressWarnings("unchecked")
	public void initLoader(Activity activity, LoaderType loaderType) {
		if (loaderType == LoaderType.TRANSLATION_LOADER) {
			activity.getLoaderManager()
					.initLoader(
							0,
							null,
							(android.app.LoaderManager.LoaderCallbacks<List<DTOTranslation>>) activity)
					.forceLoad();
		} else if (loaderType == LoaderType.WORD_LOADER) {
			activity.getLoaderManager()
					.initLoader(
							0,
							null,
							(android.app.LoaderManager.LoaderCallbacks<List<DTOWord>>) activity)
					.forceLoad();
		}
	}

	@SuppressWarnings("unchecked")
	public void restartLoader(Activity activity, LoaderType loaderType) {
		if (loaderType == LoaderType.TRANSLATION_LOADER) {
			activity.getLoaderManager()
					.restartLoader(
							0,
							null,
							(android.app.LoaderManager.LoaderCallbacks<List<DTOTranslation>>) activity)
					.forceLoad();
		} else if (loaderType == LoaderType.WORD_LOADER) {
			activity.getLoaderManager()
					.restartLoader(
							0,
							null,
							(android.app.LoaderManager.LoaderCallbacks<List<DTOWord>>) activity)
					.forceLoad();
		}
	}

	public void onLoaderReset(Activity activity) {
		initScreen(activity);
	}

	public Loader<?> onLoadCreated(Activity activity, LoaderType loaderType) {
		if (loaderType == LoaderType.TRANSLATION_LOADER) {
			initScreen(activity);
			return new TranslationLoader(activity);
		} else if (loaderType == LoaderType.WORD_LOADER) {
			initScreen(activity);
			return new WordLoader(activity);
		} else
			return null;
	}

	private void initScreen(Activity activity) {
		activity.setContentView(R.layout.loading_game);
		// update the panel first
		WordwiseUtils.updateGameTopPanel(activity);

		progress = (ProgressBar) activity.findViewById(R.id.progress_bar);
		loadingFailed = (LinearLayout) activity
				.findViewById(R.id.loadingFailed);
		loadingFailedText = (TextView) activity
				.findViewById(R.id.loadingFailedText);
		retryButton = (Button) activity.findViewById(R.id.retryButton);
		nextGameButton = (Button) activity.findViewById(R.id.nextGameButton);
		loading = (LinearLayout) activity.findViewById(R.id.loading);

		progress.setVisibility(View.VISIBLE);
	}

	public void loadFailed(String failureText) {
		// removed loading indeterminate and show loading failed error
		loading.setVisibility(View.GONE);
		loadingFailed.setVisibility(View.VISIBLE);
		loadingFailedText.setVisibility(View.VISIBLE);
		retryButton.setVisibility(View.VISIBLE);
		nextGameButton.setVisibility(View.VISIBLE);
		loadingFailedText.setText(failureText);
	}

	/**
	 * Checks whether word loading was successful, shows error if it wasn't
	 *
	 * @return true if successful, false otherwise
	 */
	public boolean wordLoadSuccessfulOrShowError(Activity activity,
			List<DTOWord> words) {
		String gameLoadFailText;
		if (words == null) {
			gameLoadFailText = activity.getResources().getString(
					R.string.fail_game_load);
			loadFailed(gameLoadFailText);
			return false;
		} else if (words.size() < GameManagerContainer.getGameManager()
				.NumberOfWordsNeeded()) {
			gameLoadFailText = activity.getResources().getString(
					R.string.fail_insufficient_words_on_server);
			loadFailed(gameLoadFailText);
			return false;
		}
		return true;
	}

	/**
	 * Checks whether translation loading was successful, shows error if it
	 * wasn't
	 *
	 * @return true if successful, false otherwise
	 */
	public boolean translationLoadSuccessfulOrShowError(Activity activity,
			List<DTOTranslation> translations) {
		String gameLoadFailText;
		if (translations == null) {
			gameLoadFailText = activity.getResources().getString(
					R.string.fail_game_load);
			loadFailed(gameLoadFailText);
			return false;
		} else if (translations.size() < GameManagerContainer.getGameManager()
				.NumberOfTranslationsNeeded()) {
			gameLoadFailText = activity.getResources().getString(
					R.string.fail_insufficient_translations_on_server);
			loadFailed(gameLoadFailText);
			return false;
		}
		return true;
	}

}


text:
package AsposeCellsExamples.TechnicalArticles;

import java.io.FileInputStream;

import com.aspose.cells.Comment;
import com.aspose.cells.CommentCollection;
import com.aspose.cells.Workbook;
import AsposeCellsExamples.Utils;

public class AddPicturetoExcelComment {
	public static void main(String[] args) throws Exception {

		// The path to the documents directory.
		String dataDir = Utils.getSharedDataDir(AddPicturetoExcelComment.class) + "TechnicalArticles/";
		// Instantiate a Workbook
		Workbook workbook = new Workbook();

		// Get a reference of comments collection with the first sheet
		CommentCollection comments = workbook.getWorksheets().get(0).getComments();

		// Add a comment to cell A1
		int commentIndex = comments.add(0, 0);
		Comment comment = comments.get(commentIndex);
		comment.setNote("First note.");
		comment.getFont().setName("Times New Roman");

		// Load/Read an image into stream
		String logo_url = dataDir + "school.jpg";

		// Creating the instance of the FileInputStream object to open the logo/picture in the stream
		FileInputStream inFile = new FileInputStream(logo_url);

		// Setting the logo/picture
		byte[] picData = new byte[inFile.available()];
		inFile.read(picData);

		// Set image data to the shape associated with the comment
		comment.getCommentShape().getFill().setImageData(picData);

		// Save the workbook
		workbook.save(dataDir + "APToExcelComment_out.xlsx");
		inFile.close();

	}
}


text:
<?php

namespace PHPCI\Plugin;

use PHPCI\Builder;
use PHPCI\Model\Build;

/**
 * Shell Plugin - Allows execute shell commands.
 * @author       Kinn Coelho Julião <kinncj@gmail.com>
 * @package      PHPCI
 * @subpackage   Plugins
 */
class Shell implements \PHPCI\Plugin
{
    /**
     * @var \PHPCI\Builder
     */
    protected $phpci;

    /**
     * @var \PHPCI\Model\Build
     */
    protected $build;

    protected $args;

    /**
     * @var string[] $commands The commands to be executed
     */
    protected $commands = array();

    public function __construct(Builder $phpci, Build $build, array $options = array())
    {
        $this->phpci = $phpci;
        $this->build = $build;

        if (isset($options['command'])) {
            // Keeping this for backwards compatibility, new projects should use interpolation vars.
            $options['command'] = str_replace("%buildpath%", $this->phpci->buildPath, $options['command']);
            $this->commands = array($options['command']);
            return;
        }

        /*
         * Support the new syntax:
         *
         * shell:
         *     - "cd /www"
         *     - "rm -f file.txt"
         */
        if (is_array($options)) {
            $this->commands = $options;
        }
    }

    /**
     * Runs the shell command.
     */
    public function execute()
    {
        if (!defined('ENABLE_SHELL_PLUGIN') || !ENABLE_SHELL_PLUGIN) {
            throw new \Exception('The shell plugin is not enabled.');
        }

        $success = true;

        foreach ($this->commands as $command) {
            $command = $this->phpci->interpolate($command);

            if (!$this->phpci->executeCommand($command)) {
                $success = false;
            }
        }

        return $success;
    }
}


text:
import 'aurelia-polyfills';
import {
  PLATFORM
} from 'aurelia-pal';
import {
  initialize
} from 'aurelia-pal-browser';

/**
 * Manually bootstraps an application.
 * @param configure A callback which passes an Aurelia instance to the developer to manually configure and start up the app.
 * @return A Promise that completes when configuration is done.
 */
export declare function bootstrap(configure: Function): Promise<void>;


text:
package org.apache.sysml.runtime.compress.cocode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.sysml.runtime.compress.cocode.PlanningCoCoder.GroupableColInfo;
import org.apache.sysml.runtime.util.SortUtils;

/**
 * Column group partitioning with bin packing heuristic.
 *
 */
public class ColumnGroupPartitionerBinPacking extends ColumnGroupPartitioner
{
	private static final boolean FIRST_FIT_DEC = true;
	private static final int MAX_COL_PER_GROUP = Integer.MAX_VALUE;

	//we use a constant partition size (independent of the number of rows
	//in order to ensure constant compression speed independent of blocking)
	public static double BIN_CAPACITY = 0.000032; //higher values, more grouping

	@Override
	public List<List<Integer>> partitionColumns(List<Integer> groupCols, HashMap<Integer, GroupableColInfo> groupColsInfo)
	{
		//obtain column weights
		int[] items = new int[groupCols.size()];
		double[] itemWeights = new double[groupCols.size()];
		for( int i=0; i<groupCols.size(); i++ ) {
			int col = groupCols.get(i);
			items[i] = col;
			itemWeights[i] = groupColsInfo.get(col).cardRatio;
		}

		//sort items (first fit decreasing)
		if( FIRST_FIT_DEC ) {
			SortUtils.sortByValue(0, items.length, itemWeights, items);
			ArrayUtils.reverse(items);
			ArrayUtils.reverse(itemWeights);
		}

		//partition columns via bin packing
		return packFirstFit(items, itemWeights);
	}

	/**
	 * NOTE: upper bound is 17/10 OPT
	 *
	 * @param items the items in terms of columns
	 * @param itemWeights the weights of the items
	 * @return
	 */
	private static List<List<Integer>> packFirstFit(int[] items, double[] itemWeights)
	{
		List<List<Integer>> bins = new ArrayList<>();
		List<Double> binWeights = new ArrayList<>();

		for( int i = 0; i < items.length; i++ ) {
			//add to existing bin
			boolean assigned = false;
			for( int j = 0; j < bins.size(); j++ ) {
				double newBinWeight = binWeights.get(j)-itemWeights[i];
				if( newBinWeight >= 0 && bins.get(j).size() < MAX_COL_PER_GROUP-1 ){
					bins.get(j).add(items[i]);
					binWeights.set(j, newBinWeight);
					assigned = true; break;
				}
			}

			//create new bin at end of list
			if( !assigned ) {
				bins.add(new ArrayList<>(Arrays.asList(items[i])));
				binWeights.add(BIN_CAPACITY-itemWeights[i]);
			}
		}

		return bins;
	}
}


text:
package org.yigou.utils;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}


text:
package junium.selenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebElementsContainer {
    protected WebDriver Driver;
    protected WebDriverWait Wait;

    public WebElementsContainer(WebDriver driver,WebDriverWait wait){
        Driver = driver;
        Wait = wait;
    }
}


text:
============================
Amazon CloudFront Signed URL
============================

Signing CloudFront URLs for Private Distributions
-------------------------------------------------

Signed URLs allow you to provide users access to your private content. A signed
URL includes additional information (e.g., expiration time) that gives you more
control over access to your content. This additional information appears in a
policy statement, which is based on either a canned policy or a custom policy.
For information about how to set up private distributions and why you need to
sign URLs, please read the `Serving Private Content through CloudFront section
<http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html>`_
of the CloudFront Developer Guide.

.. note:

    You must have the OpenSSL extension installed in you PHP environment in
    order to sign CloudFront URLs.

You can sign a URL using the CloudFront client in the SDK. First you must
create a ``CloudFrontClient`` object.

.. code-block:: php

    <?php

    $cloudFront = new Aws\CloudFront\CloudFrontClient([
        'region'  => 'us-west-2',
        'version' => '2014-11-06'
    ]);

You can sign a CloudFront URL for a video resource using either a canned or
custom policy.

.. code-block:: php

    // Setup parameter values for the resource
    $streamHostUrl = 'rtmp://example-distribution.cloudfront.net';
    $resourceKey = 'videos/example.mp4';
    $expires = time() + 300;

    // Create a signed URL for the resource using the canned policy
    $signedUrlCannedPolicy = $cloudFront->getSignedUrl([
        'url'         => $streamHostUrl . '/' . $resourceKey,
        'expires'     => $expires,
        'private_key' => '/path/to/your/cloudfront-private-key.pem',
        'key_pair_id' => '<cloudfront key pair id>'
    ]);

To use a custom policy, provide the ``policy`` key instead of ``expires``.

.. code-block:: php

    $customPolicy = <<<POLICY
    {
        "Statement": [
            {
                "Resource": "{$resourceKey}",
                "Condition": {
                    "IpAddress": {"AWS:SourceIp": "{$_SERVER['REMOTE_ADDR']}/32"},
                    "DateLessThan": {"AWS:EpochTime": {$expires}}
                }
            }
        ]
    }
    POLICY;

    // Create a signed URL for the resource using a custom policy
    $signedUrlCustomPolicy = $cloudFront->getSignedUrl(array(
        'url'    => $streamHostUrl . '/' . $resourceKey,
        'policy' => $customPolicy,
        'private_key' => '/path/to/your/cloudfront-private-key.pem',
        'key_pair_id' => '<cloudfront key pair id>'
    ));

The form of the signed URL is actually different depending on if the URL you
are signing is using the "http" or "rtmp" scheme. In the case of "http", the
full, absolute URL is returned. For "rtmp", only the relative URL is returned
for your convenience, because some players require the host and path to be
provided as separate parameters.

The following is an example of how you could use the signed URL to construct a
web page displaying a video using `JWPlayer <http://www.longtailvideo.com/jw-player/>`_.
The same type of technique would apply to other players like `FlowPlayer <http://flowplayer.org/>`_,
but will require different client-side code.

.. code-block:: html

        <title>Amazon CloudFront Streaming Example</title>

The canned policy video will be here.


text:
/* $Id: assert.h $ */
/** @file
 * IPRT - Internal RTAssert header
 */

/*
 * Copyright (C) 2009-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

#ifndef ___internal_assert_h
#define ___internal_assert_h

#include <iprt/types.h>

RT_C_DECLS_BEGIN

#ifdef IN_RING0

/**
 * Print the 1st part of an assert message to whatever native facility is best
 * fitting.
 *
 * @param   pszExpr     Expression. Can be NULL.
 * @param   uLine       Location line number.
 * @param   pszFile     Location file name.
 * @param   pszFunction Location function name.
 */
DECLHIDDEN(void) rtR0AssertNativeMsg1(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction);

/**
 * Print the 2nd (optional) part of an assert message to whatever native
 * facility is best fitting.
 *
 * @param   fInitial    Whether it's the initial (true) or an additional (false)
 *                      message.
 * @param   pszFormat   Printf like format string.
 * @param   va          Arguments to that string.
 */
DECLHIDDEN(void) rtR0AssertNativeMsg2V(bool fInitial, const char *pszFormat, va_list va);

#endif

RT_C_DECLS_END

#endif


text:
package com.google.errorprone.bugpatterns;

import static org.junit.Assert.assertThrows;

import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.annotations.DoNotCall;
import java.sql.Date;
import java.sql.Time;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** {@link DoNotCallChecker}Test */
@SuppressWarnings("DoNotCall")
@RunWith(JUnit4.class)
public class DoNotCallCheckerTest {

  private final CompilationTestHelper testHelper =
      CompilationTestHelper.newInstance(DoNotCallChecker.class, getClass());

  @Test
  public void positive() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "class Test {",
            "  @DoNotCall(\"satisfying explanation\") final void f() {}",
            "  @DoNotCall final void g() {}",
            "  void m() {",
            "    // BUG: Diagnostic contains:",
            "    // This method should not be called: satisfying explanation",
            "    f();",
            "    // BUG: Diagnostic contains:",
            "    // This method should not be called, see its documentation for details",
            "    g();",
            "    // BUG: Diagnostic contains:",
            "    Runnable r = this::g;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void positiveWhereDeclaredTypeIsSuper() {
    testHelperWithImmutableList()
        .addSourceLines(
            "Test.java",
            "import java.util.List;",
            "class Test {",
            "  void foo() {",
            "    List<Integer> xs = ImmutableList.of();",
            "    // BUG: Diagnostic contains:",
            "    xs.add(1);",
            "    xs.get(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void positiveWhereDeclaredTypeIsSuper_butAssignedMultipleTimes() {
    testHelperWithImmutableList()
        .addSourceLines(
            "Test.java",
            "import java.util.List;",
            "class Test {",
            "  void foo() {",
            "    List<Integer> xs;",
            "    if (hashCode() == 0) {",
            "      xs = ImmutableList.of();",
            "    } else {",
            "      xs = ImmutableList.of();",
            "    }",
            "    // BUG: Diagnostic contains:",
            "    xs.add(1);",
            "    xs.get(1);",
            "  }",
            "}")
        .doTest();
  }

  private CompilationTestHelper testHelperWithImmutableList() {
    // Stub out an ImmutableList with the annotations we need for testing.
    return testHelper
        .addSourceLines(
            "ImmutableCollection.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "import java.util.List;",
            "abstract class ImmutableCollection<T> implements java.util.Collection<T> {",
            "  @DoNotCall @Override public final boolean add(T t) { throw new"
                + " UnsupportedOperationException(); }",
            "}")
        .addSourceLines(
            "ImmutableList.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "import java.util.List;",
            "abstract class ImmutableList<T> extends ImmutableCollection<T> implements List<T> {",
            "  public static <T> ImmutableList<T> of() {",
            "    return null;",
            "  }",
            "}");
  }

  @Test
  public void positiveWhereDeclaredTypeIsSuper_butNotAssignedOnce() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.common.collect.ImmutableList;",
            "import java.util.ArrayList;",
            "import java.util.List;",
            "class Test {",
            "  void foo() {",
            "    List<Integer> xs;",
            "    if (true) {",
            "      xs = ImmutableList.of();",
            "    } else {",
            "      xs = new ArrayList<>();",
            "      xs.add(2);",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void concreteFinal() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public class Test {",
            "  // BUG: Diagnostic contains: should be final",
            "  @DoNotCall public void f() {}",
            "  @DoNotCall public final void g() {}",
            "}")
        .doTest();
  }

  @Test
  public void requiredOverride() {
    testHelper
        .addSourceLines(
            "A.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public interface A {",
            "  @DoNotCall public void f();",
            "}")
        .addSourceLines(
            "B.java",
            "public class B implements A {",
            "  // BUG: Diagnostic contains: overrides f in A which is annotated",
            "  @Override public void f() {}",
            "}")
        .doTest();
  }

  @Test
  public void annotatedOverride() {
    testHelper
        .addSourceLines(
            "A.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public interface A {",
            "  @DoNotCall public void f();",
            "}")
        .addSourceLines(
            "B.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public class B implements A {",
            "  @DoNotCall @Override public final void f() {}",
            "}")
        .doTest();
  }

  // The interface tries to make Object#toString @DoNotCall, and because
  // the declaration in B is implicit it doesn't get checked.
  // In practice, making default Object methods @DoNotCall isn't super
  // useful - typically users interface with the interface directly
  // (e.g. Hasher) or there's an override that has unwanted behaviour (Localizable).
  // TODO(cushon): check class declarations for super-interfaces that do this?
  @Test
  public void interfaceRedeclaresObjectMethod() {
    testHelper
        .addSourceLines(
            "I.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public interface I {",
            "  @DoNotCall public String toString();",
            "}")
        .addSourceLines(
            "B.java", //
            "public class B implements I {",
            "}")
        .addSourceLines(
            "Test.java", //
            "public class Test {",
            "  void f(B b) {",
            "    b.toString();",
            "    I i = b;",
            "    // BUG: Diagnostic contains:",
            "    i.toString();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void finalClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public final class Test {",
            "  @DoNotCall public void f() {}",
            "}")
        .doTest();
  }

  @Test
  public void privateMethod() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.errorprone.annotations.DoNotCall;",
            "public final class Test {",
            "  // BUG: Diagnostic contains: private method",
            "  @DoNotCall private void f() {}",
            "}")
        .doTest();
  }

  /** Test class containing a method annotated with @DNC. */
  public static final class DNCTest {
    @DoNotCall
    public static void f() {}

    private DNCTest() {}
  }

  @Test
  public void noDNConClasspath() {
    testHelper
        .addSourceLines(
            "Test.java",
            "class Test {",
            "  void m() {",
            "    // BUG: Diagnostic contains: This method should not be called",
            "    com.google.errorprone.bugpatterns.DoNotCallCheckerTest.DNCTest.f();",
            "  }",
            "}")
        .withClasspath(DNCTest.class, DoNotCallCheckerTest.class)
        .doTest();
  }

  @Test
  public void thirdParty() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import org.junit.Assert;",
            "public class Test {",
            "  public void foo() {",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    Assert.assertEquals(2.0, 2.0);",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    Assert.assertEquals(\"msg\", 2.0, 2.0);",
            // These are OK since they pass a tolerance
            "    Assert.assertEquals(2.0, 2.0, 0.01);",
            "    Assert.assertEquals(\"msg\", 2.0, 2.0, 0.01);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlDate_toInstant() {
    assertThrows(UnsupportedOperationException.class, () -> new Date(1234567890L).toInstant());
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Date;",
            "import java.time.Instant;",
            "public class TestClass {",
            "  public void badApis(Date date) {",
            "    // BUG: Diagnostic contains: toLocalDate()",
            "    Instant instant = date.toInstant();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlDate_timeGetters() {
    Date date = new Date(1234567890L);
    assertThrows(IllegalArgumentException.class, () -> date.getHours());
    assertThrows(IllegalArgumentException.class, () -> date.getMinutes());
    assertThrows(IllegalArgumentException.class, () -> date.getSeconds());
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Date;",
            "public class TestClass {",
            "  public void badApis(Date date) {",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int hour = date.getHours();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int mins = date.getMinutes();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int secs = date.getSeconds();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlDate_timeSetters() {
    Date date = new Date(1234567890L);
    assertThrows(IllegalArgumentException.class, () -> date.setHours(1));
    assertThrows(IllegalArgumentException.class, () -> date.setMinutes(1));
    assertThrows(IllegalArgumentException.class, () -> date.setSeconds(1));
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Date;",
            "public class TestClass {",
            "  public void badApis(Date date) {",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    date.setHours(1);",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    date.setMinutes(1);",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    date.setSeconds(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlDate_staticallyTypedAsJavaUtilDate() {
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.time.Instant;",
            "import java.util.Date;",
            "public class TestClass {",
            "  public void badApis() {",
            "    Date date = new java.sql.Date(1234567890L);",
            "    Instant instant = date.toInstant();",
            "    int hour = date.getHours();",
            "    int mins = date.getMinutes();",
            "    int secs = date.getSeconds();",
            "    date.setHours(1);",
            "    date.setMinutes(1);",
            "    date.setSeconds(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlTime_toInstant() {
    assertThrows(UnsupportedOperationException.class, () -> new Time(1234567890L).toInstant());
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Time;",
            "import java.time.Instant;",
            "public class TestClass {",
            "  public void badApis(Time time) {",
            "    // BUG: Diagnostic contains: toLocalTime()",
            "    Instant instant = time.toInstant();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlTime_dateGetters() {
    Time time = new Time(1234567890L);
    assertThrows(IllegalArgumentException.class, () -> time.getYear());
    assertThrows(IllegalArgumentException.class, () -> time.getMonth());
    assertThrows(IllegalArgumentException.class, () -> time.getDay());
    assertThrows(IllegalArgumentException.class, () -> time.getDate());
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Time;",
            "public class TestClass {",
            "  public void badApis(Time time) {",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int year = time.getYear();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int month = time.getMonth();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int day = time.getDay();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    int date = time.getDate();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlTime_dateSetters() {
    Time time = new Time(1234567890L);
    assertThrows(IllegalArgumentException.class, () -> time.setYear(1));
    assertThrows(IllegalArgumentException.class, () -> time.setMonth(1));
    assertThrows(IllegalArgumentException.class, () -> time.setDate(1));
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.sql.Time;",
            "public class TestClass {",
            "  public void badApis(Time time) {",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    time.setYear(1);",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    time.setMonth(1);",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    time.setDate(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void javaSqlTime_staticallyTypedAsJavaUtilDate() {
    testHelper
        .addSourceLines(
            "TestClass.java",
            "import java.time.Instant;",
            "import java.util.Date;",
            "public class TestClass {",
            "  public void badApis() {",
            "    Date time = new java.sql.Time(1234567890L);",
            "    Instant instant = time.toInstant();",
            "    int year = time.getYear();",
            "    int month = time.getMonth();",
            "    int date = time.getDate();",
            "    int day = time.getDay();",
            "    time.setYear(1);",
            "    time.setMonth(1);",
            "    time.setDate(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void readLock_newCondition() {
    assertThrows(
        UnsupportedOperationException.class,
        () -> new ReentrantReadWriteLock().readLock().newCondition());
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.util.concurrent.locks.ReentrantReadWriteLock;",
            "public class Test {",
            "  public void foo() {",
            "    ReentrantReadWriteLock.ReadLock lock = new ReentrantReadWriteLock().readLock();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    lock.newCondition();",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void threadLocalRandom_setSeed() {
    assertThrows(
        UnsupportedOperationException.class, () -> ThreadLocalRandom.current().setSeed(42));
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.util.concurrent.ThreadLocalRandom;",
            "public class Test {",
            "  public void foo() {",
            "    ThreadLocalRandom random = ThreadLocalRandom.current();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    random.setSeed(42L);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void memberReferencesOnThirdPartyMethods() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.util.concurrent.ThreadLocalRandom;",
            "import java.util.Optional;",
            "public class Test {",
            "  public void foo(Optional<Long> x) {",
            "    ThreadLocalRandom random = ThreadLocalRandom.current();",
            "    // BUG: Diagnostic contains: DoNotCall",
            "    x.ifPresent(random::setSeed);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void typeArgs_dontCrash() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.util.List;",
            "class Test<T extends java.util.Collection<Object>> {",
            "  @Override public boolean equals(Object o) {",
            "    T foo = (T) o;",
            "    return foo.equals(1);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void positive_getSimpleName_refactoredToGetClassName() {
    testHelper
        .addSourceLines(
            "Test.java",
            "class Test{",
            " void f() {",
            "   try {",
            "     throw new Exception();",
            "   } catch (Exception ex) {",
            "     // BUG: Diagnostic contains: getClassName",
            "     ex.getStackTrace()[0].getClass().getSimpleName();",
            "   }",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_stackWalkerGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "class Test{",
            " void f(StackWalker w) {",
            "   // BUG: Diagnostic contains: getCallerClass",
            "   w.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_stackFrameGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.StackWalker.StackFrame;",
            "class Test{",
            " void f(StackFrame f) {",
            "   // BUG: Diagnostic contains: getClassName",
            "   f.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_constructorGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.reflect.Constructor;",
            "class Test{",
            " void f(Constructor<?> c) {",
            "   // BUG: Diagnostic contains: getDeclaringClass",
            "   c.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_fieldGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.reflect.Field;",
            "class Test{",
            " void f(Field f) {",
            "   // BUG: Diagnostic contains: getDeclaringClass",
            "   f.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_methodGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.reflect.Method;",
            "class Test{",
            " void f(Method m) {",
            "   // BUG: Diagnostic contains: getDeclaringClass",
            "   m.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_beanDescriptorGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.beans.BeanDescriptor;",
            "class Test{",
            " void f(BeanDescriptor b) {",
            "   // BUG: Diagnostic contains: getBeanClass",
            "   b.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_lockInfoGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.management.LockInfo;",
            "import java.lang.management.MonitorInfo;",
            "class Test{",
            " void f(LockInfo l, MonitorInfo m) {",
            "   // BUG: Diagnostic contains: getClassName",
            "   l.getClass();",
            "   // BUG: Diagnostic contains: getClassName",
            "   m.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_parameterizedTypeGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import java.lang.reflect.ParameterizedType;",
            "class Test{",
            " void f(ParameterizedType t) {",
            "   // BUG: Diagnostic contains: getRawType",
            "   t.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_classInfoGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.common.reflect.ClassPath.ClassInfo;",
            "class Test{",
            " void f(ClassInfo i) {",
            "   // BUG: Diagnostic contains: getName",
            "   i.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_typeTokenGetClass() {
    testHelper
        .addSourceLines(
            "Test.java",
            "import com.google.common.reflect.TypeToken;",
            "class Test{",
            " void f(TypeToken<?> t) {",
            "   // BUG: Diagnostic contains: getRawType",
            "   t.getClass();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void positive_threadRun() {
    testHelper
        .addSourceLines(
            "Test.java",
            "class Test {",
            " void f(Thread t) {",
            "   // BUG: Diagnostic contains: start",
            "   t.run();",
            " }",
            "}")
        .doTest();
  }

  @Test
  public void negative_threadSuperRun() {
    testHelper
        .addSourceLines(
            "Test.java",
            "class Test extends Thread {",
            " @Override public void run() {",
            "   super.run();",
            " }",
            "}")
        .doTest();
  }
}


text:
//  Created by Andrey Ostanin on 09.02.17.
//  Copyright © 2017 Andrey Ostanin. All rights reserved.

#import "XZCommon.h"

@interface XZEventHistoryElement : NSObject
/**
 *  Data that should be saved
 */
@property(nonatomic,strong,readonly)id<NSObject,NSCopying,NSCoding> data;

/**
 *  Timestamp when data was saved
 */
@property(nonatomic,strong,readonly)NSDate *timestamp;

/**
 *  Designated initializer
 *
 *  @param data data that should be saved in history
 *
 *  @return initialized history element
 */
- (instancetype)initWithData:(id<NSObject,NSCopying,NSCoding>)data NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Writ. 6: 880 (1919)

#### Original name
Polyporus mollitextus Lloyd, 1919

### Remarks
null


text:
DROP TABLE `commands`;
DROP TABLE `users_devices`;
DROP TABLE `users`;
DROP TABLE `devices`;
DROP TABLE `positions`;


text:
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
# Security Vulnerability Disclosure

Apache NiFi welcomes the responsible reporting of security vulnerabilities. The NiFi team believes that working with skilled security researchers across the globe is crucial in identifying weaknesses in any technology. If you believe you've found a security issue in our product or service, we encourage you to notify us. We will work with you to resolve the issue promptly.

## Table of Contents

* [Disclosure Policy](#disclosure-policy)
* [Exclusions](#exclusions)
* [Reporting Methods](#reporting-methods)
* [Publishing](#publishing)

## Disclosure Policy

* Let us know as soon as possible upon discovery of a potential security issue, and we'll make every effort to quickly resolve the issue.
* Provide us a reasonable amount of time to resolve the issue before any disclosure to the public or a third-party.
* Make a good faith effort to avoid privacy violations, destruction of data, and interruption or degradation of our service. Only interact with accounts you own or with explicit permission of the account holder.

## Exclusions

While researching, we'd like to ask you to refrain from:
* Denial of service
* Spamming
* Social engineering (including phishing) of Apache NiFi staff or contractors
* Any physical attempts against Apache NiFi property or data centers

## Reporting Methods

NiFi accepts reports in multiple ways:

* Send an email to [security@nifi.apache.org](mailto:security@nifi.apache.org). This is a private list monitored by the [PMC](https://nifi.apache.org/people.html). For sensitive disclosures, the GPG key fingerprint is *1230 3BB8 1F22 E11C 8725 926A AFF2 B368 23B9 44E9*.
* NiFi has a [HackerOne](https://hackerone.com/apache_nifi) project page. HackerOne provides a triaged process for researchers and organizations to collaboratively report and resolve security vulnerabilities.

## Publishing

Apache NiFi follows the [ASF Project Security For Committers](https://www.apache.org/security/committers.html) policy. Thus, any vulnerability is not disclosed by the project until a released version which mitigates the issue is available for download. Once this release is available, the issue is fully documented in the following locations:
* An email is sent to the same addresses as the release announcement (dev@nifi.apache.org, users@nifi.apache.org, announce@apache.org), security@nifi.apache.org, and oss-security@lists.openwall.com
* The [Mitre Common Vulnerabilities and Exposures (CVE) database](https://cveform.mitre.org/)
* The [Apache NiFi Security Page](https://nifi.apache.org/security.html)

Thank you for helping keep Apache NiFi and our users safe!


text:
layout: page
title: "The Cultural Evolution of Chess Strategy"
subheadline:
teaser:
header:
    image_fullwidth: "header-chess.jpg"
    caption: 'A game of Chess, Bogota'
#
# Metainformation & Customization
#
sidebar:
comments: true
breadcrumb: true
show_meta: false
meta_title:
meta_description:
permalink:
tawkto: true               # Enable tawk.to-Service › More › _config.yml
---

Recently, Beheim et al. [1] introduced the idea of using archived records
of movement patterns in the game of Go to study the cultural evolutionary
dynamics of gaming strategy. Until the introduction of this approach, evidence
for cultural evolution was based primarily on mathematical models
[2, 3], simulation [4], short-term experimental evidence [5, 6, 7], and verbal
arguments [8, 9]. Quantitative analysis of cultural evolution through
social and prestige-biased learning in natural environments was hampered
by the lack of finely-resolved, individual-level data on human behavior over
long courses of time. Interestingly, strategy games such as Go and Chess
have risen to such a level of cultural importance, that the project of voluntarily
recording massive amounts of longitudinal data has been completed
already by game aficionados. These data permit the application of annually-resolved
time-series analysis to the evolutionary dynamics of game playing
behavior, and allow for the effects of individual learning, social learning, and
prestige-biased learning to be analyzed in a unied framework. This paper
will examine evidence regarding the use of these learning strategies in the
selection of Chess opening moves, over the period of time from 1975 to 2013,
in a data set containing over 1.1 million games played by more than 54,000
professional Chess players.

Paper coming soon.

Bibtex:
```
Coming Soon.
```


text:
require_relative 'abstract_store'

class Caching
  class MemoryStore < AbstractStore
    def initialize
      self.store = {}
    end

    def self.current
      self.instance ||= new
    end

    def get(key)
      store[key]
    end

    def set(key, value)
      store[key] = value
    end

    def clear
      store.clear
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme.TransNav" parent="AppTheme" />
</resources>


text:
'use strict';

describe('Service: charStage', function () {

  // load the service's module
  beforeEach(module('tbsApp'));

  // instantiate service
  var charStage;
  beforeEach(inject(function (_charStage_) {
    charStage = _charStage_;
  }));

  it('should do something', function () {
    expect(!!charStage).toBe(true);
  });

});


text:
package com.intellij.ide.util.projectWizard.importSources;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public abstract class DetectedProjectRoot {
  private final File myDirectory;

  protected DetectedProjectRoot(@NotNull File directory) {
    myDirectory = directory;
  }

  public File getDirectory() {
    return myDirectory;
  }

  @NotNull
  public abstract String getRootTypeName();

  @Nullable
  public DetectedProjectRoot combineWith(@NotNull DetectedProjectRoot root) {
    return null;
  }

  public boolean canContainRoot(@NotNull DetectedProjectRoot root) {
    return true;
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jsoup.parser;

/**
 *
 * @author peer.bridge
 */
enum TokenType {
        Doctype,
        StartTag,
        EndTag,
        Comment,
        Character,
        EOF
    }


text:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Advertisements;

public class AdsChest : MonoBehaviour
{
    public const int COINS_RANGE = 50;
    public const int CRYSTALS_RANGE = 75;
    public const int ITEMS_RANGE = 100;

    public const int MIN_COIN_RANGE = 50;
    public const int MID_COIN_RANGE = 70;
    public const int BIG_COIN_RANGE = 100;

    public const int MIN_CRYSTAL_RANGE = 65;
    public const int MID_CRYSTAL_RANGE = 85;
    public const int BIG_CRYSTAL_RANGE = 100;

    public const int ITEMS_COUNT = 6;

    public const int HEAL_NUM = 0;
    public const int AMMO_NUM = 1;
    public const int IMMORTAL_NUM = 2;
    public const int DAMAGE_NUM = 3;
    public const int SPEED_NUM = 4;
    public const int TIME_NUM = 5;

    float currentTime;

    [SerializeField]
    Sprite[] lootArray;
    [SerializeField]
    public SpriteRenderer loot;
    [SerializeField]
    Sprite openChest;
    bool isOpened;
    bool isRewardCollected;
    bool musicWasPlaying;

    public int[] itemsDropRate;
    public int[] itemsStorage;

    float memTimeScale;

    public void Start()
    {
        isOpened = false;
        isRewardCollected = false;

        itemsDropRate = new int[ITEMS_COUNT];
        itemsStorage = new int[100];

        if (!PlayerPrefs.HasKey("LevelAdsChest"))
        {
            PlayerPrefs.SetInt("LevelAdsChest", 0);
        }

        SetItems();
    }

    private void Update()
    {
        if (isOpened && !isRewardCollected)
        {
            if (AdsManager.Instance.isRewardVideoWatched)
            {
                AdsManager.Instance.isRewardVideoWatched = false;
                GetComponent<BoxCollider2D>().enabled = false;
                isRewardCollected = true;

                Randomize();
                GetComponent<SpriteRenderer>().sprite = openChest;
                loot.gameObject.SetActive(true);

                AppMetrica.Instance.ReportEvent("#ADS_CHEST opened in " + GameManager.currentLvl);
                DevToDev.Analytics.CustomEvent("#ADS_CHEST opened in " + GameManager.currentLvl);
            }
            if (musicWasPlaying)
            {
                SoundManager.PlayRandomMusic("kid_music", true);

                SoundManager.MuteMusic(false);
            }
            Player.Instance.mobileInput = 0;
            Player.Instance.ChangeState(new PlayerIdleState());
        }
        else
        {
            if (!UI.Instance.controlsUI.activeInHierarchy)
            {
                EnableControls(true);
            }
        }
    }

    public void Randomize()
    {
        if (PlayerPrefs.GetInt("LevelAdsChest") == 0)
        {
            PlayerPrefs.SetInt("LevelAdsChest", 1);

            loot.sprite = lootArray[1];
            AddCrystals(4);
        }
        else
        {
            int random = UnityEngine.Random.Range(1, 100);

            if (random <= COINS_RANGE)
            {
                RandomizeCoins();
            }
            if (random > COINS_RANGE && random <= CRYSTALS_RANGE)
            {
                RandomizeCrystals();
            }
            if (random > CRYSTALS_RANGE && random <= ITEMS_RANGE)
            {
                RandomizeItems();
            }
        }
    }

    void RandomizeCoins()
    {
        int random = UnityEngine.Random.Range(1, 100);

        if (random <= MIN_COIN_RANGE)
        {
            loot.sprite = lootArray[0];
            AddCoins(25);
        }
        if (random > MIN_COIN_RANGE && random <= MID_COIN_RANGE)
        {
            loot.sprite = lootArray[0];
            AddCoins(50);
        }
        if (random > MID_COIN_RANGE && random <= BIG_COIN_RANGE)
        {
            loot.sprite = lootArray[0];
            AddCoins(100);
        }
    }

    void RandomizeCrystals()
    {
        int random = UnityEngine.Random.Range(1, 100);

        if (random <= MIN_CRYSTAL_RANGE)
        {
            loot.sprite = lootArray[1];
            AddCrystals(2);
        }
        if (random > MIN_CRYSTAL_RANGE && random <= MID_CRYSTAL_RANGE)
        {
            loot.sprite = lootArray[1];
            AddCrystals(3);
        }
        if (random > MID_CRYSTAL_RANGE && random <= BIG_CRYSTAL_RANGE)
        {
            loot.sprite = lootArray[1];
            AddCrystals(4);
        }
    }

    void RandomizeItems()
    {
        int random = UnityEngine.Random.Range(1, 100);

        switch (itemsStorage[random])
        {
            case 0:
                AddItem(Inventory.HEAL, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            case 1:
                AddItem(Inventory.AMMO, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            case 2:
                AddItem(Inventory.IMMORTAL_BONUS, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            case 3:
                AddItem(Inventory.DAMAGE_BONUS, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            case 4:
                AddItem(Inventory.SPEED_BONUS, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            case 5:
                AddItem(Inventory.TIME_BONUS, itemsStorage[random] + 2);//2 - позиция первого итема в массиве lootArray
                break;

            default:
                break;
        }
    }

    void AddCoins(int value)
    {
        loot.gameObject.GetComponentInChildren<TextMesh>().text = value.ToString();
        GameManager.collectedCoins += value;
        PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + value);
    }

    void AddCrystals(int value)
    {
        loot.gameObject.GetComponentInChildren<TextMesh>().text = value.ToString();
        PlayerPrefs.SetInt("Crystals", PlayerPrefs.GetInt("Crystals") + value);
        if (SceneManager.GetActiveScene().name.Contains("Level"))
        {
            GameManager.crystalTxt.text = PlayerPrefs.GetInt("Crystals").ToString();
        }
    }

    void AddItem(string itemName, int itemNum)
    {
        loot.gameObject.GetComponentInChildren<TextMesh>().text = "+1";
        loot.sprite = lootArray[itemNum];
        Inventory.Instance.AddItem(itemName, 1);
    }

    public void SetItems()
    {
        SetItemsWeights();
        SetItemsDropRate();
    }

    public void SetItemsWeights()
    {
        itemsDropRate[HEAL_NUM] = 30;
        itemsDropRate[AMMO_NUM] = 30;
        itemsDropRate[IMMORTAL_NUM] = 5;
        itemsDropRate[DAMAGE_NUM] = 10;
        itemsDropRate[SPEED_NUM] = 15;
        itemsDropRate[TIME_NUM] = 10;
    }

    public void SetItemsDropRate()
    {
        int lastItemIndex = 0;

        for (int itemNum = 0; itemNum < ITEMS_COUNT; itemNum++)//заполняем массив idшками итемов, в соответствии с их дроп-рейтом
        {
            for (int j = lastItemIndex; j < lastItemIndex + itemsDropRate[itemNum]; j++)//пишем id итема в storage столько раз, сколько его дроп-рэйт
            {
                itemsStorage[j] = itemNum;
                if (j + 1 == lastItemIndex + itemsDropRate[itemNum])
                {
                    lastItemIndex = j + 1;
                    break;
                }
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Sword"))
        {
            if (PlayerPrefs.GetInt("MusicIsOn") == 1)
            {
                musicWasPlaying = true;
                //PlayerPrefs.SetInt("MusicIsOn", 0);
                //SoundManager.MuteMusic(true);
                SoundManager.Instance.currentMusic.Stop();
            }
#if UNITY_ANDROID || UNITY_IOS
            if (Advertisement.IsReady())
            {
                isOpened = true;
                EnableControls(false);
                Player.Instance.mobileInput = 0;
                Player.Instance.ChangeState(new PlayerIdleState());
                currentTime = Time.timeScale; //--------------------------разлочим чуть позже
            }

#endif
#if UNITY_EDITOR
                AdsManager.Instance.isRewardVideoWatched = true;
#elif UNITY_ANDROID || UNITY_IOS
            AdsManager.Instance.ShowRewardedVideo();
#endif
        }
    }

    protected void EnableControls(bool switcher)
    {
        if (switcher)
        {
            UI.Instance.controlsUI.SetActive(true);
        }
        else
        {
            UI.Instance.controlsUI.SetActive(false);
        }
    }

    IEnumerator StopTime()
    {
        yield return new WaitForSeconds(1);
        Time.timeScale = 0;
    }
}